Skip to content
Source
Sign inSign up
pingdotgg/t3code

Merge upstream pingdotgg/t3code main (v0.0.5 → v0.0.9) #668

Closedaaditagrawal(GitHub profile, opens in a new tab)wants to merge 26 commits intomain fromrefs/pull/668/headopened View on GitHub

Summary

  • Merges 34 upstream commits from pingdotgg/t3code:main into our fork
  • Resolves 16 merge conflicts across server orchestration, web components, contracts, desktop, and CI/docs files
  • Preserves all fork-specific multi-provider support (OpenCode, Copilot, Amp, GeminiCli, Kilo, Claude adapters)
  • Fixes post-merge type errors (duplicate deleteProjectScript declaration, mismatched parentheses in ChatView.tsx)

Upstream changes included

Bug fixes:

  • Fix codex binary path setting having no effect (#493)
  • Remove extra dot from working indicator (#481)
  • Fix avoid duplicating streamed assistant completion text (#465)
  • Use wss:// when page is served over HTTPS (#391)
  • Fix ChildProcess.spawn failing on Windows for .cmd shims (#495)
  • Add missing v7 key to legacy localStorage cleanup list (#594)
  • Add dismiss button to thread error banner (#588)
  • Fix native scrollbar intercepted by sidebar rail on Windows/Linux (#618)

Features & UI:

  • Plan mode UI overhaul (#596)
  • Settings in sidebar, better add project flow (#584)
  • Add delete option for project actions (#223)
  • Rename "Open PR" to "View PR" (#467)
  • Spellcheck suggestions in desktop context menu (#500)
  • Platform detection for marketing download button (#558)

Desktop:

  • Fix external link opening in desktop (#599)
  • Filesystem-friendly userData directory name (#607)
  • Intel/ARM mac fixes (#446, #641)
  • Sidebar logo alignment with macOS traffic lights (#586)

CI/Infra:

  • PR vouch workflow with trust-status labels (#602)
  • Release prep v0.0.5, v0.0.8, v0.0.9

Conflict resolution strategy

  • CI/docs files (VOUCHED.td, pr-vouch.yml, CONTRIBUTING.md): Took upstream versions
  • README.md: Merged both — kept fork content, added upstream contributing section
  • Server orchestration/provider: Kept our multi-provider logic, integrated upstream bug fixes (duplicate text prevention, Windows spawn fix)
  • Web components: Kept our provider UI, integrated upstream UX improvements (plan mode overhaul, settings flow, delete project, error dismiss)
  • Contracts: Kept our multi-provider type unions, integrated upstream plan mode schema changes

Test plan

  • bun typecheck passes (all 7 packages)
  • bun lint passes (0 errors, 14 pre-existing warnings)

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Note

Merge upstream v0.0.5→v0.0.9 and add multi‑provider adapters, model selection (Cursor/Claude Code traits), provider usage/model APIs, and UI for command palette, Ghostty terminal, accent color, and project reorder across web, server, and shared contracts

Add provider adapters and session routing for copilot, claudeCode, cursor, opencode, geminiCli, amp, and kilo, extend shared model contracts and resolution (Cursor families, Claude Code effort), expose provider listModels/getUsage via WebSocket and React Query, and update web UI with command palette, Ghostty terminal, accent color theming, provider model picker with traits, sidebar usage, thread search, and project drag‑reorder; persist project order and redact provider options in persisted/runtime events.

📍Where to Start

Start with provider adapter registration in makeProviderAdapterRegistry at apps/server/src/provider/Layers/ProviderAdapterRegistry.ts, then review shared model contracts in packages/contracts/src/model.ts and provider kind/options in packages/contracts/src/orchestration.ts.

📊 Macroscope summarized 1087311. 29 files reviewed, 51 issues evaluated, 5 issues filtered, 12 comments posted

🗂️ Filtered Issues

apps/server/src/ampServerManager.ts — 4 comments posted, 9 evaluated, 1 filtered
  • line 345: The sendTurn function constructs the user message payload using only input.input (text), completely ignoring any tool results that may be present in the input object. When the assistant initiates a tool call (tool_use), the runtime executes it and calls sendTurn with the result. By omitting these results from the JSON sent to the AMP process (hardcoding type: "text"), the assistant never receives the tool output, breaking the tool usage lifecycle. [ Out of scope (triage) ]
apps/server/src/kiloServerManager.ts — 1 comment posted, 14 evaluated, 1 filtered
  • line 703: The function readProviderListResponse fails to handle the error case of the input union type. If value is an error wrapper (e.g. { error: "Access Denied", data: undefined }), value.data is undefined, causing the code to fall through to line 703. This throws a generic Error("Kilo SDK returned an empty provider list response") instead of propagating the actual error. This swallows the underlying exception from the SDK, making debugging impossible. The function should check for and throw value.error if present. [ Cross-file consolidated ]
apps/server/src/opencodeServerManager.ts — 2 comments posted, 8 evaluated, 1 filtered
  • line 1801: The handleMessagePartUpdatedEvent function updates the internal partStreamById map for text and reasoning parts but fails to emit any runtime event (e.g., completion.chunk or item.updated) before returning. This effectively swallows the AI's textual response, preventing it from being streamed to the client application, which will result in an empty or non-updating response in the UI. This contrasts with the tool branch, which correctly delegates to a handler that emits events. [ Out of scope (triage) ]
apps/server/src/provider/Layers/ClaudeCodeAdapter.ts — 0 comments posted, 3 evaluated, 2 filtered
  • line 348: The classifyToolItemType function uses the single keyword "file" (line 348) to classify a tool as file_change. This heuristic is overly broad and incorrect for standard read-only tools like read_file, list_files, file_exists, or search_files. It causes these read operations to be categorized as file_change items, potentially leading to incorrect UI states (e.g., displaying a diff view for a search operation) and feeding incorrect data into the classifyRequestType logic. [ Cross-file consolidated ]
  • line 661: The function logNativeSdkMessage uses crypto.randomUUID() which is neither imported nor guaranteed to be available in the global scope (e.g., in Node.js < 19 without flags or specific polyfills). This will cause a ReferenceError and crash the event processing loop if nativeEventLogger is enabled. The codebase consistently uses yield* Random.nextUUIDv4 from the effect library elsewhere (e.g., line 1590, 1889), and should do so here as well to ensure runtime compatibility and consistency with the Effect runtime. [ Out of scope (triage) ]
    1. Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro

      Run ID: 98ed2380-b3b6-46a4-a017-4033e052fa1e

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    2. Opened against wrong repo — this should target the fork. Closing.

    3. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    4. @@ -0,0 +10,21 @@
      10+ pendingCompletionProviderTurnId: TurnId | undefined;
      11+ pendingTurnIds: Array<TurnId>;
      12+ pendingTurnUsage: CopilotAssistantUsage | undefined;
      13+}
      14+
      15+export function completionTurnRefs(state: CopilotTurnTrackingState) {
      16+ return {
      17+ turnId: state.pendingCompletionTurnId ?? state.currentTurnId,
      18+ providerTurnId: state.pendingCompletionProviderTurnId ?? state.currentProviderTurnId,
      19+ };
      20+}
      21+
      22+export function beginCopilotTurn(
      23+ state: CopilotTurnTrackingState,
      24+ providerTurnId: TurnId,
      25+): void {
      26+ state.pendingCompletionTurnId = undefined;
      27+ state.pendingCompletionProviderTurnId = undefined;
      28+ state.pendingTurnUsage = undefined;
      29+ state.currentProviderTurnId = providerTurnId;
      30+ state.currentTurnId = state.pendingTurnIds.shift() ?? state.currentTurnId ?? providerTurnId;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low Layers/copilotTurnTracking.ts:30

      When pendingTurnIds is empty, state.currentTurnId is set to itself instead of the new providerTurnId, causing all subsequent turns to reuse the first turn's ID. The expression state.pendingTurnIds.shift() ?? state.currentTurnId ?? providerTurnId prevents providerTurnId from ever being used once currentTurnId is populated. Consider removing ?? state.currentTurnId so the fallback chain correctly prefers the new providerTurnId when no client ID is pending.

      Suggested change
      30- state.currentTurnId = state.pendingTurnIds.shift() ?? state.currentTurnId ?? providerTurnId;
      30+state.currentTurnId = state.pendingTurnIds.shift() ?? providerTurnId;
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/provider/Layers/copilotTurnTracking.ts around line 30:
      
      When `pendingTurnIds` is empty, `state.currentTurnId` is set to itself instead of the new `providerTurnId`, causing all subsequent turns to reuse the first turn's ID. The expression `state.pendingTurnIds.shift() ?? state.currentTurnId ?? providerTurnId` prevents `providerTurnId` from ever being used once `currentTurnId` is populated. Consider removing `?? state.currentTurnId` so the fallback chain correctly prefers the new `providerTurnId` when no client ID is pending.
      
      Evidence trail:
      apps/server/src/provider/Layers/copilotTurnTracking.ts line 30: `state.currentTurnId = state.pendingTurnIds.shift() ?? state.currentTurnId ?? providerTurnId;` - line 29 shows `state.currentProviderTurnId = providerTurnId;` which IS updated each turn. apps/server/src/provider/Layers/CopilotAdapter.ts lines 1063-1091 shows `beginCopilotTurn` called on each `assistant.turn_start` event, and `clearTurnTracking` only called on `session.idle` or `abort`. Test file copilotTurnTracking.test.ts shows initial state has `pendingTurnIds: []` and `currentTurnId: undefined`.
      @@ -0,0 +390,21 @@
      390+ // ── Approval / user-input stubs ───────────────────────────────────
      391+
      392+ respondToRequest(
      393+ _threadId: ThreadId,
      394+ _requestId: ApprovalRequestId,
      395+ _decision: ProviderApprovalDecision,
      396+ ): Promise<void> {
      397+ return Promise.resolve();
      398+ }
      399+
      400+ respondToUserInput(
      401+ _threadId: ThreadId,
      402+ _requestId: ApprovalRequestId,
      403+ _answers: ProviderUserInputAnswers,
      404+ ): Promise<void> {
      405+ return Promise.resolve();
      406+ }
      407+
      408+ // ── Session teardown ──────────────────────────────────────────────
      409+
      410+ stopSession(threadId: ThreadId): void {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/ampServerManager.ts:410

      stopSession returns immediately after calling process.kill(), but the session entry is not removed from this.sessions until the asynchronous 'close' event fires. This creates a race where startSession immediately called after stopSession finds the stale entry and throws "AMP session already exists". Consider returning a promise that resolves after cleanup completes.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/ampServerManager.ts around line 410:
      
      `stopSession` returns immediately after calling `process.kill()`, but the session entry is not removed from `this.sessions` until the asynchronous `'close'` event fires. This creates a race where `startSession` immediately called after `stopSession` finds the stale entry and throws "AMP session already exists". Consider returning a promise that resolves after cleanup completes.
      
      Evidence trail:
      apps/server/src/ampServerManager.ts lines 410-421 (stopSession returns void, calls process.kill() and returns immediately), lines 250-275 (close event handler where session.status is set to 'closed' at line 267 and this.sessions.delete(threadId) at line 275), lines 182-188 (startSession checks existing session and throws if status !== 'closed')
      @@ -0,0 +11,21 @@
      11+ pendingTurnIds: Array<TurnId>;
      12+ pendingTurnUsage: CopilotAssistantUsage | undefined;
      13+}
      14+
      15+export function completionTurnRefs(state: CopilotTurnTrackingState) {
      16+ return {
      17+ turnId: state.pendingCompletionTurnId ?? state.currentTurnId,
      18+ providerTurnId: state.pendingCompletionProviderTurnId ?? state.currentProviderTurnId,
      19+ };
      20+}
      21+
      22+export function beginCopilotTurn(
      23+ state: CopilotTurnTrackingState,
      24+ providerTurnId: TurnId,
      25+): void {
      26+ state.pendingCompletionTurnId = undefined;
      27+ state.pendingCompletionProviderTurnId = undefined;
      28+ state.pendingTurnUsage = undefined;
      29+ state.currentProviderTurnId = providerTurnId;
      30+ state.currentTurnId = state.pendingTurnIds.shift() ?? state.currentTurnId ?? providerTurnId;
      31+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Layers/copilotTurnTracking.ts:22

      beginCopilotTurn clears pendingCompletionTurnId, pendingCompletionProviderTurnId, and pendingTurnUsage on lines 26–28. If a new turn starts before the previous turn's async completion logic finishes (e.g., usage event still pending), this wipes Turn A's buffered data and completion references. Any subsequent completionTurnRefs call falls back to state.currentTurnId (now Turn B), causing Turn A's metrics to be incorrectly attributed to Turn B. Consider preserving the pending completion state until it is explicitly consumed rather than clearing it on every new turn.

      +export function beginCopilotTurn(
      +  state: CopilotTurnTrackingState,
      +  providerTurnId: TurnId,
      +): void {
      +  state.currentProviderTurnId = providerTurnId;
      +  state.currentTurnId = state.pendingTurnIds.shift() ?? state.currentTurnId ?? providerTurnId;
      +}
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/provider/Layers/copilotTurnTracking.ts around lines 22-31:
      
      `beginCopilotTurn` clears `pendingCompletionTurnId`, `pendingCompletionProviderTurnId`, and `pendingTurnUsage` on lines 26–28. If a new turn starts before the previous turn's async completion logic finishes (e.g., usage event still pending), this wipes Turn A's buffered data and completion references. Any subsequent `completionTurnRefs` call falls back to `state.currentTurnId` (now Turn B), causing Turn A's metrics to be incorrectly attributed to Turn B. Consider preserving the pending completion state until it is explicitly consumed rather than clearing it on every new turn.
      
      Evidence trail:
      apps/server/src/provider/Layers/copilotTurnTracking.ts:26-28 (beginCopilotTurn clears pending state), apps/server/src/provider/Layers/copilotTurnTracking.ts:15-19 (completionTurnRefs fallback logic), apps/server/src/provider/Layers/CopilotAdapter.ts:1063 (beginCopilotTurn called on turn_start), apps/server/src/provider/Layers/CopilotAdapter.ts:1090 (markTurnAwaitingCompletion called on turn_end), apps/server/src/provider/Layers/CopilotAdapter.ts:713 (completionTurnRefs used for usage event)
      @@ -0,0 +465,21 @@
      465+
      466+ const trimmed = line.trim();
      467+ if (!trimmed) return;
      468+
      469+ let msg: AmpJsonlMessage;
      470+ try {
      471+ msg = JSON.parse(trimmed) as AmpJsonlMessage;
      472+ } catch {
      473+ // Non-JSON output — treat as raw assistant text.
      474+ this.logger.warn("Failed to parse JSONL line", { length: trimmed.length });
      475+ this.emitEvent(threadId, session.activeTurnId, {
      476+ type: "content.delta",
      477+ payload: {
      478+ streamKind: "assistant_text",
      479+ delta: trimmed + "\n",
      480+ },
      481+ });
      482+ return;
      483+ }
      484+
      485+ switch (msg.type) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/ampServerManager.ts:462

      handleOutputLine parses untrusted input with JSON.parse and immediately accesses msg.type. If the external process sends the string "null", JSON.parse returns null, causing a TypeError: Cannot read property 'type' of null that crashes the Node.js process. Consider checking that msg is a non-null object before the switch statement.

      -    switch (msg.type) {
      +    if (!msg || typeof msg !== "object") {
      +      this.logger.warn("Invalid JSONL message", { line: trimmed.slice(0, 200) });
      +      return;
      +    }
      +    switch (msg.type) {
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/ampServerManager.ts around lines 462-485:
      
      `handleOutputLine` parses untrusted input with `JSON.parse` and immediately accesses `msg.type`. If the external process sends the string `"null"`, `JSON.parse` returns `null`, causing a `TypeError: Cannot read property 'type' of null` that crashes the Node.js process. Consider checking that `msg` is a non-null object before the switch statement.
      
      Evidence trail:
      apps/server/src/ampServerManager.ts lines 462-485 (at REVIEWED_COMMIT): `handleOutputLine` method parses JSON at line 470 with `msg = JSON.parse(trimmed) as AmpJsonlMessage`, catch block handles parse errors at lines 471-480, then line 485 has `switch (msg.type)` with no null check between parsing and access.
      @@ -178,16 +179,4 @@
      178179 `,
      179180 });
      180181
      181- const append: OrchestrationEventStoreShape["append"] = (event) =>
      182- appendEventRow({
      183- eventId: event.eventId,
      184- aggregateKind: event.aggregateKind,
      185- streamId: event.aggregateId,
      186- type: event.type,
      187- causationEventId: event.causationEventId,
      188- correlationId: event.correlationId,
      189- actorKind: inferActorKind(event),
      190- occurredAt: event.occurredAt,
      191- commandId: event.commandId,
      192- payloadJson: event.payload,
      193- metadataJson: event.metadata,
      182+ const append: OrchestrationEventStoreShape["append"] = (event) => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low Layers/OrchestrationEventStore.ts:182

      The append method stores a redacted event to disk and returns the redacted version to the caller. This strips username/password from providerOptions before the event is handed back, so any immediate downstream use of that event (e.g., calling an LLM provider) fails due to missing credentials. Return the original unredacted event augmented with the assigned sequence instead, keeping the redaction for persistence only.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/persistence/Layers/OrchestrationEventStore.ts around line 182:
      
      The `append` method stores a redacted event to disk and returns the redacted version to the caller. This strips `username`/`password` from `providerOptions` before the event is handed back, so any immediate downstream use of that event (e.g., calling an LLM provider) fails due to missing credentials. Return the original unredacted event augmented with the assigned `sequence` instead, keeping the redaction for persistence only.
      
      Evidence trail:
      apps/server/src/persistence/Layers/OrchestrationEventStore.ts lines 182-195 (append method redacts then stores), apps/server/src/orchestration/redactEvent.ts lines 31-45 (redactEventForBoundary strips username/password), apps/server/src/orchestration/Layers/OrchestrationEngine.ts lines 124-165 (savedEvent pushed to eventPubSub), apps/server/src/orchestration/Layers/ProviderCommandReactor.ts lines 762-775 (subscribes to streamDomainEvents), lines 455-501 (processTurnStartRequested uses event.payload.providerOptions), lines 354-362 (sendTurnForThread passes providerOptions), lines 240-259 (effectiveProviderOptions passed to providerService.startSession)
      @@ -0,0 +416,21 @@
      416+ }
      417+ return sessions;
      418+ }
      419+
      420+ hasSession(threadId: ThreadId): boolean {
      421+ return this.sessions.has(threadId);
      422+ }
      423+
      424+ readThread(threadId: ThreadId): Promise<ProviderThreadSnapshot> {
      425+ if (!this.sessions.has(threadId)) {
      426+ throw new Error(`Unknown Gemini CLI session: ${threadId}`);
      427+ }
      428+ return Promise.resolve({ threadId, turns: [] });
      429+ }
      430+
      431+ rollbackThread(threadId: ThreadId): Promise<ProviderThreadSnapshot> {
      432+ if (!this.sessions.has(threadId)) {
      433+ throw new Error(`Unknown Gemini CLI session: ${threadId}`);
      434+ }
      435+ return Promise.resolve({ threadId, turns: [] });
      436+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/geminiCliServerManager.ts:431

      rollbackThread returns an empty snapshot without actually resetting the GeminiCliSession state, so subsequent turns still use the old geminiSessionId and retain the full conversation history. If rollback isn't supported by the Gemini CLI, throw an error instead of silently returning a misleading empty snapshot.

      -  rollbackThread(threadId: ThreadId): Promise<ProviderThreadSnapshot> {
      -    if (!this.sessions.has(threadId)) {
      -      throw new Error(`Unknown Gemini CLI session: ${threadId}`);
      -    }
      -    return Promise.resolve({ threadId, turns: [] });
      -  }
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/geminiCliServerManager.ts around lines 431-436:
      
      `rollbackThread` returns an empty snapshot without actually resetting the `GeminiCliSession` state, so subsequent turns still use the old `geminiSessionId` and retain the full conversation history. If rollback isn't supported by the Gemini CLI, throw an error instead of silently returning a misleading empty snapshot.
      
      Evidence trail:
      - apps/server/src/geminiCliServerManager.ts lines 431-436: `rollbackThread` returns `{ threadId, turns: [] }` without modifying session state
      - apps/server/src/geminiCliServerManager.ts lines 121-138: `GeminiCliSession` interface showing `geminiSessionId` field at line 129
      - apps/server/src/geminiCliServerManager.ts lines 278-279: `geminiSessionId` is used via `--resume` flag for subsequent turns
      - apps/server/src/geminiCliServerManager.ts lines 202-217: Session creation showing all initial fields that should be reset for a proper rollback
      @@ -0,0 +410,21 @@
      410+ stopSession(threadId: ThreadId): void {
      411+ const session = this.sessions.get(threadId);
      412+ if (!session) return;
      413+ session.closing = true;
      414+ try {
      415+ session.process.kill();
      416+ } catch {
      417+ // Process may already be dead — clean up immediately since handlers won't fire.
      418+ session.status = "closed";
      419+ this.sessions.delete(threadId);
      420+ }
      421+ }
      422+
      423+ // ── Listing / introspection ───────────────────────────────────────
      424+
      425+ listSessions(): ProviderSession[] {
      426+ const sessions: ProviderSession[] = [];
      427+ for (const session of this.sessions.values()) {
      428+ sessions.push({
      429+ provider: PROVIDER,
      430+ status: session.status === "closed" ? "closed" : "ready",
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/ampServerManager.ts:425

      In listSessions, the status mapping session.status === "closed" ? "closed" : "ready" collapses the internal "running" state into "ready". Clients therefore see busy sessions as available, and attempting sendTurn on such a session throws "already has a turn in progress" — a mismatch between reported and actual state. Consider mapping the three internal states directly to their external equivalents.

      -        status: session.status === "closed" ? "closed" : "ready",
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/ampServerManager.ts around lines 425-430:
      
      In `listSessions`, the status mapping `session.status === "closed" ? "closed" : "ready"` collapses the internal `"running"` state into `"ready"`. Clients therefore see busy sessions as available, and attempting `sendTurn` on such a session throws "already has a turn in progress" — a mismatch between reported and actual state. Consider mapping the three internal states directly to their external equivalents.
      
      Evidence trail:
      apps/server/src/ampServerManager.ts line 76: `status: "ready" | "running" | "closed";` (three internal states)
      apps/server/src/ampServerManager.ts line 430: `status: session.status === "closed" ? "closed" : "ready"` (mapping collapses running to ready)
      apps/server/src/ampServerManager.ts lines 331-334: `if (session.status === "running" || session.activeTurnId) { throw new Error(...already has a turn in progress...) }` (confirms error thrown for running sessions)
      @@ -0,0 +721,21 @@
      721+ return previous?.kind === "tool" ? "item.updated" : "item.started";
      722+}
      723+
      724+async function readJsonData<T>(promise: Promise<T>): Promise<T> {
      725+ return promise;
      726+}
      727+
      728+function readProviderListResponse(
      729+ value:
      730+ | ProviderListResponse
      731+ | { data: ProviderListResponse; error?: undefined }
      732+ | { data?: undefined; error: unknown },
      733+): ProviderListResponse {
      734+ if ("all" in value && "connected" in value) {
      735+ return value;
      736+ }
      737+ if (value.data !== undefined) {
      738+ return value.data;
      739+ }
      740+ throw new Error("OpenCode SDK returned an empty provider list response");
      741+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/opencodeServerManager.ts:728

      When the SDK returns an error response like { error: "Unauthorized" }, readProviderListResponse falls through to the final throw with message "OpenCode SDK returned an empty provider list response", suppressing the actual error. Consider rethrowing or including value.error in the error message so callers can see the root cause.

      -  if (value.data !== undefined) {
      -    return value.data;
      -  }
      -  throw new Error("OpenCode SDK returned an empty provider list response");
      +  if (value.data !== undefined) {
      +    return value.data;
      +  }
      +  throw new Error(`OpenCode SDK returned an empty provider list response: ${value.error}`);
      
      Also found in 1 other location(s)

      apps/server/src/kiloServerManager.ts:703

      The function readProviderListResponse fails to handle the error case of the input union type. If value is an error wrapper (e.g. { error: &#34;Access Denied&#34;, data: undefined }), value.data is undefined, causing the code to fall through to line 703. This throws a generic Error(&#34;Kilo SDK returned an empty provider list response&#34;) instead of propagating the actual error. This swallows the underlying exception from the SDK, making debugging impossible. The function should check for and throw value.error if present.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/opencodeServerManager.ts around lines 728-741:
      
      When the SDK returns an error response like `{ error: "Unauthorized" }`, `readProviderListResponse` falls through to the final `throw` with message "OpenCode SDK returned an empty provider list response", suppressing the actual error. Consider rethrowing or including `value.error` in the error message so callers can see the root cause.
      
      Evidence trail:
      apps/server/src/opencodeServerManager.ts lines 728-743 at REVIEWED_COMMIT - The `readProviderListResponse` function accepts `{ data?: undefined; error: unknown }` as a valid input type, but the function body only checks for `"all" in value && "connected" in value` and `value.data !== undefined`. When an error response is passed, both conditions are false, and the function throws a generic error without using `value.error`.
      
      Also found in 1 other location(s):
      - apps/server/src/kiloServerManager.ts:703 -- The function `readProviderListResponse` fails to handle the error case of the input union type. If `value` is an error wrapper (e.g. `{ error: "Access Denied", data: undefined }`), `value.data` is undefined, causing the code to fall through to line 703. This throws a generic `Error("Kilo SDK returned an empty provider list response")` instead of propagating the actual error. This swallows the underlying exception from the SDK, making debugging impossible. The function should check for and throw `value.error` if present.
      
      @@ -0,0 +41,21 @@
      41+ cachedTokens: 0,
      42+ turnCount: 0,
      43+};
      44+
      45+export function fetchAmpUsage(): ProviderUsageResult {
      46+ const acc = _ampUsageAccumulator;
      47+ let sessionUsage: ProviderSessionUsage | undefined;
      48+ if (acc.turnCount > 0) {
      49+ sessionUsage = {
      50+ inputTokens: acc.inputTokens,
      51+ outputTokens: acc.outputTokens,
      52+ ...(acc.cachedTokens > 0 ? { cachedTokens: acc.cachedTokens } : {}),
      53+ totalTokens: acc.inputTokens + acc.outputTokens,
      54+ turnCount: acc.turnCount,
      55+ };
      56+ }
      57+ return {
      58+ provider: PROVIDER,
      59+ ...(sessionUsage ? { sessionUsage } : {}),
      60+ };
      61+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      src/ampServerManager.ts:45

      fetchAmpUsage returns sessionUsage only when turnCount > 0, but token usage is accumulated in _ampUsageAccumulator even when a session crashes or is interrupted before turnCount increments. This causes the function to return { provider: "amp" } with no usage data even when tokens were consumed, leading to silent under-reporting of costs for failed or interrupted sessions. Consider gating on total token presence rather than turn count, or ensure turnCount is incremented whenever usage is recorded.

      +export function fetchAmpUsage(): ProviderUsageResult {
      +  const acc = _ampUsageAccumulator;
      +  let sessionUsage: ProviderSessionUsage | undefined;
      +  if (acc.inputTokens > 0 || acc.outputTokens > 0) {
      +    sessionUsage = {
      +      inputTokens: acc.inputTokens,
      +      outputTokens: acc.outputTokens,
      +      ...(acc.cachedTokens > 0 ? { cachedTokens: acc.cachedTokens } : {}),
      +      totalTokens: acc.inputTokens + acc.outputTokens,
      +      turnCount: acc.turnCount,
      +    };
      +  }
      +  return {
      +    provider: PROVIDER,
      +    ...(sessionUsage ? { sessionUsage } : {}),
      +  };
      +}
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/ampServerManager.ts around lines 45-61:
      
      `fetchAmpUsage` returns `sessionUsage` only when `turnCount > 0`, but token usage is accumulated in `_ampUsageAccumulator` even when a session crashes or is interrupted before `turnCount` increments. This causes the function to return `{ provider: "amp" }` with no usage data even when tokens were consumed, leading to silent under-reporting of costs for failed or interrupted sessions. Consider gating on total token presence rather than turn count, or ensure `turnCount` is incremented whenever usage is recorded.
      
      Evidence trail:
      apps/server/src/ampServerManager.ts lines 45-57 (fetchAmpUsage returns sessionUsage only when turnCount > 0), lines 431-443 (token accumulation occurs whenever inner.usage is present), line 452 (turnCount++ only when stop_reason === 'end_turn'), lines 229-249 (close handler doesn't increment turnCount), lines 251-272 (error handler doesn't increment turnCount), lines 315-322 (interruptTurn doesn't increment turnCount). REVIEWED_COMMIT.
      @@ -0,0 +1255,21 @@
      1255+ });
      1256+
      1257+ const startedBaseUrl = await new Promise<string>((resolve, reject) => {
      1258+ const timeout = setTimeout(() => {
      1259+ reject(
      1260+ new Error(
      1261+ `Timed out waiting for OpenCode server to start after ${SERVER_START_TIMEOUT_MS}ms`,
      1262+ ),
      1263+ );
      1264+ }, SERVER_START_TIMEOUT_MS);
      1265+ let output = "";
      1266+
      1267+ const onChunk = (chunk: Buffer) => {
      1268+ output += chunk.toString();
      1269+ const url = parseServerUrl(output);
      1270+ if (!url) {
      1271+ return;
      1272+ }
      1273+ clearTimeout(timeout);
      1274+ resolve(url);
      1275+ };
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/opencodeServerManager.ts:1267

      The onChunk listener is never removed from child.stdout and child.stderr after the server URL is detected (line 1273). The listener keeps accumulating all server output into the output string for the lifetime of the child process, causing unbounded memory growth and repeated parseServerUrl calls on ever-growing data. Consider removing the listeners with child.stdout.off('data', onChunk) and child.stderr.off('data', onChunk) after resolving the promise.

              const onChunk = (chunk: Buffer) => {
                 output += chunk.toString();
                 const url = parseServerUrl(output);
                 if (!url) {
                   return;
                 }
                 clearTimeout(timeout);
      +          child.stdout.off("data", onChunk);
      +          child.stderr.off("data", onChunk);
                 resolve(url);
               };
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/opencodeServerManager.ts around lines 1267-1275:
      
      The `onChunk` listener is never removed from `child.stdout` and `child.stderr` after the server URL is detected (line 1273). The listener keeps accumulating all server output into the `output` string for the lifetime of the child process, causing unbounded memory growth and repeated `parseServerUrl` calls on ever-growing data. Consider removing the listeners with `child.stdout.off('data', onChunk)` and `child.stderr.off('data', onChunk)` after resolving the promise.
      
      Evidence trail:
      apps/server/src/opencodeServerManager.ts lines 1250-1310 at REVIEWED_COMMIT: Line 1267 defines `onChunk` that appends to `output` and calls `parseServerUrl`. Lines 1276-1277 attach listeners with `.on('data', onChunk)`. Line 1273 calls `resolve(url)` without removing the listeners. The child process is stored in `this.server.child` (line 1303-1307) and kept alive, meaning listeners remain active indefinitely.
      @@ -0,0 +129,21 @@
      129+ return models;
      130+}
      131+
      132+const ANSI_CONTROL_SEQUENCE_PATTERN = new RegExp(
      133+ String.raw`\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])`,
      134+ "g",
      135+);
      136+
      137+function stripAnsiControlSequences(value: string): string {
      138+ return value.replace(ANSI_CONTROL_SEQUENCE_PATTERN, "");
      139+}
      140+
      141+function parseCursorModelsFromPlainText(stdout: string): Array<{ slug: string; name: string }> {
      142+ const normalized = stripAnsiControlSequences(stdout);
      143+ const models: Array<{ slug: string; name: string }> = [];
      144+ for (const line of normalized.split(/\r?\n/)) {
      145+ const trimmed = line.trim();
      146+ if (!trimmed || !trimmed.includes(" - ")) {
      147+ continue;
      148+ }
      149+ const match = /^(?<slug>[a-z0-9./-]+)\s+-\s+(?<name>.+?)(?:\s+\((?:current|default)\))*$/i.exec(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low Layers/CursorAdapter.ts:149

      The regex [a-z0-9./-]+ on line 149 rejects model slugs containing colons or underscores, so identifiers like llama2:7b or my_model are silently discarded. Consider expanding the character class to include : and _.

      -    const match = /^(?<slug>[a-z0-9./-]+)\s+-\s+(?<name>.+?)(?:\s+\((?:current|default)\))*$/i.exec(
      +    const match = /^(?<slug>[a-z0-9.:/_-]+)\s+-\s+(?<name>.+?)(?:\s+\((?:current|default)\))*$/i.exec(
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/provider/Layers/CursorAdapter.ts around line 149:
      
      The regex `[a-z0-9./-]+` on line 149 rejects model slugs containing colons or underscores, so identifiers like `llama2:7b` or `my_model` are silently discarded. Consider expanding the character class to include `:` and `_`.
      
      Evidence trail:
      apps/server/src/provider/Layers/CursorAdapter.ts lines 140-161 at REVIEWED_COMMIT. Line 149 shows regex `/^(?<slug>[a-z0-9./-]+)\s+-\s+(?<name>.+?)(?:\s+\((?:current|default)\))*$/i` where the character class `[a-z0-9./-]+` excludes colons and underscores. Lines 150-152 show `if (!match?.groups) { continue; }` which silently skips non-matching lines.
      @@ -0,0 +1036,21 @@
      1036+ ): Promise<void> {
      1037+ const context = this.requireSession(threadId);
      1038+ const pending = context.pendingQuestions.get(requestId);
      1039+ if (!pending) {
      1040+ throw new Error(`Unknown Kilo question request '${requestId}'`);
      1041+ }
      1042+
      1043+ const max = pending.questions.reduce(
      1044+ (result, question) => (question.answerIndex > result ? question.answerIndex : result),
      1045+ -1,
      1046+ );
      1047+ const orderedAnswers = Array.from({ length: max + 1 }, () => [] as string[]);
      1048+ for (const question of pending.questions) {
      1049+ const value = answers[question.id];
      1050+ if (Array.isArray(value)) {
      1051+ orderedAnswers[question.answerIndex] = value.map(String);
      1052+ continue;
      1053+ }
      1054+ if (typeof value === "string" && value.length > 0) {
      1055+ orderedAnswers[question.answerIndex] = [value];
      1056+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low src/kiloServerManager.ts:1054

      In respondToUserInput, scalar answers that are not strings (numbers, booleans) are silently discarded because of typeof value === "string", leaving the answer slot as []. This contradicts the array branch which converts values with .map(String), implying non-strings should be converted rather than dropped. Consider converting scalar values with String(value) instead of filtering them out.

      -      if (typeof value === "string" && value.length > 0) {
      -        orderedAnswers[question.answerIndex] = [value];
      +      if (value != null && value !== "" && value !== false) {
      +        orderedAnswers[question.answerIndex] = [String(value)];
             }
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/kiloServerManager.ts around lines 1054-1056:
      
      In `respondToUserInput`, scalar answers that are not strings (numbers, booleans) are silently discarded because of `typeof value === "string"`, leaving the answer slot as `[]`. This contradicts the array branch which converts values with `.map(String)`, implying non-strings should be converted rather than dropped. Consider converting scalar values with `String(value)` instead of filtering them out.
      
      Evidence trail:
      apps/server/src/kiloServerManager.ts lines 1048-1057 at REVIEWED_COMMIT: Line 1048 initializes orderedAnswers with empty arrays. Lines 1051-1053 handle arrays with `.map(String)` conversion. Lines 1055-1056 only accept strings with `typeof value === "string" && value.length > 0`, meaning numeric/boolean scalars are never assigned and the slot remains `[]`.
    5. I really feel like you need to fix your workflow, because this isnt great that it keeps making PR's against the upstream repo

Sign in to join this conversation.