Skip to content

Commit f2779fc

Browse files
authored
Merge pull request #20 from aaditagrawal/code-quality
chore: code quality cleanup (Snow Leopard pass)
2 parents 6937e35 + c3926cc commit f2779fc

23 files changed

Lines changed: 92 additions & 226 deletions

AGENTS.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ If a tradeoff is required, choose correctness and robustness over short-term con
3030

3131
## Maintainability
3232

33-
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
33+
Long-term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
3434

3535
## Package Roles
3636

apps/desktop/src/main.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1230,7 +1230,7 @@ function registerIpcHandlers(): void {
12301230
ipcMain.handle(LOG_LIST_CHANNEL, async () => {
12311231
try {
12321232
const entries = await FS.promises.readdir(LOG_DIR);
1233-
return entries.filter((f) => f.endsWith(".log")).sort();
1233+
return entries.filter((f) => f.endsWith(".log")).toSorted();
12341234
} catch {
12351235
return [];
12361236
}

apps/server/src/ampServerManager.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,7 @@ export class AmpServerManager extends EventEmitter<{
355355
} catch (err) {
356356
throw new Error(
357357
`Failed to write to AMP stdin for session ${input.threadId}: ${err instanceof Error ? err.message : String(err)}`,
358+
{ cause: err },
358359
);
359360
}
360361

apps/server/src/codexAppServerManager.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
isCodexCliVersionSupported,
2828
parseCodexCliVersion,
2929
} from "./provider/codexCliVersion";
30+
import { createLogger } from "./logger";
3031

3132
type PendingRequestKey = string;
3233

@@ -514,6 +515,7 @@ export interface CodexAppServerManagerEvents {
514515

515516
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
516517
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
518+
private readonly logger = createLogger("codex");
517519

518520
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
519521
constructor(services?: ServiceMap.ServiceMap<never>) {
@@ -585,21 +587,21 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
585587
this.writeMessage(context, { method: "initialized" });
586588
try {
587589
const modelListResponse = await this.sendRequest(context, "model/list", {});
588-
console.log("codex model/list response", modelListResponse);
590+
this.logger.info("model/list response", { response: modelListResponse });
589591
} catch (error) {
590-
console.log("codex model/list failed", error);
592+
this.logger.warn("model/list failed", { error });
591593
}
592594
try {
593595
const accountReadResponse = await this.sendRequest(context, "account/read", {});
594-
console.log("codex account/read response", accountReadResponse);
596+
this.logger.info("account/read response", { response: accountReadResponse });
595597
context.account = readCodexAccountSnapshot(accountReadResponse);
596-
console.log("codex subscription status", {
598+
this.logger.info("subscription status", {
597599
type: context.account.type,
598600
planType: context.account.planType,
599601
sparkEnabled: context.account.sparkEnabled,
600602
});
601603
} catch (error) {
602-
console.log("codex account/read failed", error);
604+
this.logger.warn("account/read failed", { error });
603605
}
604606

605607
const normalizedModel = resolveCodexModelForAccount(

apps/server/src/geminiCliServerManager.test.ts

Lines changed: 4 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { describe, expect, it, vi, beforeEach } from "vitest";
2-
import { EventEmitter } from "node:events";
32
import { ThreadId, TurnId, type ProviderRuntimeEvent } from "@t3tools/contracts";
43

54
import { GeminiCliServerManager } from "./geminiCliServerManager";
@@ -10,42 +9,6 @@ const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
109
// Helpers to inspect spawned processes
1110
// ---------------------------------------------------------------------------
1211

13-
/** Minimal mock for ChildProcess returned by `spawn`. */
14-
function createMockChildProcess() {
15-
const stdout = new EventEmitter();
16-
const stderr = new EventEmitter();
17-
const child = Object.assign(new EventEmitter(), {
18-
stdout,
19-
stderr,
20-
stdin: { write: vi.fn() },
21-
kill: vi.fn(),
22-
pid: 12345,
23-
});
24-
return child;
25-
}
26-
27-
/** Capture spawn calls so we can inspect args & feed fake output. */
28-
function mockSpawn() {
29-
const children: ReturnType<typeof createMockChildProcess>[] = [];
30-
const spawnMock = vi.fn((_cmd: string, _args: string[]) => {
31-
const child = createMockChildProcess();
32-
children.push(child);
33-
return child;
34-
});
35-
vi.doMock("node:child_process", () => ({ spawn: spawnMock }));
36-
return { spawnMock, children };
37-
}
38-
39-
/** Feed a line of JSON to the child's stdout as if it were a readline event. */
40-
function feedStdoutLine(
41-
child: ReturnType<typeof createMockChildProcess>,
42-
json: Record<string, unknown>,
43-
): void {
44-
// Simulate readline "line" event by emitting data that includes a newline.
45-
// Since we use readline.createInterface on stdout, we emit raw data.
46-
child.stdout.emit("data", Buffer.from(JSON.stringify(json) + "\n"));
47-
}
48-
4912
// ---------------------------------------------------------------------------
5013
// Unit tests — no real gemini process
5114
// ---------------------------------------------------------------------------
@@ -234,7 +197,7 @@ describe("GeminiCliServerManager", () => {
234197

235198
const sessions = manager.listSessions();
236199
expect(sessions).toHaveLength(2);
237-
expect(sessions.map((s) => s.threadId).sort()).toEqual(["thread-1", "thread-2"]);
200+
expect(sessions.map((s) => s.threadId).toSorted()).toEqual(["thread-1", "thread-2"]);
238201
} finally {
239202
manager.stopAll();
240203
}
@@ -352,8 +315,8 @@ describe("GeminiCliServerManager JSON event mapping", () => {
352315
expect(events).toHaveLength(2);
353316
expect(events[0]?.type).toBe("content.delta");
354317
expect(events[0]?.provider).toBe("geminiCli");
355-
expect((events[0]?.payload as { delta: string }).delta).toBe("Hello, ");
356-
expect((events[0]?.payload as { streamKind: string }).streamKind).toBe("assistant_text");
318+
expect((events[0]!.payload as { delta: string }).delta).toBe("Hello, ");
319+
expect((events[0]!.payload as { streamKind: string }).streamKind).toBe("assistant_text");
357320

358321
// Both deltas must share the same itemId for proper message aggregation.
359322
expect(events[1]?.type).toBe("content.delta");
@@ -660,7 +623,7 @@ describe.skipIf(!hasGemini || process.env.RUN_GEMINI_LIVE_TESTS !== "1")(
660623

661624
// Turn should be completed successfully.
662625
const completed = events.find((e) => e.type === "turn.completed");
663-
expect((completed?.payload as { state: string }).state).toBe("completed");
626+
expect((completed!.payload as { state: string }).state).toBe("completed");
664627
} finally {
665628
manager.stopAll();
666629
}

apps/server/src/kilo/serverLifecycle.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,8 @@ export async function ensureServer(
5858
}
5959

6060
const serverPromise = spawnOrConnect(options);
61-
try {
62-
const state = await serverPromise;
63-
return { state, serverPromise };
64-
} catch (error) {
65-
// Propagate the error — the caller's finally block clears serverPromise
66-
// when this.server is still undefined, enabling retry on next call.
67-
throw error;
68-
}
61+
const state = await serverPromise;
62+
return { state, serverPromise };
6963
}
7064

7165
async function spawnOrConnect(options?: KiloProviderOptions): Promise<SharedServerState> {

apps/server/src/kilo/types.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import type {
2-
ProviderApprovalDecision,
32
ProviderRuntimeEvent,
43
ProviderSendTurnInput,
54
ProviderSession,

apps/server/src/opencode/serverLifecycle.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -57,14 +57,8 @@ export async function ensureServer(
5757
}
5858

5959
const serverPromise = spawnOrConnect(options);
60-
try {
61-
const state = await serverPromise;
62-
return { state, serverPromise };
63-
} catch (error) {
64-
// Propagate the error — the caller's finally block clears serverPromise
65-
// when this.server is still undefined, enabling retry on next call.
66-
throw error;
67-
}
60+
const state = await serverPromise;
61+
return { state, serverPromise };
6862
}
6963

7064
async function spawnOrConnect(options?: OpenCodeProviderOptions): Promise<SharedServerState> {

apps/server/src/opencode/types.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import type {
2-
ProviderApprovalDecision,
32
ProviderRuntimeEvent,
43
ProviderSendTurnInput,
54
ProviderSession,

apps/server/src/orchestration/Layers/ProviderCommandReactor.ts

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
1717

1818
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
1919
import { GitCore } from "../../git/Services/GitCore.ts";
20-
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
2120
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
2221
import { ProviderService } from "../../provider/Services/ProviderService.ts";
2322
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
@@ -75,22 +74,6 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
7574
const WORKTREE_BRANCH_PREFIX = "t3code";
7675
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
7776

78-
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
79-
const error = Cause.squash(cause);
80-
if (Schema.is(ProviderAdapterRequestError)(error)) {
81-
const detail = error.detail.toLowerCase();
82-
return (
83-
detail.includes("unknown pending approval request") ||
84-
detail.includes("unknown pending permission request")
85-
);
86-
}
87-
const message = Cause.pretty(cause);
88-
return (
89-
message.includes("unknown pending approval request") ||
90-
message.includes("unknown pending permission request")
91-
);
92-
}
93-
9477
function isTemporaryWorktreeBranch(branch: string): boolean {
9578
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
9679
}

0 commit comments

Comments
 (0)