From e6e2ab05cceb3f8245e87f8499d4891f27de33cb Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 1 Nov 2026 16:50:47 -0800 Subject: [PATCH 001/163] feat(usage): filter Usage totals by provider and model (#28952) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/state/usage.ts | 16 ++- apps/server/src/usage/UsageService.test.ts | 114 +++++++++++++++++- apps/server/src/usage/UsageService.ts | 12 +- apps/server/src/usage/usageAggregation.ts | 36 ++++++ apps/web/src/state/usage.ts | 16 ++- docs/user/usage.md | 24 ++++ packages/client-runtime/src/state/server.ts | 8 ++ .../client-runtime/src/state/usage.test.ts | 32 ++++- packages/client-runtime/src/state/usage.ts | 16 ++- packages/contracts/src/settings.test.ts | 11 ++ packages/contracts/src/settings.ts | 4 + packages/contracts/src/usage.ts | 20 +++ packages/shared/src/usageMerge.test.ts | 8 ++ packages/shared/src/usageMerge.ts | 5 +- 14 files changed, 307 insertions(+), 15 deletions(-) diff --git a/apps/mobile/src/state/usage.ts b/apps/mobile/src/state/usage.ts index 9851b841c88c5..ed9fb01fc1f7f 100644 --- a/apps/mobile/src/state/usage.ts +++ b/apps/mobile/src/state/usage.ts @@ -6,7 +6,11 @@ import { type UsageSummary, type UsageSummaryInput, } from "@t3tools/contracts"; -import { needsCursorKeychainAccess, refreshUsage } from "@t3tools/client-runtime/state/usage"; +import { + needsCursorKeychainAccess, + refreshUsage, + usageSummaryInput, +} from "@t3tools/client-runtime/state/usage"; import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access"; import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge"; import { AsyncResult, Atom } from "effect/reactivity"; @@ -52,7 +56,15 @@ const usageByWindowAtom = Atom.family((windowKey: string) => }); continue; } - const result = get(serverEnvironment.usageSummary({ environmentId, input })); + const result = get( + serverEnvironment.usageSummary({ + environmentId, + input: usageSummaryInput( + input, + get(serverEnvironment.usageModelFilterAtom(environmentId)), + ), + }), + ); const summary = AsyncResult.getOrElse(result, () => null); statuses.push({ environmentId, diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 32ef901326f77..8c09383d56c18 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -67,12 +67,17 @@ const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unkno const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); const decodeUnknownJsonString = Schema.decodeSync(Schema.fromJsonString(Schema.Unknown)); -function claudeLine(id: number, outputTokens: number, model = "claude-fable-5"): string { +function claudeLine( + id: number, + outputTokens: number, + model = "claude-fable-5", + sessionId = "session-1", +): string { return `${JSON.stringify({ type: "assistant", timestamp: "2026-08-01T10:00:00Z", requestId: `req_${id}`, - sessionId: "session-1", + sessionId, message: { id: `msg_${id}`, model, @@ -2077,6 +2082,111 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); + it.live("filters original model IDs before aliases, pricing, buckets and session counts", () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + yield* Effect.promise(() => + NodeFSP.writeFile( + transcript, + claudeLine(1, 3, "orbit-1", "mixed") + + claudeLine(2, 5, "orbit-2", "mixed") + + claudeLine(3, 7, "drift-9", "mixed") + + claudeLine(4, 11, "drift-9", "excluded-only"), + ), + ); + const rates = { + "orbit-1": { input_cost_per_token: 0.000001, output_cost_per_token: 0.00001 }, + "orbit-2": { input_cost_per_token: 0.000002, output_cost_per_token: 0.00002 }, + }; + const include = { + // The codex selector must not match the Claude drift-9 records. + include: [ + { provider: "claude", model: "orbit-1" }, + { model: "orbit-2" }, + { provider: "codex", model: "drift-9" }, + ], + }; + const exclude = { exclude: [{ model: "drift-9" }] }; + const HOURLY: UsageSummaryInput = { + ...WINDOW, + resolution: "hour", + sinceTime: "2026-08-01T09:00:00Z", + untilTime: "2026-08-01T11:00:00Z", + }; + const cells = (summary: UsageSummary) => + summary.buckets.map(({ model, totals, costUsd, records, sessions }) => ({ + model, + outputTokens: totals.outputTokens, + costUsd: Math.round(costUsd * 1e6), + records, + sessions, + })); + + yield* Effect.gen(function* () { + const service = yield* UsageService.make; + // Same service, concurrent reads: the in-flight key must keep these scans apart. + const [unfiltered, noOp, keepNothing, included, reordered, excluded, hourly] = + yield* Effect.all( + [ + service.readSummary(WINDOW), + service.readSummary({ ...WINDOW, modelFilter: { exclude: [] } }), + service.readSummary({ ...WINDOW, modelFilter: { include: [] } }), + service.readSummary({ ...WINDOW, modelFilter: include }), + service.readSummary({ + ...WINDOW, + modelFilter: { include: [...include.include].reverse() }, + }), + service.readSummary({ ...WINDOW, modelFilter: exclude }), + service.readSummary({ ...HOURLY, modelFilter: include }), + ], + { concurrency: "unbounded" }, + ); + + // Unfiltered keeps today's behavior: the alias folds drift-9 into orbit-1. + assert.deepStrictEqual(cells(unfiltered), [ + { model: "orbit-1", outputTokens: 21, costUsd: 240, records: 3, sessions: 2 }, + { model: "orbit-2", outputTokens: 5, costUsd: 120, records: 1, sessions: 1 }, + ]); + assert.strictEqual(unfiltered.sources[0]?.distinctSessions, 2); + assert.strictEqual(unfiltered.modelFilter, undefined); + assert.strictEqual(noOp, unfiltered); + assert.deepStrictEqual(keepNothing.buckets, []); + assert.strictEqual(keepNothing.sources[0]?.distinctSessions, 0); + + const kept = [ + { model: "orbit-1", outputTokens: 3, costUsd: 40, records: 1, sessions: 1 }, + { model: "orbit-2", outputTokens: 5, costUsd: 120, records: 1, sessions: 1 }, + ]; + assert.deepStrictEqual(cells(included), kept); + assert.deepStrictEqual(cells(excluded), kept); + assert.deepStrictEqual(cells(hourly), kept); + assert.strictEqual(hourly.buckets[0]?.hourStart, "2026-08-01T10:00:00.000Z"); + for (const summary of [included, excluded, hourly]) { + assert.strictEqual(summary.sources[0]?.distinctSessions, 1); + } + // Equal filters share one scan and echo one canonical form. + assert.strictEqual(reordered, included); + assert.deepStrictEqual(included.modelFilter, { + include: [ + { provider: "claude", model: "orbit-1" }, + { provider: "codex", model: "drift-9" }, + { model: "orbit-2" }, + ], + }); + }).pipe( + Effect.scoped, + Effect.provide( + layerService({ + prefix: "usage-service-model-filter-test", + home, + settings: { ...settings, usageModelAliases: { "drift-9": "orbit-1" } }, + ratesDocument: rates, + }), + ), + ); + }).pipe(Effect.scoped), + ); + it.live("reprices unchanged transcripts when custom prices are added, edited, or removed", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index f5f10fb156f3f..7e2e8586ed95f 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -39,7 +39,7 @@ import type { TranscriptUsageFormat, UsageRecord, } from "@t3tools/provider-core/server/usage"; -import { resolveModelAliases, UsageAggregator } from "./usageAggregation.ts"; +import { canonicalModelFilter, resolveModelAliases, UsageAggregator } from "./usageAggregation.ts"; import { createOverrideRateTable, parseRateTable, type RateTable } from "./usagePricing.ts"; import { listTranscriptFiles, @@ -724,6 +724,7 @@ export const make = Effect.gen(function* () { rates, priceOverrides: createOverrideRateTable(settings.usagePriceOverrides), modelAliases: resolveModelAliases(settings.usageModelAliases), + ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }), }); const sources: UsageSource[] = []; @@ -882,6 +883,7 @@ export const make = Effect.gen(function* () { sources, pricing: pricing(), scanDurationMs: Math.max(0, finishedAtMs - startedAtMs), + ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }), } satisfies UsageSummary; }); @@ -897,9 +899,15 @@ export const make = Effect.gen(function* () { input.untilTime ?? null, settings, input.awaitRefresh === true, + input.modelFilter ?? null, ]); - const readSummary = Effect.fn("UsageService.readSummary")(function* (input: UsageSummaryInput) { + const readSummary = Effect.fn("UsageService.readSummary")(function* ( + requested: UsageSummaryInput, + ) { + const { modelFilter: requestedFilter, ...unfiltered } = requested; + const modelFilter = canonicalModelFilter(requestedFilter); + const input = modelFilter === undefined ? unfiltered : { ...unfiltered, modelFilter }; const settings = yield* readSettings; const key = scanKey(input, settings); const deferred = yield* Effect.uninterruptible( diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index 17903cd062eae..8f94c84a3c470 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -3,6 +3,8 @@ import type { UsageBucket, UsageCategoryCost, UsageDay, + UsageModelFilter, + UsageModelSelector, UsageResolution, UsageTokenTotals, } from "@t3tools/contracts"; @@ -67,6 +69,7 @@ export interface AggregateOptions { readonly rates: RateTable; readonly priceOverrides?: RateTable; readonly modelAliases?: ReadonlyMap; + readonly modelFilter?: UsageModelFilter; readonly resolution?: UsageResolution; readonly sinceTimeMs?: number; readonly untilTimeMs?: number; @@ -88,6 +91,38 @@ export function resolveModelAliases( return resolved; } +/** Matches original IDs, so an alias cannot pull excluded usage into a kept model. */ +function keepsUsageRecord(filter: UsageModelFilter | undefined, record: UsageRecord): boolean { + if (filter === undefined) return true; + const model = record.model.trim(); + const matches = (selector: UsageModelSelector) => + selector.model === model && + (selector.provider === undefined || selector.provider === record.provider); + return (filter.include?.some(matches) ?? true) && !(filter.exclude?.some(matches) ?? false); +} + +const selectorKey = (selector: UsageModelSelector) => + JSON.stringify([selector.provider ?? null, selector.model]); + +const canonicalSelectors = (selectors: readonly UsageModelSelector[]) => + [...new Map(selectors.map((selector) => [selectorKey(selector), selector]))] + // Code-unit order, so servers in different locales echo the same form. + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([, selector]) => selector); + +/** Equal filters get one form, so they share scans and clients can compare echoed filters. */ +export function canonicalModelFilter( + filter: UsageModelFilter | undefined, +): UsageModelFilter | undefined { + if (filter === undefined) return undefined; + const exclude = filter.exclude?.length ? canonicalSelectors(filter.exclude) : undefined; + if (filter.include === undefined && exclude === undefined) return undefined; + return { + ...(filter.include === undefined ? {} : { include: canonicalSelectors(filter.include) }), + ...(exclude === undefined ? {} : { exclude }), + }; +} + export interface AggregateResult { readonly buckets: readonly UsageBucket[]; readonly duplicatesDropped: number; @@ -129,6 +164,7 @@ export class UsageAggregator { } add(input: UsageRecord, sourcePath?: string): boolean { + if (!keepsUsageRecord(this.#options.modelFilter, input)) return false; const record = this.#mapModel(input); if (record.dedupeKey !== null) { if (this.#seen.has(record.dedupeKey)) { diff --git a/apps/web/src/state/usage.ts b/apps/web/src/state/usage.ts index 9a68a5fa724f7..f47a65cd08268 100644 --- a/apps/web/src/state/usage.ts +++ b/apps/web/src/state/usage.ts @@ -8,7 +8,11 @@ import { type UsageProviderKind, type UsageSummaryInput, } from "@t3tools/contracts"; -import { needsCursorKeychainAccess, refreshUsage } from "@t3tools/client-runtime/state/usage"; +import { + needsCursorKeychainAccess, + refreshUsage, + usageSummaryInput, +} from "@t3tools/client-runtime/state/usage"; import { resolveUsageAccess } from "@t3tools/client-runtime/state/usage-access"; import { AsyncResult, Atom } from "effect/reactivity"; import { useState } from "react"; @@ -55,7 +59,15 @@ const usageByWindowAtom = Atom.family((windowKey: string) => }); continue; } - const result = get(serverEnvironment.usageSummary({ environmentId, input })); + const result = get( + serverEnvironment.usageSummary({ + environmentId, + input: usageSummaryInput( + input, + get(serverEnvironment.usageModelFilterAtom(environmentId)), + ), + }), + ); const summary = AsyncResult.getOrElse(result, () => null); statuses.push({ environmentId, diff --git a/docs/user/usage.md b/docs/user/usage.md index 0289defe8bc71..71eb1e0fe8773 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -87,6 +87,30 @@ marked **Not saved**. Reconnect them and choose **Retry failed saves** to finish without writing again to environments that already saved. Changes are not queued after you close the dialog. +## Show only some models + +To count only some models, or to leave some out, add `usageModelFilter` to the server's +`settings.json` in its `userdata` directory, such as `~/.t3/userdata/settings.json`: + +```json +{ + "usageModelFilter": { + "include": [{ "provider": "claude", "model": "orbit-1" }, { "model": "orbit-2" }], + "exclude": [{ "model": "drift-9" }] + } +} +``` + +`include` keeps only the listed models and `exclude` leaves the listed models out. `provider` is +one of `claude`, `codex`, `cursor`, `grok`, `opencode`, `antigravity`, `pi`, or `muse`; omit it +to match a model ID from any provider. Use the model ID that Usage shows without **Map to**, such +as a provider-prefixed ID for Pi. Filters apply before **Map to**, so a model you leave out is not +counted under its mapped name. Usage applies each environment's own filter. Remove the setting to +show every model again. + +If the setting is invalid, Usage ignores it and shows every model, and the next save of any other +setting removes it from `settings.json`. + ## Track subscription limits **Usage → Limits** pools every subscription account it can see per provider, so with several Codex diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 890d1feaddf96..06eb14e2d8477 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1112,6 +1112,13 @@ export function createServerEnvironmentAtoms( ]); }).pipe(Atom.withLabel(`environment-data:server:usage-scan-settings:${environmentId}`)), ); + // Settings snapshots rebuild the filter object; only a changed filter should touch the Usage tab. + const usageModelFilterAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => get(settingsValueAtom(environmentId))?.usageModelFilter).pipe( + Atom.withEquality((a, b) => JSON.stringify(a) === JSON.stringify(b)), + Atom.withLabel(`environment-data:server:usage-model-filter:${environmentId}`), + ), + ); const providersValueAtom = Atom.family((environmentId: EnvironmentId) => Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe( Atom.withLabel(`environment-data:server:providers:${environmentId}`), @@ -1194,6 +1201,7 @@ export function createServerEnvironmentAtoms( }), updateStateAtom, settingsValueAtom, + usageModelFilterAtom, providersValueAtom, providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, { label: "environment-data:provider:auth-state", diff --git a/packages/client-runtime/src/state/usage.test.ts b/packages/client-runtime/src/state/usage.test.ts index 29aac2ae98ecf..0650b1f2093c7 100644 --- a/packages/client-runtime/src/state/usage.test.ts +++ b/packages/client-runtime/src/state/usage.test.ts @@ -5,7 +5,9 @@ import { UsageDay, USAGE_CONTRACT_VERSION, type ServerProvider, + type UsageModelFilter, type UsageSummary, + type UsageSummaryInput, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; @@ -39,7 +41,7 @@ afterEach(() => { for (const registry of registries.splice(0)) registry.dispose(); }); -function harness(ids = ["a"]) { +function harness(ids = ["a"], modelFilters: Record = {}) { const registry = AtomRegistry.make(); registries.push(registry); const environments = ids.map((id) => { @@ -65,13 +67,18 @@ function harness(ids = ["a"]) { if (!environment) throw new Error(`Unknown environment: ${environmentId}`); return environment; } + const requested: { environmentId: EnvironmentId; input: UsageSummaryInput }[] = []; const options = { registry, environmentIds: environments.map((entry) => entry.environmentId), input, server: { - usageSummary: ({ environmentId }: { environmentId: EnvironmentId }) => - get(environmentId).query, + usageSummary: (target: { environmentId: EnvironmentId; input: UsageSummaryInput }) => { + requested.push(target); + return get(target.environmentId).query; + }, + usageModelFilterAtom: (environmentId: EnvironmentId) => + Atom.make(modelFilters[environmentId]), refreshUsageRates: { label: "test:rates", requiredScopes: () => [], @@ -86,7 +93,7 @@ function harness(ids = ["a"]) { presentationAtom: (environmentId: EnvironmentId) => get(environmentId).presentation, }, } satisfies Parameters[0]; - return { registry, environments, refresh: () => refreshUsage(options) }; + return { registry, environments, requested, refresh: () => refreshUsage(options) }; } describe("manual usage refresh", () => { @@ -113,6 +120,23 @@ describe("manual usage refresh", () => { expect(finished).toBe(true); }); + it("rescans each environment with its own configured model filter", async () => { + const modelFilter = { include: [{ provider: "claude" as const, model: "orbit-1" }] }; + const { environments, requested, refresh } = harness(["filtered", "plain"], { + filtered: modelFilter, + }); + const refreshing = refresh(); + for (const entry of environments) { + entry.rates.resolve(AsyncResult.success(pricing)); + entry.scan.resolve(summary); + } + await refreshing; + expect(requested).toEqual([ + { environmentId: "filtered", input: { ...input, modelFilter } }, + { environmentId: "plain", input }, + ]); + }); + it("settles when an environment disconnects during the rescan", async () => { const { registry, diff --git a/packages/client-runtime/src/state/usage.ts b/packages/client-runtime/src/state/usage.ts index 7bc582eb7da39..2dea725be1f14 100644 --- a/packages/client-runtime/src/state/usage.ts +++ b/packages/client-runtime/src/state/usage.ts @@ -1,6 +1,7 @@ import type { EnvironmentId, ServerProvider, + UsageModelFilter, UsageSummary, UsageSummaryInput, } from "@t3tools/contracts"; @@ -43,6 +44,14 @@ export function cursorKeychainAccessEnvironments< : environments.filter((environment) => environment.needsCursorKeychainAccess); } +/** The Usage tab asks each environment with that environment's configured model filter. */ +export function usageSummaryInput( + input: UsageSummaryInput, + modelFilter: UsageModelFilter | undefined, +): UsageSummaryInput { + return modelFilter === undefined ? input : { ...input, modelFilter }; +} + const limitsRefreshAfter = new Map(); const limitsRefreshes = new Map>(); @@ -86,7 +95,7 @@ export async function refreshUsage({ registry: AtomRegistry.AtomRegistry; server: Pick< ReturnType, - "usageSummary" | "refreshUsageRates" + "usageSummary" | "refreshUsageRates" | "usageModelFilterAtom" >; presentations: Pick, "presentationAtom">; environmentIds: readonly EnvironmentId[]; @@ -94,7 +103,10 @@ export async function refreshUsage({ }): Promise { await Promise.all( environmentIds.map(async (environmentId) => { - const query = server.usageSummary({ environmentId, input }); + const query = server.usageSummary({ + environmentId, + input: usageSummaryInput(input, registry.get(server.usageModelFilterAtom(environmentId))), + }); const presentation = presentations.presentationAtom(environmentId); const controller = new AbortController(); const abortWhenDisconnected = () => { diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts index 859644a54c72f..4b593d4d335b9 100644 --- a/packages/contracts/src/settings.test.ts +++ b/packages/contracts/src/settings.test.ts @@ -126,6 +126,17 @@ describe("ServerSettings usage price overrides", () => { expect(() => decodeServerSettingsPatch({ usagePriceOverrides })).toThrow(); } }); + + it("ignores an invalid model filter without dropping the other settings", () => { + const valid = { include: [{ provider: "newer-provider", model: "orbit-1" }] }; + expect(decodeServerSettings({ usageModelFilter: valid }).usageModelFilter).toEqual(valid); + const settings = decodeServerSettings({ + usageModelFilter: { exclude: [{ model: "" }] }, + usageModelAliases: { "drift-9": "orbit-1" }, + }); + expect(settings.usageModelFilter).toBeUndefined(); + expect(settings.usageModelAliases).toEqual({ "drift-9": "orbit-1" }); + }); }); describe("ServerSettings secret providers", () => { diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index e90b977fae32d..b1848090d9d00 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -20,6 +20,7 @@ import { TrimmedString, } from "./baseSchemas.ts"; import { UsageLimitSourceId } from "./usageLimitSourceId.ts"; +import { UsageModelFilter } from "./usage.ts"; import { SecretProviderId, SecretProviderSlug } from "./secretReference.ts"; import { EnvironmentMachineKind, ThreadEnvMode, WorktreeSubmodules } from "./environment.ts"; import { KeybindingShortcut } from "./keybindings.ts"; @@ -1361,6 +1362,9 @@ export const ServerSettings = Schema.Struct({ usageModelAliases: Schema.Record(TrimmedNonEmptyString, TrimmedNonEmptyString).pipe( Schema.withDecodingDefault(Effect.succeed({})), ), + + /** Sent by the Usage tab with each summary request to this environment; edit in settings.json. Invalid values are ignored. */ + usageModelFilter: ForwardCompatibleOptional(UsageModelFilter), }); export type ServerSettings = typeof ServerSettings.Type; diff --git a/packages/contracts/src/usage.ts b/packages/contracts/src/usage.ts index 8e34c10eb885e..7f5a609eee20a 100644 --- a/packages/contracts/src/usage.ts +++ b/packages/contracts/src/usage.ts @@ -108,6 +108,23 @@ export const UsagePricing = Schema.Struct({ }); export type UsagePricing = typeof UsagePricing.Type; +/** + * Matches a provider's original model ID, before usage model aliases apply. Omit provider to + * match any; a string provider lets older clients carry selectors for providers they lack. + */ +export const UsageModelSelector = Schema.Struct({ + provider: Schema.optional(TrimmedNonEmptyString), + model: TrimmedNonEmptyString, +}); +export type UsageModelSelector = typeof UsageModelSelector.Type; + +/** Keeps records matching `include` (all when omitted) and not matching `exclude`. */ +export const UsageModelFilter = Schema.Struct({ + include: Schema.optional(Schema.Array(UsageModelSelector)), + exclude: Schema.optional(Schema.Array(UsageModelSelector)), +}); +export type UsageModelFilter = typeof UsageModelFilter.Type; + export const UsageSummaryInput = Schema.Struct({ sinceDay: UsageDay, untilDay: UsageDay, @@ -117,6 +134,7 @@ export const UsageSummaryInput = Schema.Struct({ sinceTime: Schema.optional(TrimmedNonEmptyString), untilTime: Schema.optional(TrimmedNonEmptyString), awaitRefresh: Schema.optional(Schema.Boolean), + modelFilter: Schema.optional(UsageModelFilter), }); export type UsageSummaryInput = typeof UsageSummaryInput.Type; @@ -130,6 +148,8 @@ export const UsageSummary = Schema.Struct({ sources: ForwardCompatibleArray(UsageSource), pricing: UsagePricing, scanDurationMs: NonNegativeInt, + /** The filter the server applied; absent means unfiltered, including servers that predate filters. */ + modelFilter: Schema.optional(UsageModelFilter), }); export type UsageSummary = typeof UsageSummary.Type; diff --git a/packages/shared/src/usageMerge.test.ts b/packages/shared/src/usageMerge.test.ts index b58c2e6a8d878..828b652077f62 100644 --- a/packages/shared/src/usageMerge.test.ts +++ b/packages/shared/src/usageMerge.test.ts @@ -271,6 +271,14 @@ describe("mergeUsage", () => { ); expect(merged.duplicateSources).toEqual(["new: /home/theo/.claude"]); } + + const filtered = environment("new", { + ...partial.summary, + modelFilter: { exclude: [{ model: "claude-fable-5" }] }, + }); + const merged = mergeUsage([complete, filtered], USAGE_CONTRACT_VERSION); + expect(merged.costUsd).toBe(10); + expect(merged.sessions).toBe(1); }); it("retains a complete cell when a larger partial cell may have skipped old records", () => { diff --git a/packages/shared/src/usageMerge.ts b/packages/shared/src/usageMerge.ts index 994ae01d6ffec..6c3e9e84ae21d 100644 --- a/packages/shared/src/usageMerge.ts +++ b/packages/shared/src/usageMerge.ts @@ -178,9 +178,12 @@ function claimSources(environments: readonly EnvironmentUsage[]): { if (source.status !== "partial") continue; const key = fingerprintKey(source.fingerprint); const owner = ownerScanByFingerprint.get(key); + // A scan under another model filter counts different records, so its cells are not missing ones. if ( owner?.source.status !== "ok" || - Date.parse(environment.summary.readAt) <= Date.parse(owner.environment.summary.readAt) + Date.parse(environment.summary.readAt) <= Date.parse(owner.environment.summary.readAt) || + JSON.stringify(environment.summary.modelFilter) !== + JSON.stringify(owner.environment.summary.modelFilter) ) { continue; } From e925dd681904f8a1ead0502ecca3f65f5bc28146 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Mon, 2 Nov 2026 07:06:12 +0530 Subject: [PATCH 002/163] fix(web): allow folder references on saved local desktop servers (#27785) Co-authored-by: PR Batch Tester Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/chat/ChatComposer.tsx | 6 +- .../src/components/chat/folderDrop.test.ts | 82 +++++++++++++++++++ apps/web/src/components/chat/folderDrop.ts | 35 ++++++-- 3 files changed, 116 insertions(+), 7 deletions(-) create mode 100644 apps/web/src/components/chat/folderDrop.test.ts diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index aa2c52443a5cb..9ad9158cd4da3 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -261,7 +261,7 @@ import { useMediaQuery } from "../../hooks/useMediaQuery"; import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen"; import { useStableCallback } from "../../hooks/useStableCallback"; import { usePanelAnimationSettings } from "../../panelAnimations"; -import { readEnvironmentScope } from "../../state/session"; +import { readEnvironmentScope, readPreparedConnection } from "../../state/session"; import type { ReviewCommentContext } from "../../reviewCommentContext"; import { useComposerRestingTransition } from "./useComposerRestingTransition"; import { ComposerCommandMenuLayer } from "./ComposerCommandMenuLayer"; @@ -2522,11 +2522,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) localEnvironmentDisabled: isLocalEnvironmentDisabled(), environmentId, primaryEnvironmentId, + connection: readPreparedConnection(environmentId), + isDesktopRenderer: window.desktopBridge !== undefined, }); if (target === "remote") { toastManager.add({ type: "error", - title: "Folders can only be referenced in the local desktop environment", + title: "Folders can only be referenced on a server running on this computer", }); return; } diff --git a/apps/web/src/components/chat/folderDrop.test.ts b/apps/web/src/components/chat/folderDrop.test.ts new file mode 100644 index 0000000000000..6c42bf42cb6dd --- /dev/null +++ b/apps/web/src/components/chat/folderDrop.test.ts @@ -0,0 +1,82 @@ +import { + BearerConnectionTarget, + RelayConnectionTarget, + SshConnectionTarget, +} from "@t3tools/client-runtime/connection"; +import { EnvironmentId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { folderDropTarget } from "./folderDrop"; + +const environmentId = EnvironmentId.make("saved-local"); +const base = { environmentId, label: "server" }; +const savedServer = (httpBaseUrl: string, connectionId = "saved-1") => ({ + target: new BearerConnectionTarget({ ...base, connectionId }), + httpBaseUrl, +}); +const thinClient = { + localEnvironmentDisabled: true, + environmentId, + primaryEnvironmentId: null, + isDesktopRenderer: true, +}; + +describe("folderDropTarget", () => { + it.each([ + [ + "the bundled primary", + { + ...thinClient, + localEnvironmentDisabled: false, + primaryEnvironmentId: environmentId, + connection: null, + }, + "local", + ], + [ + "a saved loopback server on desktop", + { ...thinClient, connection: savedServer("http://127.0.0.1:3773") }, + "local", + ], + [ + "a saved LAN server", + { ...thinClient, connection: savedServer("http://192.168.1.20:3773") }, + "remote", + ], + [ + "a saved loopback server in a browser", + { ...thinClient, isDesktopRenderer: false, connection: savedServer("http://localhost:3773") }, + "remote", + ], + [ + "a desktop WSL backend", + { ...thinClient, connection: savedServer("http://127.0.0.1:3774", "local:wsl-ubuntu") }, + "remote", + ], + [ + "an SSH forward on loopback", + { + ...thinClient, + connection: { + target: new SshConnectionTarget({ ...base, connectionId: "ssh-1" }), + httpBaseUrl: "http://127.0.0.1:41000", + }, + }, + "remote", + ], + [ + "a relay connection", + { + ...thinClient, + connection: { + target: new RelayConnectionTarget(base), + httpBaseUrl: "https://relay.t3.codes", + }, + }, + "remote", + ], + ["an unprepared connection", { ...thinClient, connection: null }, "remote"], + ] as const)("targets %s", (_name, input, expected) => { + expect(folderDropTarget(input)).toBe(expected); + }); +}); diff --git a/apps/web/src/components/chat/folderDrop.ts b/apps/web/src/components/chat/folderDrop.ts index 8f462394e8fac..df4089589aa2d 100644 --- a/apps/web/src/components/chat/folderDrop.ts +++ b/apps/web/src/components/chat/folderDrop.ts @@ -1,18 +1,43 @@ +import type { PreparedConnection } from "@t3tools/client-runtime/connection"; import type { EnvironmentId } from "@t3tools/contracts"; +import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal"; +import { isLoopbackHostname } from "~/environments/primary/target"; + export function folderDropTarget(input: { localEnvironmentDisabled: boolean; environmentId: EnvironmentId; primaryEnvironmentId: EnvironmentId | null; + connection: Pick | null; + isDesktopRenderer: boolean; }): "local" | "remote" { if ( - input.localEnvironmentDisabled || - input.primaryEnvironmentId === null || - input.environmentId !== input.primaryEnvironmentId + !input.localEnvironmentDisabled && + input.primaryEnvironmentId !== null && + input.environmentId === input.primaryEnvironmentId ) { - return "remote"; + return "local"; + } + return input.isDesktopRenderer && + input.connection !== null && + isSavedLoopbackConnection(input.connection) + ? "local" + : "remote"; +} + +// A direct saved connection to loopback shares the desktop's filesystem; WSL backends and SSH forwards do not. +function isSavedLoopbackConnection({ + target, + httpBaseUrl, +}: Pick): boolean { + if (target._tag !== "BearerConnectionTarget" || isDesktopLocalConnectionTarget(target)) { + return false; + } + try { + return isLoopbackHostname(new URL(httpBaseUrl).hostname); + } catch { + return false; } - return "local"; } export function resolveDroppedFolderPath( From 05c0ed7da69ee6aceab8fad84e8a0dc0c474138a Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 1 Nov 2026 19:58:33 -0600 Subject: [PATCH 003/163] fix(web): clarify the waiting label for background work (#28969) --- .../components/chat/ThreadActivityBanners.tsx | 48 +++++++++++-------- .../src/state/threadExecution.ts | 10 ++-- 2 files changed, 32 insertions(+), 26 deletions(-) diff --git a/apps/web/src/components/chat/ThreadActivityBanners.tsx b/apps/web/src/components/chat/ThreadActivityBanners.tsx index 217d0b6ea92b7..368931833dc72 100644 --- a/apps/web/src/components/chat/ThreadActivityBanners.tsx +++ b/apps/web/src/components/chat/ThreadActivityBanners.tsx @@ -11,6 +11,7 @@ import { type RunStopPresentation, } from "@t3tools/client-runtime/state/thread-execution"; import { childThreadInputsTitle } from "@t3tools/client-runtime/state/threads"; +import { commandDisplayText } from "@t3tools/client-runtime/work-log/command-label"; import { formatDuration } from "@t3tools/shared/orchestrationTiming"; import * as DateTime from "effect/DateTime"; import { @@ -25,7 +26,6 @@ import { } from "lucide-react"; import { Fragment } from "react"; import { tickTextContent } from "~/lib/tickTextContent"; -import { cn } from "~/lib/utils"; import { Button, InlineButton } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import type { ComposerBannerStackItem } from "./ComposerBannerStack"; @@ -174,6 +174,16 @@ export function backgroundWorkNowItem(input: { const subagent = item?.type === "subagent" ? item : undefined; return { task, + label: + item?.type === "command_execution" && commandDisplayText(item.input) === task.label ? ( + + {task.label} + + ) : task.label.includes("\n") ? ( + {task.label} + ) : ( + task.label + ), activity: subagent?.progress?.replace(/\s+/gu, " ").trim() || null, startedAtMs: item?.startedAt ? DateTime.toEpochMillis(item.startedAt) : null, updatedAtMs: subagent ? DateTime.toEpochMillis(subagent.updatedAt) : 0, @@ -185,34 +195,32 @@ export function backgroundWorkNowItem(input: { .filter((row) => row.activity) .toSorted((left, right) => right.updatedAtMs - left.updatedAtMs)[0]; const isCommand = (row: (typeof rows)[number]) => row.task.kind !== "subagent"; - const verb = presentation.waiting ? "Waiting on" : "Running"; const onlyThreadId = only?.childThreadId; const startedAtMs = only?.startedAtMs ?? null; return { id: `background-work:${input.threadId}`, icon: rows.every(isCommand) ? : , - title: only ? ( - <> - {verb}{" "} - - {only.task.label} - - - ) : ( - presentation.title - ), + title: + only && typeof only.label !== "string" && only.task.label !== only.task.kind ? ( + <> + {presentation.waiting ? "Waiting" : "Running"} · {only.label} + + ) : ( + presentation.title + ), description: only ? ( only.activity ) : newest ? ( - `${newest.task.label}: ${newest.activity}` - ) : rows.every(isCommand) ? ( - {rows.map((row) => row.task.label).join(", ")} + <> + {newest.label}: {newest.activity} + ) : ( - rows.map((row) => row.task.label).join(", ") + rows.map((row, index) => ( + + {index > 0 ? ", " : null} + {row.label} + + )) ), actions: ( <> diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index 361f44f717edb..b6151c7c875be 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -433,12 +433,10 @@ export function presentPendingBackgroundWork( if (items.length === 1 && only !== undefined) { const noun = BACKGROUND_WORK_KINDS[only.kind].singular; const named = only.label !== noun; - const title = waiting - ? named - ? `${only.kind === "monitor" ? "" : `Waiting on ${noun} `}${only.label}` - : `Waiting on a ${noun}` - : named - ? `Running: ${only.label}` + const title = named + ? `${waiting ? "Waiting" : "Running"} · ${only.label}` + : waiting + ? `Waiting on a ${noun}` : `Running a ${noun}`; return { title, items, waiting }; } From dd6c05ec313c6c870c7a7688e87143da5084031d Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 1 Nov 2026 18:23:44 -0800 Subject: [PATCH 004/163] fix(preview): agent browser use no longer steals composer focus (#28613) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/preview/GuestInput.test.ts | 53 +++++++++++++++++++ apps/desktop/src/preview/GuestInput.ts | 35 ++++++++---- .../preview/agentOpenedPreviews.test.ts | 3 ++ .../components/preview/agentOpenedPreviews.ts | 2 +- apps/web/src/rightPanelStore.ts | 17 ++++-- 5 files changed, 94 insertions(+), 16 deletions(-) diff --git a/apps/desktop/src/preview/GuestInput.test.ts b/apps/desktop/src/preview/GuestInput.test.ts index 579b564f59aa1..a0889940a6682 100644 --- a/apps/desktop/src/preview/GuestInput.test.ts +++ b/apps/desktop/src/preview/GuestInput.test.ts @@ -124,6 +124,59 @@ describe("preview guest input", () => { }, ); + it.each([{ userClicksStuckTab: false }, { userClicksStuckTab: true }])( + "keeps the right focus when a sibling press finishes beside a stuck one, user clicks: $userClicksStuckTab", + async ({ userClicksStuckTab }) => { + const document = { activeElement: {} as object }; + const composer = { + isConnected: true, + focus: () => { + document.activeElement = composer; + }, + }; + document.activeElement = composer; + const context = NodeVM.createContext({ document }); + const host = { + isDestroyed: () => false, + executeJavaScript: async (script: string) => NodeVM.runInContext(script, context), + }; + const previews = new Map( + [7, 8].map((id) => [id, { tagName: "WEBVIEW", getWebContentsId: () => id }]), + ); + const stuckPressFocused = Promise.withResolvers(); + const stuckPressEnds = Promise.withResolvers(); + const press = (id: number) => { + const debuggee = { + sendCommand: async () => { + document.activeElement = previews.get(id)!; + if (id === 7) { + stuckPressFocused.resolve(); + await stuckPressEnds.promise; + } else if (userClicksStuckTab) { + document.activeElement = previews.get(7)!; + } + return {}; + }, + }; + return sendPageCommand( + { id, focusedFrame: null, hostWebContents: host } as unknown as Electron.WebContents, + debuggee as unknown as Electron.Debugger, + "Input.dispatchMouseEvent", + { type: "mousePressed", x: 10, y: 10, button: "left" }, + ); + }; + // A press held open, as by a page's confirm() on mousedown, must not block or win focus. + const stuck = press(7); + await stuckPressFocused.promise; + await press(8); + const expected = userClicksStuckTab ? previews.get(7) : composer; + expect(document.activeElement).toBe(expected); + stuckPressEnds.resolve(); + await stuck; + expect(Object.keys(context)).toEqual(["document"]); + }, + ); + it.each([ { method: "Input.dispatchMouseEvent", diff --git a/apps/desktop/src/preview/GuestInput.ts b/apps/desktop/src/preview/GuestInput.ts index d3ccf29c76ed7..2af13af8d7daa 100644 --- a/apps/desktop/src/preview/GuestInput.ts +++ b/apps/desktop/src/preview/GuestInput.ts @@ -92,7 +92,8 @@ const evaluate = async (debuggee: Electron.Debugger, expression: string) => { return reply.result?.value; }; -let focusSequence = 0; +/** Host focus shared by the presses in flight in one window, so a later press keeps the field an earlier one saved. */ +const HOST_FOCUS = "globalThis.__t3PreviewFocus"; /** A CDP pointer press focuses the guest's native view even with focus emulation enabled. */ const sendPointerPress = async ( @@ -106,22 +107,36 @@ const sendPointerPress = async ( if (!host || host.isDestroyed() || webContents.focusedFrame) { return debuggee.sendCommand(method, params, sessionId); } - const key = JSON.stringify(`__t3PreviewFocus${++focusSequence}`); + // Focus in a webview with a press in flight came from that press, so keep the earlier save. await host.executeJavaScript(`(() => { + const state = (${HOST_FOCUS} ??= { saved: null, presses: [] }); const active = document.activeElement; - if (!active || active === document.body || active.tagName === "WEBVIEW") return; - globalThis[${key}] = () => { - delete globalThis[${key}]; - const current = document.activeElement; - if (active.isConnected && current?.tagName === "WEBVIEW" && - current.getWebContentsId() === ${webContents.id}) active.focus({ preventScroll: true }); - }; + let pressed = false; + try { + pressed = active?.tagName === "WEBVIEW" && state.presses.includes(active.getWebContentsId()); + } catch {} + if (!pressed) { + state.saved = active && active !== document.body && active.tagName !== "WEBVIEW" ? active : null; + } + state.presses.push(${webContents.id}); })()`); try { return await debuggee.sendCommand(method, params, sessionId); } finally { if (!host.isDestroyed()) { - await host.executeJavaScript(`globalThis[${key}]?.()`); + // Membership check: a host reload starts a new state without this press. + await host.executeJavaScript(`(() => { + const state = ${HOST_FOCUS}; + const index = state ? state.presses.indexOf(${webContents.id}) : -1; + if (index < 0) return; + state.presses.splice(index, 1); + if (state.presses.length === 0) delete ${HOST_FOCUS}; + const current = document.activeElement; + try { + if (state.saved?.isConnected && current?.tagName === "WEBVIEW" && + current.getWebContentsId() === ${webContents.id}) state.saved.focus({ preventScroll: true }); + } catch {} + })()`); } } }; diff --git a/apps/web/src/components/preview/agentOpenedPreviews.test.ts b/apps/web/src/components/preview/agentOpenedPreviews.test.ts index f6ad67432acdd..dee29a16cf527 100644 --- a/apps/web/src/components/preview/agentOpenedPreviews.test.ts +++ b/apps/web/src/components/preview/agentOpenedPreviews.test.ts @@ -230,11 +230,14 @@ describe("revealServerTabs", () => { expect(useRightPanelStore.getState().byThreadKey[threadKey]?.activeSurfaceId).not.toBe( browserSurfaceId, ); + const userActionRevision = useRightPanelStore.getState().getUserActionRevision(ref); revealServerTabs(ref, [tab("tab_a", true)], { autoShowFloatingPreview: true }); expect(useRightPanelStore.getState().byThreadKey[threadKey]?.activeSurfaceId).toBe( browserSurfaceId, ); expect(floatingTabId()).toBeNull(); + // A user action moves keyboard focus into the panel; an agent reveal must not. + expect(useRightPanelStore.getState().getUserActionRevision(ref)).toBe(userActionRevision); }); }); diff --git a/apps/web/src/components/preview/agentOpenedPreviews.ts b/apps/web/src/components/preview/agentOpenedPreviews.ts index 8273258d51e54..8255cc48a551d 100644 --- a/apps/web/src/components/preview/agentOpenedPreviews.ts +++ b/apps/web/src/components/preview/agentOpenedPreviews.ts @@ -49,7 +49,7 @@ export function revealServerTabs( (surface) => surface.kind === "preview" && surface.resourceId === session.tabId, ); if (surface && force) { - useRightPanelStore.getState().activateSurface(threadRef, surface.id); + useRightPanelStore.getState().revealSurface(threadRef, surface.id); } else if (!surface) { usePreviewMiniPlayerStore.getState().open(threadRef, browserMiniPlayerSource(session.tabId)); } diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index 6d9c692d64564..1f736d4f119ae 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -166,6 +166,8 @@ interface RightPanelStoreState { activateTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void; closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void; activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void; + /** Agent-driven activation. Not a user action, so it does not move keyboard focus. */ + revealSurface: (ref: ScopedThreadRef, surfaceId: string) => void; closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void; closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void; closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void; @@ -451,6 +453,11 @@ const userActionOnThread = ( : {}), }); +const activated = (current: ThreadRightPanelState, surfaceId: string): ThreadRightPanelState => + current.surfaces.some((surface) => surface.id === surfaceId) + ? { ...current, isOpen: true, activeSurfaceId: surfaceId } + : current; + const closeAction = ( state: RightPanelStoreState, threadKey: string, @@ -928,11 +935,11 @@ export const useRightPanelStore = create()( ), activateSurface: (ref, surfaceId) => set((state) => - userAction(state, scopedThreadKey(ref), (current) => - current.surfaces.some((surface) => surface.id === surfaceId) - ? { ...current, isOpen: true, activeSurfaceId: surfaceId } - : current, - ), + userAction(state, scopedThreadKey(ref), (current) => activated(current, surfaceId)), + ), + revealSurface: (ref, surfaceId) => + set((state) => + automaticUpdate(state, scopedThreadKey(ref), (current) => activated(current, surfaceId)), ), closeSurface: (ref, surfaceId) => set((state) => From b92c8f473990cbc73b5320461bd06b9e26d4031b Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 1 Nov 2026 18:52:19 -0800 Subject: [PATCH 005/163] fix(server): token telemetry counts each request once and only confirmed models (#29001) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 1 + .../Adapters/ClaudeAdapterV2.ts | 48 ++- .../Adapters/CodexAdapterV2.ts | 34 +- .../Adapters/OpenCode2AdapterV2.test.ts | 57 +++ .../ProviderEventIngestor.test.ts | 31 +- .../orchestration-v2/ProviderEventIngestor.ts | 110 +---- .../ProviderTurnStartService.test.ts | 10 + .../ProviderTurnStartService.ts | 13 +- .../RunExecutionService.test.ts | 29 +- .../orchestration-v2/RunExecutionService.ts | 61 ++- .../claude_compact_after_peer_turn/output.ts | 21 + .../fixtures/claude_idle_resume/output.ts | 11 + .../claude_nested_subagent_model/output.ts | 12 + .../fixtures/claude_result_is_error/output.ts | 2 + .../codex_transcript.ndjson | 47 ++ .../fixtures/codex_model_reroute/output.ts | 21 + .../testkit/fixtures/index.ts | 29 ++ .../opencode_transcript.ndjson | 55 +++ .../opencode2_missing_step_usage/output.ts | 22 + .../fixtures/opencode2_simple/output.ts | 1 + .../fixtures/subagent_v2/codex_output.ts | 10 + .../src/provider/ClaudeTurnTokenUsage.ts | 101 ++++- .../src/provider/CodexTurnTokenUsage.ts | 17 +- .../src/provider/TurnTokenUsage.test.ts | 15 +- apps/server/src/server.ts | 4 +- .../src/telemetry/ProviderDimensions.ts | 40 ++ .../telemetry/ProviderUsageAnalytics.test.ts | 323 ++++++++++++++ .../src/telemetry/ProviderUsageAnalytics.ts | 407 ++++++++++++++++++ docs/internals/product-analytics.md | 71 ++- docs/user/telemetry.md | 7 +- packages/contracts/src/providerRuntime.ts | 8 + .../src/server/v2/adapter.ts | 30 +- 32 files changed, 1470 insertions(+), 178 deletions(-) create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/output.ts create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/opencode2_missing_step_usage/opencode_transcript.ndjson create mode 100644 apps/server/src/orchestration-v2/testkit/fixtures/opencode2_missing_step_usage/output.ts create mode 100644 apps/server/src/telemetry/ProviderUsageAnalytics.test.ts create mode 100644 apps/server/src/telemetry/ProviderUsageAnalytics.ts diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 06b62e0e03b09..a7b1f7e2e03f8 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -5457,6 +5457,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { outputTokens: queryExits ? 40 : 46, cachedInputTokens: queryExits ? 2000 : 11455, cacheCreationTokens: queryExits ? 500 : 2847, + ...(queryExits ? {} : { models: ["claude-sonnet-4-6"] }), }, ); } diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 4f26e50e57645..5b4a4ad84d435 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -21,7 +21,14 @@ import { } from "./claudeWorkflowProgress.ts"; import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview"; -import { normalizeClaudeTurnTokenUsage } from "../../provider/ClaudeTurnTokenUsage.ts"; +import { + addClaudeLedgerUsage, + claudeLedgerDelta, + claudeModelLedger, + normalizeClaudeTurnTokenUsage, + type ClaudeLedgerUsage, + type ClaudeModelLedger, +} from "../../provider/ClaudeTurnTokenUsage.ts"; import { toMcpElicitationResponse } from "../../provider/CodexMcpElicitation.ts"; import { type CanUseTool, @@ -4071,6 +4078,9 @@ interface ActiveClaudeTurnContext { compactionFailure: { readonly message: string | undefined } | null; // Steers end segments whose usage is excluded from the final result; bill them too, oldest first. readonly steeredSegmentUsage: Array; + // Ledger growth of the steered segments; undefined once any segment's growth is unknown. + steeredLedgerUsage: ClaudeLedgerUsage | undefined; + readonly rootModels: Set; readonly subagentsByTaskId: Map; readonly subagentsByToolUseId: Map; readonly promptUuid: string | null; @@ -4122,6 +4132,8 @@ interface ClaudeLiveQueryContext { permissionMode: PermissionMode; stopping: boolean; readonly subagentsFromEarlierProcesses: ReadonlySet; + // The SDK's per-process model ledger at the last result; a new process starts at zero. + modelLedger: ClaudeModelLedger | undefined; // Per process, not per session: a relative temp dir follows the cwd this CLI // was launched in, and a later turn's cwd can differ. readonly taskOutputRoot: string | undefined; @@ -4775,6 +4787,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const interruptedTurns = yield* Ref.make(new Set()); const steeredTurns = yield* Ref.make(new Set()); const queryContext = yield* Ref.make(null); + // Wake buffers replay result frames, so ledger growth is measured once on arrival. + const resultLedgerUsage = new WeakMap(); // A worktree handoff changes the project settings even within one session. let bypassCache: { cwd: string | null; availability: ClaudeBypassAvailability } | null = null; @@ -7613,6 +7627,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( input.context.subagentsByToolUseId.size > 0, input.status, input.context.steeredSegmentUsage, + { + rootModels: input.context.rootModels, + ...(input.result === undefined + ? {} + : { + ledger: addClaudeLedgerUsage( + input.context.steeredLedgerUsage, + resultLedgerUsage.get(input.result), + ), + }), + }, ), }, }), @@ -8528,6 +8553,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (message.type === "assistant" && input.replayed !== true) { if (message.parent_tool_use_id === null) { + // CLI notices and API errors arrive as assistant messages from "". + if (message.message.model && message.message.model !== "") { + context.rootModels.add(message.message.model); + } // Subagent uuids exist only in the sidechain transcript, so resume and fork cannot target them. context.nativeMessageCursor = message.uuid; context.latestAssistantRateLimit = @@ -9409,6 +9438,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const wasSteered = (yield* Ref.get(steeredTurns)).has(context.providerTurnId); if (!interrupted && wasSteered && isClaudeActiveSteeringAbortResult(message)) { context.steeredSegmentUsage.push(message.usage); + context.steeredLedgerUsage = addClaudeLedgerUsage( + context.steeredLedgerUsage, + resultLedgerUsage.get(message), + ); return; } yield* Ref.update(steeredTurns, (current) => { @@ -10404,6 +10437,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( (subagent) => subagent.task.status === "running", ), ), + modelLedger: new Map(), taskOutputRoot: claudeTaskOutputRoot( adapterOptions.environment, path, @@ -10432,6 +10466,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { context.permissionMode = message.permissionMode; } + if (message.type === "result") { + const ledger = claudeModelLedger(message.modelUsage); + const growth = claudeLedgerDelta(context.modelLedger, ledger); + if (growth !== undefined) resultLedgerUsage.set(message, growth); + // A ledger that went backwards cannot anchor the next turn's growth. + context.modelLedger = + growth === undefined && context.modelLedger !== undefined + ? undefined + : ledger; + } return handleSdkMessage({ query: querySession, message }); }), ), @@ -10577,6 +10621,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( latestAssistantRateLimit: null, compactionFailure: null, steeredSegmentUsage: [], + steeredLedgerUsage: { inputTokens: 0, outputTokens: 0 }, + rootModels: new Set(), subagentsByTaskId: new Map(), subagentsByToolUseId: new Map(), promptUuid, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index e6399ff36fd20..fa6bb58a9dcbe 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1830,6 +1830,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const turnWaiters = yield* Ref.make(new Map>()); const subagentThreads = yield* Ref.make(new Map()); const subagentSelections = new Map>(); + // A reroute names one turn; until new settings arrive, the thread's model is unknown. + const reroutedTurnModels = new Map(); + const reroutedThreads = new Set(); + const reportedTurnModel = (nativeThreadId: string, nativeTurnId: string) => { + const rerouted = reroutedTurnModels.get(nativeTurnId); + reroutedTurnModels.delete(nativeTurnId); + if (rerouted !== undefined) return rerouted; + return reroutedThreads.has(nativeThreadId) + ? undefined + : subagentSelections.get(nativeThreadId)?.model; + }; const pendingSubagentTurns = yield* Ref.make( new Map>(), ); @@ -4475,15 +4486,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); yield* client.handleServerNotification("thread/settings/updated", (payload) => - updateSubagentSelection( - payload.threadId, - payload.threadSettings.model, - payload.threadSettings.effort, - payload.threadSettings.serviceTier, + Effect.sync(() => reroutedThreads.delete(payload.threadId)).pipe( + Effect.andThen( + updateSubagentSelection( + payload.threadId, + payload.threadSettings.model, + payload.threadSettings.effort, + payload.threadSettings.serviceTier, + ), + ), ), ); yield* client.handleServerNotification("model/rerouted", (payload) => - updateSubagentSelection(payload.threadId, payload.toModel), + Effect.sync(() => { + reroutedTurnModels.set(payload.turnId, payload.toModel); + reroutedThreads.add(payload.threadId); + }).pipe(Effect.andThen(updateSubagentSelection(payload.threadId, payload.toModel))), ); yield* client.handleServerNotification("hook/completed", (payload) => @@ -6127,6 +6145,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), input.nativeTurnId, input.status === "completed", + reportedTurnModel( + input.context.providerThread.nativeThreadRef?.nativeId ?? "", + input.nativeTurnId, + ), ), }; if (!holdsForGoal) { diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index bb26a5dd53a30..b4c319e8e9a96 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -2150,6 +2150,20 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { const { runtime, thread } = yield* resumed([ out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "" }), promptAccepted, + event("session.step.started", { + sessionID: SESSION, + assistantMessageID: "msg_before_gap", + agent: "build", + model: { id: "big-pickle", providerID: "opencode", variant: "default" }, + started: 1, + }), + event("session.step.ended", { + sessionID: SESSION, + assistantMessageID: "msg_before_gap", + finish: "tool-calls", + cost: 0, + tokens: { input: 100, output: 10, reasoning: 0, cache: { read: 0, write: 0 } }, + }), ...reconnected({}, "succeeded"), ]); const events = yield* runtime.events.pipe( @@ -2164,6 +2178,15 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { "command_execution:completed", ]); assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" }); + // Steps that ended during the gap sent no tokens or models, so both stay incomplete. + const settled = collected.findLast( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, + ); + const usage = + settled?.type === "provider_turn.updated" ? settled.providerTurn.turnTokenUsage : undefined; + assert.deepInclude(usage, { usageStatus: "partial", inputTokens: 100, outputTokens: 10 }); + assert.notProperty(usage, "models"); }).pipe(Effect.scoped), ); @@ -2879,6 +2902,40 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect("leaves models unknown when a step ends without a seen start", () => + Effect.gen(function* () { + const tokens = { input: 10, output: 1, reasoning: 0, cache: { read: 0, write: 0 } }; + const step = (id: string) => ({ sessionID: SESSION, assistantMessageID: id }); + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.step.started", { + ...step("msg_seen"), + agent: "build", + model: { id: "big-pickle", providerID: "opencode", variant: "default" }, + started: 1, + }), + event("session.step.ended", { ...step("msg_seen"), finish: "tool-calls", cost: 0, tokens }), + event("session.step.ended", { ...step("msg_unseen"), finish: "stop", cost: 0, tokens }), + event("session.execution.succeeded", { sessionID: SESSION }), + ]); + const turn = yield* runtime.events.pipe( + Stream.filter( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, + ), + Stream.runHead, + Effect.forkScoped, + ); + yield* runtime.startTurn(turnInput(thread)); + const settled = Option.getOrUndefined(yield* Fiber.join(turn)); + const usage = + settled?.type === "provider_turn.updated" ? settled.providerTurn.turnTokenUsage : undefined; + assert.deepInclude(usage, { usageStatus: "complete", inputTokens: 20, outputTokens: 2 }); + assert.notProperty(usage, "models"); + }).pipe(Effect.scoped), + ); + it.effect("reports cache writes as cache creation, not only as input", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts index 7f1006f1c5ec5..927a9060dd4f4 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts @@ -45,6 +45,7 @@ import * as EventStore from "./EventStore.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderEventIngestor from "./ProviderEventIngestor.ts"; +import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; @@ -325,12 +326,14 @@ it.effect("refreshes the failing instance snapshot after a committed usage_limit ); it.effect("records accepted billed turn usage once without billing the context window", () => { - const recorded: Array>> = []; - const layerAnalytics = Layer.succeed(ProviderEventIngestor.ProviderTurnAnalytics, { - record: (properties: Readonly>) => + const recorded: Array = []; + const layerAnalytics = Layer.succeed(ProviderUsageAnalytics.ProviderTurnAnalytics, { + runStarted: () => Effect.void, + turnCompleted: (report) => Effect.sync(() => { - recorded.push(properties); + recorded.push(report); }), + runSettled: () => Effect.void, }); return Effect.gen(function* () { const now = yield* DateTime.now; @@ -413,23 +416,9 @@ it.effect("records accepted billed turn usage once without billing the context w assert.isEmpty(ignored); assert.lengthOf(recorded, 1); assert.deepEqual(recorded[0], { - provider: CODEX_DRIVER, - terminalStatus: "completed", - usageStatus: "complete", - usageScope: "main_agent", - hasSubagents: false, - inputTokens: 40, - cachedInputTokens: 30, - outputTokens: 10, - model: modelSelection.model, - mixedModels: false, - runtimeMode: "full-access", - interactionMode: "default", - createdBy: "agent", - creationSource: "provider", - scheduled: false, - subagent: true, - durationMs: 120, + driver: CODEX_DRIVER, + providerTurn, + context: input.analyticsContext, }); }).pipe(Effect.provide(layerTest.pipe(Layer.provide(layerAnalytics)))); }); diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 5a2aa39faece4..f27580d909aff 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -5,14 +5,9 @@ import { OrchestrationV2StoredEvent, type OrchestrationV2PlanArtifact, type OrchestrationV2Run, - type OrchestrationV2ProviderTurn, type OrchestrationV2Subagent, type OrchestrationV2ThreadProjection, type ModelSelection, - type OrchestrationV2Actor, - type OrchestrationV2CreationSource, - type RuntimeMode, - type ProviderInteractionMode, ProviderInstanceId, ProviderSessionId, ProviderThreadId, @@ -31,8 +26,11 @@ import * as SqlError from "effect/sql/SqlError"; import { AgentScope } from "@t3tools/shared/AgentScope"; import { isTemporaryWorktreeBranch } from "@t3tools/shared/git"; -import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3tools/shared/model"; -import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; +import { modelSelectionsEqual } from "@t3tools/shared/model"; +import { + ProviderTurnAnalytics, + type ProviderTurnAnalyticsContext, +} from "../telemetry/ProviderUsageAnalytics.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; import * as EventSink from "./EventSink.ts"; @@ -85,88 +83,6 @@ export const ProviderEventIngestorV2Error = Schema.Union([ ]); export type ProviderEventIngestorV2Error = typeof ProviderEventIngestorV2Error.Type; -export interface ProviderTurnAnalyticsContext { - readonly modelSelection: ModelSelection; - readonly runtimeMode?: RuntimeMode; - readonly interactionMode?: ProviderInteractionMode; - readonly origin?: ProviderTurnOrigin; -} - -/** - * Where the run's starting message came from. Most turns start without a - * person (provider continuations, agent sends, delegated subagents), so - * reports need this to tell user turns apart. - */ -export interface ProviderTurnOrigin { - readonly createdBy: OrchestrationV2Actor; - readonly creationSource: OrchestrationV2CreationSource; - readonly scheduled: boolean; - readonly subagent: boolean; -} - -export class ProviderTurnAnalytics extends Context.Reference<{ - readonly record: (properties: Readonly>) => Effect.Effect; -}>("t3/orchestration-v2/ProviderTurnAnalytics", { - defaultValue: () => ({ record: () => Effect.void }), -}) {} - -export const layerAnalytics = Layer.effect( - ProviderTurnAnalytics, - Effect.gen(function* () { - const analytics = yield* AnalyticsService.AnalyticsService; - return { - record: Effect.fn("ProviderTurnAnalytics.record")(function ( - properties: Readonly>, - ) { - return analytics.record("provider.turn.completed", properties); - }), - }; - }), -); - -function providerTurnAnalyticsProperties(input: { - readonly driver: ProviderAdapter.ProviderAdapterV2Event["driver"]; - readonly providerTurn: OrchestrationV2ProviderTurn; - readonly context?: ProviderTurnAnalyticsContext; -}): Readonly> { - const usage = input.providerTurn.turnTokenUsage; - const modelSelection = input.context?.modelSelection; - const effort = modelSelection - ? (getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ?? - getModelSelectionStringOptionValue(modelSelection, "effort")) - : undefined; - return { - provider: input.driver, - terminalStatus: input.providerTurn.status, - usageStatus: usage?.usageStatus ?? "unavailable", - usageScope: usage?.usageScope ?? "main_agent", - ...(usage ? { hasSubagents: usage.hasSubagents } : {}), - ...(usage?.inputTokens === undefined ? {} : { inputTokens: usage.inputTokens }), - ...(usage?.cachedInputTokens === undefined - ? {} - : { cachedInputTokens: usage.cachedInputTokens }), - ...(usage?.cacheCreationTokens === undefined - ? {} - : { cacheCreationTokens: usage.cacheCreationTokens }), - ...(usage?.outputTokens === undefined ? {} : { outputTokens: usage.outputTokens }), - ...(usage?.reasoningTokens === undefined ? {} : { reasoningTokens: usage.reasoningTokens }), - ...(modelSelection ? { model: modelSelection.model, mixedModels: false } : {}), - ...(effort ? { effort } : {}), - ...(input.context?.runtimeMode ? { runtimeMode: input.context.runtimeMode } : {}), - ...(input.context?.interactionMode ? { interactionMode: input.context.interactionMode } : {}), - ...input.context?.origin, - ...(input.providerTurn.startedAt && input.providerTurn.completedAt - ? { - durationMs: Math.max( - 0, - DateTime.toEpochMillis(input.providerTurn.completedAt) - - DateTime.toEpochMillis(input.providerTurn.startedAt), - ), - } - : {}), - }; -} - type TodoListPlan = Extract; function withPlanStepDurations( @@ -891,15 +807,13 @@ export const layer: Layer.Layer< const oldest = completedTurnAnalytics.values().next().value; if (oldest !== undefined) completedTurnAnalytics.delete(oldest); } - yield* analytics.record( - providerTurnAnalyticsProperties({ - driver: input.event.driver, - providerTurn, - ...(input.analyticsContext === undefined - ? {} - : { context: input.analyticsContext }), - }), - ); + yield* analytics.turnCompleted({ + driver: input.event.driver, + providerTurn, + ...(input.analyticsContext === undefined + ? {} + : { context: input.analyticsContext }), + }); }), ), (effect) => diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 05fc1b8545bb2..c9311433eecab 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -51,6 +51,7 @@ import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter" import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import * as ProviderTurnStart from "./ProviderTurnStartService.ts"; import * as RunExecutionService from "./RunExecutionService.ts"; +import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts"; import * as RuntimePolicy from "./RuntimePolicy.ts"; const isDomainEvent = Schema.is(OrchestrationV2DomainEvent); @@ -301,6 +302,7 @@ function makeLocalCommandHarness(input: { readonly switchedProvider?: boolean; }; }) { + const settledRuns: Array = []; const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z"); const threadId = ThreadId.make("thread-native-account-command"); const runId = RunId.make("run-native-account-command"); @@ -947,6 +949,11 @@ function makeLocalCommandHarness(input: { }), Layer.mock(ProviderAuthService.ProviderAuthService)({ tryHandlePromptCommand }), Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }), + Layer.succeed(ProviderUsageAnalytics.ProviderTurnAnalytics, { + runStarted: () => Effect.void, + turnCompleted: () => Effect.void, + runSettled: (report) => Effect.sync(() => void settledRuns.push(report.status)), + }), Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: resolveRuntimePolicy, }), @@ -954,6 +961,7 @@ function makeLocalCommandHarness(input: { ), ); return { + settledRuns, getThreadRecords, getTurnStartContext, setProjection: (next: OrchestrationV2ThreadProjection) => { @@ -1578,6 +1586,7 @@ effectIt.effect("terminalizes a starting run when its provider session cannot op ); const projection = harness.projection(); expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null }); + expect(harness.settledRuns).toEqual(["failed"]); expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null }); expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null }); expect(projection.turnItems).toMatchObject([ @@ -1667,6 +1676,7 @@ effectIt.effect("does not overwrite a run interrupted while its provider session expect(harness.startRootRun).not.toHaveBeenCalled(); const projection = harness.projection(); expect(projection.runs.at(-1)?.status).toBe("interrupted"); + expect(harness.settledRuns).toEqual([]); expect(projection.attempts[0]?.status).toBe("pending"); expect(projection.nodes[0]?.status).toBe("pending"); expect(projection.turnItems).toEqual([]); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 9a5ad6114e2b9..62a9e8b88e96d 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -33,6 +33,7 @@ import * as ProviderAuthService from "../provider/ProviderAuthService.ts"; import * as ServerSettings from "../serverSettings.ts"; import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; import * as EventSink from "./EventSink.ts"; +import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts"; import * as ContextHandoffService from "./ContextHandoffService.ts"; import { isActiveRun } from "./CommandPolicy.ts"; import { @@ -148,6 +149,7 @@ export const layer: Layer.Layer< ProviderTurnStartServiceV2, Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; + const turnAnalytics = yield* ProviderUsageAnalytics.ProviderTurnAnalytics; const contextHandoffService = yield* ContextHandoffService.ContextHandoffServiceV2; const idAllocator = yield* IdAllocator.IdAllocatorV2; const fileSystem = yield* FileSystem.FileSystem; @@ -496,13 +498,22 @@ export const layer: Layer.Layer< } satisfies OrchestrationV2DomainEvent; }), ); - yield* eventSink.writeIfRunCurrent({ + const written = yield* eventSink.writeIfRunCurrent({ threadId: projection.thread.id, runId, activeAttemptId: attempt.id, expectedStatus: "starting", events, }); + // A steering restart that cannot start still ends a run whose earlier turns counted. + if (written.committed) { + yield* turnAnalytics.runSettled({ + runId, + status, + completedAt: now, + childrenRunning: false, + }); + } }, ); const settleStartFailure = Effect.fn("ProviderTurnStartService.settleStartFailure")( diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 1cbd164b9e672..f76148d01bf6d 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -47,6 +47,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderEventIngestor from "./ProviderEventIngestor.ts"; +import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts"; import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts"; import * as PreviewAgentActivity from "../preview/PreviewAgentActivity.ts"; import * as RunExecutionService from "./RunExecutionService.ts"; @@ -1413,10 +1414,21 @@ it.effect("ingests new member threads of an owned child after the root turn term const subagentNodeId = NodeId.make("node:run-execution-late-child:subagent"); const childMessageIngested = yield* Deferred.make(); const order = yield* Ref.make>([]); - const origins = yield* Ref.make>([]); + const origins = yield* Ref.make>([]); + const requests = yield* Ref.make>([]); const layerTest = RunExecutionService.layer.pipe( Layer.provide( Layer.mergeAll( + Layer.succeed(ProviderUsageAnalytics.ProviderTurnAnalytics, { + runStarted: (input) => + Ref.update(requests, (current) => [...current, `started:${input.runId}`]), + turnCompleted: () => Effect.void, + runSettled: (input) => + Ref.update(requests, (current) => [ + ...current, + `settled:${input.runId}:${input.status}:children-running=${input.childrenRunning}`, + ]), + }), McpAppModelContext.layerEmpty, PreviewAgentActivity.layer, Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }), @@ -1443,7 +1455,11 @@ it.effect("ingests new member threads of an owned child after the root turn term const eventType = input.event.type; yield* Ref.update(origins, (current) => [ ...current, - [eventType, input.analyticsContext?.origin] as const, + [ + eventType, + input.analyticsContext?.origin, + input.analyticsContext?.segment, + ] as const, ]); if ( input.event.type === "app_thread.created" && @@ -1603,6 +1619,7 @@ it.effect("ingests new member threads of an owned child after the root turn term attempt: { id: attemptId, providerTurnId: rootProviderTurnId, + reason: "initial", } as OrchestrationV2RunAttempt, attemptId, providerTurnOrdinal: 1, @@ -1635,7 +1652,7 @@ it.effect("ingests new member threads of an owned child after the root turn term assert.deepEqual(yield* Ref.get(order), ["root-finalized", "member-thread", "child-message"]); // The run's message started the root; the parent agent started the child's turn. const recorded = yield* Ref.get(origins); - assert.deepEqual(recorded[0], [ + assert.deepEqual(recorded[0]?.slice(0, 2), [ "app_thread.created", { createdBy: "user", creationSource: "web", scheduled: false, subagent: false }, ]); @@ -1644,8 +1661,14 @@ it.effect("ingests new member threads of an owned child after the root turn term [ "provider_turn.updated", { createdBy: "agent", creationSource: "provider", scheduled: false, subagent: true }, + "native_child", ], ); + // The child outlives the root, so the request summary says its later turns are missing. + assert.deepEqual(yield* Ref.get(requests), [ + `started:${runId}`, + `settled:${runId}:completed:children-running=true`, + ]); }), ); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 780ee76437f4a..6a52fac447926 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -46,6 +46,7 @@ import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ProviderEventIngestor from "./ProviderEventIngestor.ts"; +import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts"; import type { ProjectionStoreV2Error } from "./ProjectionStore.ts"; import { knownProviderFailureMessage, @@ -98,7 +99,7 @@ function isSettledSubagentStatus(status: OrchestrationV2Subagent["status"]): boo } /** A provider-native subagent's turns arrive on its parent's run, but the parent agent started them. */ -const NATIVE_SUBAGENT_TURN_ORIGIN: ProviderEventIngestor.ProviderTurnOrigin = { +const NATIVE_SUBAGENT_TURN_ORIGIN: ProviderUsageAnalytics.ProviderTurnOrigin = { createdBy: "agent", creationSource: "provider", scheduled: false, @@ -615,6 +616,7 @@ export const layer: Layer.Layer< const previewAgentActivity = yield* PreviewAgentActivity.PreviewAgentActivity; const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2; const finalizationObserver = yield* RunFinalizationService.RunFinalizationObserver; + const turnAnalytics = yield* ProviderUsageAnalytics.ProviderTurnAnalytics; const writeFinalRunEvents = Effect.fn("RunExecutionService.writeFinalRunEvents")( function* (input: { @@ -871,13 +873,19 @@ export const layer: Layer.Layer< } else { yield* eventSink.writeWithEffects(finalization); } + yield* turnAnalytics.runSettled({ + runId: input.run.id, + status: input.terminal.status, + completedAt, + childrenRunning: hasOpenSubagentProjection && cascadedSubagentEvents.length === 0, + }); yield* input.refreshAfterTurn; }, ); return RunExecutionServiceV2.of({ startRootRun: Effect.fn("RunExecutionService.startRootRun")(function* (input) { - const rootTurnOrigin: ProviderEventIngestor.ProviderTurnOrigin = { + const rootTurnOrigin: ProviderUsageAnalytics.ProviderTurnOrigin = { createdBy: input.message.createdBy, creationSource: input.message.creationSource, scheduled: input.message.scheduledTaskId !== undefined, @@ -997,6 +1005,25 @@ export const layer: Layer.Layer< const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100); const latestProviderThread = yield* Ref.make(input.providerThread); const latestRootProviderTurn = yield* Ref.make(null); + // Later root turns in one attempt are provider continuations, such as Codex goal turns. + let firstRootProviderTurnId: ProviderTurnId | undefined; + const analyticsContext = { + runId: input.run.id, + modelSelection: input.modelSelection, + runtimeMode: input.runtimePolicy.runtimeMode, + interactionMode: input.runtimePolicy.interactionMode, + origin: rootTurnOrigin, + ...(input.run.restartContinuationOfRunId === undefined + ? {} + : { restartContinuation: true }), + } satisfies ProviderUsageAnalytics.ProviderTurnAnalyticsContext; + if (input.attempt.reason === "initial") { + yield* turnAnalytics.runStarted({ + runId: input.run.id, + driver: input.providerThread.driver, + context: { ...analyticsContext, segment: "initial" }, + }); + } const routeIdentity: ProviderEventRouteIdentity = { threadId: input.run.threadId, runId: input.run.id, @@ -1396,17 +1423,27 @@ export const layer: Layer.Layer< const isRootProviderThreadUpdate = event.type === "provider_thread.updated" && event.providerThread.id === input.providerThread.id; + const nativeChildTurn = + event.type === "provider_turn.updated" && + event.providerTurn.providerThreadId !== input.providerThread.id; + if (event.type === "provider_turn.updated" && !nativeChildTurn) { + firstRootProviderTurnId ??= event.providerTurn.id; + } const storedEvents = yield* providerEventIngestor.ingestNormalized({ - analyticsContext: { - modelSelection: input.modelSelection, - runtimeMode: input.runtimePolicy.runtimeMode, - interactionMode: input.runtimePolicy.interactionMode, - origin: - event.type === "provider_turn.updated" && - event.providerTurn.providerThreadId !== input.providerThread.id - ? NATIVE_SUBAGENT_TURN_ORIGIN - : rootTurnOrigin, - }, + analyticsContext: nativeChildTurn + ? { + ...analyticsContext, + origin: NATIVE_SUBAGENT_TURN_ORIGIN, + segment: "native_child", + } + : { + ...analyticsContext, + segment: + event.type === "provider_turn.updated" && + event.providerTurn.id !== firstRootProviderTurnId + ? "continuation" + : input.attempt.reason, + }, providerSessionId: input.providerSessionId, providerInstanceId: input.run.providerInstanceId, threadId: input.run.threadId, diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_compact_after_peer_turn/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_compact_after_peer_turn/output.ts index 0c357deefea1a..3e9359e3dcc5b 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_compact_after_peer_turn/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_compact_after_peer_turn/output.ts @@ -51,4 +51,25 @@ export function assertClaudeCompactAfterPeerTurnOutput( assert.equal(runs[2]?.status, "completed"); assert.deepEqual(runs[2]?.replies, ["PEER_ACK"]); assert.deepEqual(runs[2]?.compactions, []); + + const usage = projection.runs.map( + (run) => + projection.providerTurns.find((turn) => turn.runAttemptId === run.activeAttemptId) + ?.turnTokenUsage, + ); + assert.deepInclude(usage[0], { + outputTokens: 7, + otherUsage: { inputTokens: 1015, outputTokens: 12 }, + }); + // /compact reports zero tokens as a local command. + assert.deepInclude(usage[1], { + usageStatus: "complete", + inputTokens: 0, + outputTokens: 0, + localCommand: true, + }); + // The peer result's ledger is empty, so neither it nor the next result has a baseline. + assert.deepInclude(usage[2], { usageStatus: "complete", outputTokens: 4 }); + assert.notProperty(usage[1], "otherUsage"); + assert.notProperty(usage[2], "otherUsage"); } diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_idle_resume/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_idle_resume/output.ts index cf8fac0d3a1a2..c5c114d441d02 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_idle_resume/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_idle_resume/output.ts @@ -32,4 +32,15 @@ export function assertClaudeIdleResumeOutput( "idle resume first turn complete", "idle resume second turn complete", ]); + // The resumed process's ledger starts at zero, so the first turn is not counted again. + assert.deepEqual( + projection.providerTurns.map((turn) => [ + turn.turnTokenUsage?.outputTokens, + turn.turnTokenUsage?.otherUsage, + ]), + [ + [7, { inputTokens: 0, outputTokens: 0 }], + [7, { inputTokens: 0, outputTokens: 0 }], + ], + ); } diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_nested_subagent_model/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_nested_subagent_model/output.ts index 99b218f215f6c..6d4866078ed3a 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_nested_subagent_model/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_nested_subagent_model/output.ts @@ -56,4 +56,16 @@ export function assertClaudeNestedSubagentModelOutput( const nestedChild = result.projections.get(nested.childThreadId); assert.isDefined(nestedChild); assert.equal(nestedChild.thread.modelSelection.model, SUBAGENT_MODEL); + + // The result counts only the root; the process ledger adds both subagents' work once. + assert.lengthOf(projection.providerTurns, 1); + assert.deepInclude(projection.providerTurns[0]?.turnTokenUsage, { + usageStatus: "complete", + hasSubagents: true, + inputTokens: 74_167, + outputTokens: 236, + reasoningTokens: 30, + models: ["claude-sonnet-4-6"], + otherUsage: { inputTokens: 87_409, outputTokens: 335 }, + }); } diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_result_is_error/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_result_is_error/output.ts index fe3167b22cbcd..a8cf34999da34 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_result_is_error/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_result_is_error/output.ts @@ -40,6 +40,8 @@ export function assertClaudeResultIsErrorOutput( (turn) => turn.status !== "completed" && turn.status !== "running", ); assert.equal(failedTurn?.status, "failed"); + // The API error's "" frame is a CLI notice, not a model that did work. + assert.notProperty(failedTurn?.turnTokenUsage, "models"); const errorItem = projection.turnItems.find( (item) => item.runId === failedRun?.id && item.type === "error", diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson new file mode 100644 index 0000000000000..6b90c579a26a3 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson @@ -0,0 +1,47 @@ +{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"codex_model_reroute","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"multi_turn.ndjson","description":"The multi_turn recording with a model/rerouted notification added by hand to the first turn. The second turn gets no new thread settings.","model":"gpt-6-luna"}} +{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}} +{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}} +{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}} +{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000},"cwd":"","model":"gpt-6-luna"}}} +{"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295480414}} +{"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295480414}} +{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"detailed","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295480656}} +{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295480656}} +{"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295480666}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":3,"result":{"turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295480718}} +{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295480,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295480718}} +{"type":"emit_inbound","label":"model/rerouted","frame":{"method":"model/rerouted","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","fromModel":"gpt-6-luna","toModel":"gpt-6-astra","reason":"highRiskCyberActivity"}}} +{"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295481015}} +{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295481236}} +{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295481609}} +{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-22a8-7e91-9510-1578c7566bc0","clientId":null,"content":[{"type":"text","text":"Respond with exactly: first fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","startedAtMs":1790295483054},"emittedAtMs":1790295483054}} +{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a0d5ed-22a8-7e91-9510-1578c7566bc0","clientId":null,"content":[{"type":"text","text":"Respond with exactly: first fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","completedAtMs":1790295483054},"emittedAtMs":1790295483061}} +{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","startedAtMs":1790295485125},"emittedAtMs":1790295485125}} +{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","itemId":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","delta":"first"},"emittedAtMs":1790295485125}} +{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","itemId":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","delta":" fixture"},"emittedAtMs":1790295485125}} +{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","itemId":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","delta":" turn"},"emittedAtMs":1790295485125}} +{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","itemId":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","delta":" complete"},"emittedAtMs":1790295485125}} +{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","text":"first fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","completedAtMs":1790295485125},"emittedAtMs":1790295485134}} +{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","tokenUsage":{"total":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295485211}} +{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"idle"}},"emittedAtMs":1790295485220}} +{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","text":"first fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295480,"completedAt":1790295485,"durationMs":4550}},"emittedAtMs":1790295485220}} +{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"detailed","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}} +{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295485265}} +{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}} +{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295485286}} +{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295485,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295485286}} +{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-2bdf-7093-9e82-b961af1fe132","clientId":null,"content":[{"type":"text","text":"Respond with exactly: second fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","startedAtMs":1790295485409},"emittedAtMs":1790295485409}} +{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a0d5ed-2bdf-7093-9e82-b961af1fe132","clientId":null,"content":[{"type":"text","text":"Respond with exactly: second fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","completedAtMs":1790295485409},"emittedAtMs":1790295485413}} +{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","startedAtMs":1790295487332},"emittedAtMs":1790295487332}} +{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","itemId":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","delta":"second"},"emittedAtMs":1790295487332}} +{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","itemId":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","delta":" fixture"},"emittedAtMs":1790295487332}} +{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","itemId":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","delta":" turn"},"emittedAtMs":1790295487332}} +{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","itemId":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","delta":" complete"},"emittedAtMs":1790295487332}} +{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","text":"second fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","completedAtMs":1790295487382},"emittedAtMs":1790295487398}} +{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","tokenUsage":{"total":{"totalTokens":47211,"inputTokens":47195,"cachedInputTokens":28160,"cacheWriteInputTokens":0,"outputTokens":16,"reasoningOutputTokens":0},"last":{"totalTokens":25785,"inputTokens":25777,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295487407}} +{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"idle"}},"emittedAtMs":1790295487412}} +{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","text":"second fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295485,"completedAt":1790295487,"durationMs":2138}},"emittedAtMs":1790295487412}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/output.ts new file mode 100644 index 0000000000000..cca633fd5d789 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/output.ts @@ -0,0 +1,21 @@ +import { assert } from "@effect/vitest"; +import type { ProviderReplayTranscript } from "@t3tools/contracts"; + +import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts"; +import { assertBaseProjection, projectionFor } from "../shared.ts"; + +export function assertCodexModelRerouteOutput( + result: OrchestratorV2ScenarioResult, + transcript: ProviderReplayTranscript, +) { + assertBaseProjection({ + result, + transcript, + runCount: 2, + runStatuses: ["completed", "completed"], + }); + const [first, second] = projectionFor(result, transcript.scenario).providerTurns; + // The reroute names the first turn only; without new settings the second turn's model is unknown. + assert.deepEqual(first?.turnTokenUsage?.models, ["gpt-6-astra"]); + assert.notProperty(second?.turnTokenUsage, "models"); +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts index 1782f6f072a1f..f242c8e0a467d 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts @@ -106,6 +106,8 @@ import { openCode2SimpleInput } from "./opencode2_simple/input.ts"; import { openCode2SkillInput } from "./opencode2_skill/input.ts"; import { assertOpenCode2SkillOutput } from "./opencode2_skill/output.ts"; import { assertOpenCode2SimpleOutput } from "./opencode2_simple/output.ts"; +import { assertOpenCode2MissingStepUsageOutput } from "./opencode2_missing_step_usage/output.ts"; +import { assertCodexModelRerouteOutput } from "./codex_model_reroute/output.ts"; import { openCode2ToolCallInput } from "./opencode2_tool_call/input.ts"; import { assertOpenCode2ToolCallOutput } from "./opencode2_tool_call/output.ts"; import { assertOpenCodeSubagentOutput } from "./opencode_subagent/output.ts"; @@ -984,6 +986,21 @@ export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray"}}} +{"type": "emit_inbound", "label": "model.list.response", "frame": {"type": "sdk.response", "operation": "model.list", "data": {"location": {"directory": ""}, "data": [{"id": "space-bunny-free", "modelID": "space-bunny-free", "providerID": "opencode", "name": "Space Bunny Free", "compatibility": {"reasoningField": "reasoning_content"}, "package": "@opencode/ai/providers/openai-compatible", "settings": {"apiKey": "public", "baseURL": "https://opencode.ai/zen/v1", "provider": "opencode"}, "capabilities": {"tools": true, "input": ["text", "image", "video"], "output": ["text"]}, "variants": [{"id": "low", "settings": {"reasoningEffort": "low"}}, {"id": "medium", "settings": {"reasoningEffort": "medium"}}, {"id": "high", "settings": {"reasoningEffort": "high"}}, {"id": "xhigh", "settings": {"reasoningEffort": "xhigh"}}, {"id": "max", "settings": {"reasoningEffort": "max"}}], "time": {"released": 1790121600000}, "cost": [{"input": 0, "output": 0, "cache": {"read": 0, "write": 0}}], "status": "active", "enabled": true, "limit": {"context": 1048576, "input": 524288, "output": 524288}}, {"id": "big-pickle", "modelID": "big-pickle", "providerID": "opencode", "family": "big-pickle", "name": "Big Pickle", "compatibility": {"reasoningField": "reasoning_content"}, "package": "@opencode/ai/providers/openai-compatible", "settings": {"apiKey": "public", "baseURL": "https://opencode.ai/zen/v1", "provider": "opencode"}, "capabilities": {"tools": true, "input": ["text"], "output": ["text"]}, "variants": [], "time": {"released": 1760659200000}, "cost": [{"input": 0, "output": 0, "cache": {"read": 0, "write": 0}}], "status": "active", "enabled": true, "limit": {"context": 200000, "input": 160000, "output": 32000}}]}}} +{"type": "emit_inbound", "label": "server.connected", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73205b001QM7spc7rTwRevR", "type": "server.connected", "data": {}}}} +{"type": "expect_outbound", "label": "session.create", "frame": {"type": "session.create", "input": {"location": "", "model": {"providerID": "opencode", "id": "space-bunny-free", "variant": "high"}, "permissions": ""}}} +{"type": "emit_inbound", "label": "session.create.response", "frame": {"type": "sdk.response", "operation": "session.create", "data": {"data": {"id": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "projectID": "global", "model": {"id": "space-bunny-free", "providerID": "opencode", "variant": "high"}, "cost": 0, "tokens": {"input": 0, "output": 0, "reasoning": 0, "cache": {"read": 0, "write": 0}}, "time": {"created": 1790656585840, "updated": 1790656585840}, "title": "spike simple", "location": {"directory": ""}}}}} +{"type": "emit_inbound", "label": "session.created", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732070001MeC12AQ1Ds6a0a", "created": 1790656585840, "type": "session.created", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "slug": "sunny-pixel", "version": "2.0.18", "projectID": "global", "location": {"directory": ""}, "subpath": "", "title": "spike simple", "model": {"id": "space-bunny-free", "providerID": "opencode", "variant": "high"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 0, "version": 1}}}} +{"type": "emit_inbound", "label": "project.updated", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732078001oO5ghtqXkMav9d", "created": 1790656585848, "type": "project.updated", "data": {"id": "global", "canonical": "", "vcs": "git", "time": {"created": 1790656063718, "updated": 1790656063718, "active": 1790656585847}, "sandboxes": []}}}} +{"type": "expect_outbound", "label": "session.instructions.entry.put", "frame": {"type": "session.instructions.entry.put", "input": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "key": "t3-code", "value": ""}}} +{"type": "emit_inbound", "label": "session.instructions.entry.put.response", "frame": {"type": "sdk.response", "operation": "session.instructions.entry.put", "data": null}} +{"type": "expect_outbound", "label": "session.prompt", "frame": {"type": "session.prompt", "input": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "text": ""}}} +{"type": "emit_inbound", "label": "session.prompt.response", "frame": {"type": "sdk.response", "operation": "session.prompt", "data": {"data": {"id": "msg_0eb732081001RntUJfRtTXOAjd", "sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "time": {"created": 1790656585859}, "type": "user", "payload": {"text": "Think carefully step by step about whether 391 is prime, showing your reasoning, then answer in one short sentence."}, "delivery": "steer"}}}} +{"type": "emit_inbound", "label": "session.inbox.enqueued", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732083001UPoh8n1ciLGG4J", "created": 1790656585859, "type": "session.inbox.enqueued", "location": {"directory": ""}, "data": {"inboxID": "msg_0eb732081001RntUJfRtTXOAjd", "sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "item": {"type": "user", "payload": {"text": "Think carefully step by step about whether 391 is prime, showing your reasoning, then answer in one short sentence."}, "delivery": "steer"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 1, "version": 1}}}} +{"type": "emit_inbound", "label": "session.execution.started", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732089001TRfMB4IJIUtJuG", "created": 1790656585865, "type": "session.execution.started", "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk"}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 2, "version": 1}}}} +{"type": "emit_inbound", "label": "session.instructions.updated", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732098001v3n3L11aMx0r6G", "created": 1790656585880, "metadata": {"instructions": {"initial": true}}, "type": "session.instructions.updated", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "delta": {"core/environment": "27a84baf7fee37fde05d49a6aaf0f184019068a15362a38f5d1ec17ac7e8f2b7", "core/date": "bf08b8486572ab3eef677a3c9ee12468e411ae41a8f4d2fb6cf02a6ca73f1986", "core/codemode": "616a7ad8b8e40e8a71eab238dfbbe9eaf0f4a9e6fdad853226d075bfe602e1e6", "core/skill-guidance": "0d001919496102654717308c72635523bf7c3cd99c81e058cc79f2947104f9a5"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 3, "version": 2}}}} +{"type": "emit_inbound", "label": "session.inbox.delivered", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73209d001wgPxWUQRwkXvBn", "created": 1790656585885, "type": "session.inbox.delivered", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "inboxID": "msg_0eb732081001RntUJfRtTXOAjd"}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 4, "version": 1}}}} +{"type": "emit_inbound", "label": "session.step.started", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7326930015SMmHkSszcae37", "created": 1790656587411, "type": "session.step.started", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "agent": "build", "model": {"id": "space-bunny-free", "providerID": "opencode", "variant": "high"}, "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "snapshot": "99482b54df6361365fa0ed7363ccf07edaa7fc93", "started": 1790656585925}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 5, "version": 1}}}} +{"type": "emit_inbound", "label": "session.reasoning.started", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732699001FC5efnDXzkrBV3", "created": 1790656587417, "type": "session.reasoning.started", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "state": {"reasoningField": "reasoning_content"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 6, "version": 1}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732702001XkfhcVQWas7guy", "created": 1790656587522, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "Check divisibility up to sqrt("}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.2", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73277b001U6tDaZPzh5G8Ub", "created": 1790656587643, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "391) \u2248 19.77."}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.3", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732805001zRua1yhKskE6du", "created": 1790656587781, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " Primes: 2,3,5,7,"}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.4", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73286e001XXnCtQeutby7Jh", "created": 1790656587886, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "11,13,17,19.\n\n391 is"}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.5", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7328e8001vpkz0eDsHflXmv", "created": 1790656588008, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " odd, not div by 2"}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.6", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732955001YnC9O9FAgIagoL", "created": 1790656588118, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": ". 3+9+"}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.7", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732aaa001b129VgQ4aT7avM", "created": 1790656588458, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "1=13, not div by 3. Not by 5. 7: 7\u00d755=385, remainder 6. 11: 11\u00d7"}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.8", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732b29001AMm839z4dDYXHE", "created": 1790656588585, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "35=385, remainder 6. 13: "}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.9", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732ba0001Ivdi55eX7RWaIN", "created": 1790656588704, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "13\u00d730=390, remainder 1. "}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.10", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732c1f001l5voAVE8zZty1G", "created": 1790656588832, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "17: 17\u00d723=391!"}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.11", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732c95001xtU1t86iQ32FcX", "created": 1790656588949, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " 17\u00d723 = 391. Yes"}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.12", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732d3b001F922FhdbWHFFh9", "created": 1790656589115, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": ": 17\u00d723 = 340 +"}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.13", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732db1001Llbce6UsLrsMtr", "created": 1790656589234, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " 51 = 391. So "}}}} +{"type": "emit_inbound", "label": "session.reasoning.delta.14", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732de6001fDagd9vuCaT77g", "created": 1790656589286, "type": "session.reasoning.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "391 is composite."}}}} +{"type": "emit_inbound", "label": "session.text.started", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732de7001zYvkQcsI5WOzgG", "created": 1790656589287, "type": "session.text.started", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 7, "version": 1}}}} +{"type": "emit_inbound", "label": "session.text.delta", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732e50001GdabW0WKYVl32T", "created": 1790656589392, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "\u221a391 \u2248 19.8,"}}}} +{"type": "emit_inbound", "label": "session.text.delta.2", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732ed2001IBPZhAC1kx4d1v", "created": 1790656589522, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " so I need to test primes "}}}} +{"type": "emit_inbound", "label": "session.text.delta.3", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732f38001E0KjfQvDXHZ7h1", "created": 1790656589624, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "2, 3, 5, 7, "}}}} +{"type": "emit_inbound", "label": "session.text.delta.4", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732fad001JzcESOkjYwU5ik", "created": 1790656589741, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "11, 13, 17, 19: it's"}}}} +{"type": "emit_inbound", "label": "session.text.delta.5", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73301c001UBnr5x154Roys2", "created": 1790656589852, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " odd, digits sum to 13, doesn't"}}}} +{"type": "emit_inbound", "label": "session.text.delta.6", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73308e001sYejhe1LAMtvcI", "created": 1790656589966, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " end in 0/5, and 7\u00d7"}}}} +{"type": "emit_inbound", "label": "session.text.delta.7", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7331030012XzmUwjcWGmPUe", "created": 1790656590084, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "55=385, 11"}}}} +{"type": "emit_inbound", "label": "session.text.delta.8", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7331700018ST8kVeG36WRUV", "created": 1790656590192, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "\u00d735=385, 13\u00d730=390 leave remain"}}}} +{"type": "emit_inbound", "label": "session.text.delta.9", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7331df001Nm2KLtcVET4KlU", "created": 1790656590304, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "ders \u2014 but 17\u00d723 = 391"}}}} +{"type": "emit_inbound", "label": "session.text.delta.10", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb733251001HkPIEuVZxWlLIU", "created": 1790656590417, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " exactly, so the search"}}}} +{"type": "emit_inbound", "label": "session.text.delta.11", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7332bd001f1FZxccg5aNmhq", "created": 1790656590525, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " stops there.\n\n391 is not prime: it's the"}}}} +{"type": "emit_inbound", "label": "session.text.delta.12", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73333d001mIrQbkY6rbRMi3", "created": 1790656590654, "type": "session.text.delta", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " product 17 \u00d7 23."}}}} +{"type": "emit_inbound", "label": "session.reasoning.ended", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7333720010sLSSNU5xRXUwa", "created": 1790656590707, "type": "session.reasoning.ended", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "text": "Check divisibility up to sqrt(391) \u2248 19.77. Primes: 2,3,5,7,11,13,17,19.\n\n391 is odd, not div by 2. 3+9+1=13, not div by 3. Not by 5. 7: 7\u00d755=385, remainder 6. 11: 11\u00d735=385, remainder 6. 13: 13\u00d730=390, remainder 1. 17: 17\u00d723=391! 17\u00d723 = 391. Yes: 17\u00d723 = 340 + 51 = 391. So 391 is composite.", "state": {"reasoningField": "reasoning_content"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 8, "version": 1}}}} +{"type": "emit_inbound", "label": "session.text.ended", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb733378001jAPLwPeycQ4M5d", "created": 1790656590712, "type": "session.text.ended", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "text": "\u221a391 \u2248 19.8, so I need to test primes 2, 3, 5, 7, 11, 13, 17, 19: it's odd, digits sum to 13, doesn't end in 0/5, and 7\u00d755=385, 11\u00d735=385, 13\u00d730=390 leave remainders \u2014 but 17\u00d723 = 391 exactly, so the search stops there.\n\n391 is not prime: it's the product 17 \u00d7 23."}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 9, "version": 1}}}} +{"type": "emit_inbound", "label": "session.step.streamed", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73337f001Y6nJkjv1tXkqGt", "created": 1790656590719, "type": "session.step.streamed", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT"}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 10, "version": 1}}}} +{"type": "emit_inbound", "label": "session.step.ended", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb733390001vg5GRCuNzMFbCA", "created": 1790656590736, "type": "session.step.ended", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "finish": "stop", "rawFinish": "stop", "cost": 0, "tokens": {"input": 8701, "output": 113, "reasoning": 147, "cache": {"read": 489, "write": 0}}, "snapshot": "99482b54df6361365fa0ed7363ccf07edaa7fc93", "files": []}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 11, "version": 1}}}} +{"type": "emit_inbound", "label": "session.usage.updated", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb733396001Ke5QhqiR5CdvP6", "created": 1790656590742, "type": "session.usage.updated", "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "cost": 0, "tokens": {"input": 8701, "output": 113, "reasoning": 147, "cache": {"read": 489, "write": 0}}}}}} +{"type": "emit_inbound", "label": "session.step.started.2", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7333a1001missingStepStart", "created": 1790656590750, "type": "session.step.started", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "agent": "build", "model": {"id": "space-bunny-free", "providerID": "opencode", "variant": "high"}, "assistantMessageID": "msg_0eb7333a0001missingStepUsage", "snapshot": "99482b54df6361365fa0ed7363ccf07edaa7fc93", "started": 1790656590750}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 12, "version": 1}}}} +{"type": "emit_inbound", "label": "session.step.failed", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7333a2001missingStepFailed", "created": 1790656590760, "type": "session.step.failed", "location": {"directory": ""}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7333a0001missingStepUsage", "error": {"type": "provider_error", "message": "Stream closed before usage was reported"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 13, "version": 1}}}} +{"type": "emit_inbound", "label": "session.execution.succeeded", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb733399001NhwTrB32UU6d6H", "created": 1790656590745, "type": "session.execution.succeeded", "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk"}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 14, "version": 1}}}} +{"type": "runtime_exit", "status": "success"} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_missing_step_usage/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_missing_step_usage/output.ts new file mode 100644 index 0000000000000..68474abb954f2 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_missing_step_usage/output.ts @@ -0,0 +1,22 @@ +import { assert } from "@effect/vitest"; +import type { ProviderReplayTranscript } from "@t3tools/contracts"; + +import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts"; +import { assertBaseProjection, projectionFor } from "../shared.ts"; + +export function assertOpenCode2MissingStepUsageOutput( + result: OrchestratorV2ScenarioResult, + transcript: ProviderReplayTranscript, +) { + assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] }); + const [providerTurn] = projectionFor(result, transcript.scenario).providerTurns; + assert.equal(providerTurn?.status, "completed"); + // The measured step survives; the step without a report keeps the turn total partial. + assert.deepInclude(providerTurn?.turnTokenUsage, { + usageStatus: "partial", + inputTokens: 8701 + 489, + outputTokens: 113 + 147, + reasoningTokens: 147, + models: ["opencode/space-bunny-free"], + }); +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_simple/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_simple/output.ts index 1626a07900415..b56ac6c810ff5 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_simple/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_simple/output.ts @@ -41,6 +41,7 @@ export function assertOpenCode2SimpleOutput( cachedInputTokens: 489, outputTokens: 113 + 147, reasoningTokens: 147, + models: ["opencode/space-bunny-free"], }); assert.deepInclude(providerTurn?.tokenUsage, { usedTokens: 8701 + 489 + 113, diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.ts index f87dd62976059..d9f6d3e66c879 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.ts @@ -83,4 +83,14 @@ export function assertSubagentV2Output( "child thread must contain the post-root subagent response", ); assert.equal(childProjection.providerTurns[0]?.status, "completed"); + + // Codex reports each agent's counts on its own turn. Only the root's model was reported. + assert.deepInclude(projection.providerTurns[0]?.turnTokenUsage, { + usageStatus: "complete", + outputTokens: 69, + models: ["gpt-6-luna"], + }); + const childUsage = childProjection.providerTurns[0]?.turnTokenUsage; + assert.deepInclude(childUsage, { usageStatus: "complete", outputTokens: 6 }); + assert.notProperty(childUsage, "models"); } diff --git a/apps/server/src/provider/ClaudeTurnTokenUsage.ts b/apps/server/src/provider/ClaudeTurnTokenUsage.ts index 79eaaa60a11ce..2fa6a11bac1e5 100644 --- a/apps/server/src/provider/ClaudeTurnTokenUsage.ts +++ b/apps/server/src/provider/ClaudeTurnTokenUsage.ts @@ -49,12 +49,96 @@ function withEarlierSegmentUsage( return total; } +/** Per-model totals from the SDK's `modelUsage`, which grows for the life of one CLI process. */ +export type ClaudeModelLedger = ReadonlyMap< + string, + { readonly input: number; readonly output: number } +>; + +export interface ClaudeLedgerUsage { + readonly inputTokens: number; + readonly outputTokens: number; +} + +/** Unknown when absent or empty: a process that did model work never reports an empty ledger. */ +export function claudeModelLedger(modelUsage: unknown): ClaudeModelLedger | undefined { + if (typeof modelUsage !== "object" || modelUsage === null) return undefined; + if (Object.keys(modelUsage).length === 0) return undefined; + const ledger = new Map(); + for (const [model, entry] of Object.entries(modelUsage as Record)) { + const fields = (entry ?? {}) as Record; + const input = finiteNonNegativeInteger(fields.inputTokens); + const output = finiteNonNegativeInteger(fields.outputTokens); + if (input === undefined || output === undefined) return undefined; + const cacheRead = finiteNonNegativeInteger(fields.cacheReadInputTokens) ?? 0; + const cacheWrite = finiteNonNegativeInteger(fields.cacheCreationInputTokens) ?? 0; + ledger.set(model, { input: input + cacheRead + cacheWrite, output }); + } + return ledger; +} + +/** Ledger growth since `previous`. Unknown without a baseline or when a counter goes backwards. */ +export function claudeLedgerDelta( + previous: ClaudeModelLedger | undefined, + current: ClaudeModelLedger | undefined, +): ClaudeLedgerUsage | undefined { + if (previous === undefined || current === undefined) return undefined; + let inputTokens = 0; + let outputTokens = 0; + for (const [model, before] of previous) { + const after = current.get(model); + if (after === undefined || after.input < before.input || after.output < before.output) { + return undefined; + } + } + for (const [model, after] of current) { + const before = previous.get(model); + inputTokens += after.input - (before?.input ?? 0); + outputTokens += after.output - (before?.output ?? 0); + } + return { inputTokens, outputTokens }; +} + +export function addClaudeLedgerUsage( + left: ClaudeLedgerUsage | undefined, + right: ClaudeLedgerUsage | undefined, +): ClaudeLedgerUsage | undefined { + return left === undefined || right === undefined + ? undefined + : { + inputTokens: left.inputTokens + right.inputTokens, + outputTokens: left.outputTokens + right.outputTokens, + }; +} + +export interface ClaudeTurnObservations { + // Models on the turn's root assistant messages. + readonly rootModels?: ReadonlySet; + // Ledger growth across every result this turn consumed, including steered segments. + readonly ledger?: ClaudeLedgerUsage | undefined; +} + export function normalizeClaudeTurnTokenUsage( - result: { readonly subtype: SDKResultMessage["subtype"]; readonly usage?: unknown } | undefined, + result: + | { + readonly subtype: SDKResultMessage["subtype"]; + readonly usage?: unknown; + readonly local_command?: unknown; + } + | undefined, hasSubagents: boolean, terminalStatus: RuntimeTurnState, earlierSegmentUsage: ReadonlyArray = [], + observed: ClaudeTurnObservations = {}, ): TurnTokenUsage { + const observedFields = { + ...(observed.rootModels !== undefined && observed.rootModels.size > 0 + ? { models: [...observed.rootModels] } + : {}), + ...(typeof result?.local_command === "string" && result.local_command.length > 0 + ? { localCommand: true } + : {}), + }; const finalUsage = result?.usage as Record | undefined; const usage = withEarlierSegmentUsage(finalUsage ?? {}, earlierSegmentUsage); const uncachedInputTokens = finiteNonNegativeInteger(usage.input_tokens); @@ -89,10 +173,25 @@ export function normalizeClaudeTurnTokenUsage( usageStatus: "unavailable", usageScope: "main_agent", hasSubagents, + ...observedFields, }; } + // The result omits subagent and compaction work that the process-wide ledger records. + const otherUsage = + observed.ledger !== undefined && + inputTokens !== undefined && + rawOutputTokens !== undefined && + observed.ledger.inputTokens >= inputTokens && + observed.ledger.outputTokens >= rawOutputTokens + ? { + inputTokens: observed.ledger.inputTokens - inputTokens, + outputTokens: observed.ledger.outputTokens - rawOutputTokens, + } + : undefined; const commonUsage = { + ...observedFields, + ...(otherUsage === undefined ? {} : { otherUsage }), usageScope: "main_agent", ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}), ...(cacheCreationTokens !== undefined ? { cacheCreationTokens } : {}), diff --git a/apps/server/src/provider/CodexTurnTokenUsage.ts b/apps/server/src/provider/CodexTurnTokenUsage.ts index 7b0f20a123ffe..7b2524464b0e0 100644 --- a/apps/server/src/provider/CodexTurnTokenUsage.ts +++ b/apps/server/src/provider/CodexTurnTokenUsage.ts @@ -133,27 +133,23 @@ export function accumulateCodexTurnTokenUsage( } } +/** `model` is the thread model Codex last reported, which a reroute replaces. */ export function completeCodexTurnTokenUsage( state: CodexTurnTokenUsageState, turnId: string, completed: boolean, + model?: string, ): TurnTokenUsage { const usage = state.byTurnId.get(turnId); state.byTurnId.delete(turnId); if (state.activeTurnId === turnId) state.activeTurnId = undefined; - if (!usage) { + const models = model === undefined ? {} : { models: [model] }; + if (!usage?.observed) { return { usageStatus: "unavailable", usageScope: "main_agent", - hasSubagents: false, - }; - } - - if (!usage.observed) { - return { - usageStatus: "unavailable", - usageScope: "main_agent", - hasSubagents: usage.hasSubagents, + hasSubagents: usage?.hasSubagents ?? false, + ...models, }; } @@ -169,5 +165,6 @@ export function completeCodexTurnTokenUsage( outputTokens: usage.outputTokens, reasoningTokens: Math.min(usage.outputTokens, usage.reasoningTokens), hasSubagents: usage.hasSubagents, + ...models, }; } diff --git a/apps/server/src/provider/TurnTokenUsage.test.ts b/apps/server/src/provider/TurnTokenUsage.test.ts index 06802143e73c1..fb14511211e36 100644 --- a/apps/server/src/provider/TurnTokenUsage.test.ts +++ b/apps/server/src/provider/TurnTokenUsage.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from "vite-plus/test"; -import { normalizeClaudeTurnTokenUsage } from "./ClaudeTurnTokenUsage.ts"; +import { + claudeLedgerDelta, + claudeModelLedger, + normalizeClaudeTurnTokenUsage, +} from "./ClaudeTurnTokenUsage.ts"; import { accumulateCodexTurnTokenUsage, completeCodexTurnTokenUsage, @@ -209,6 +213,15 @@ describe("billable native turn usage", () => { }, ); + it("measures Claude ledger growth only from a known, nondecreasing baseline", () => { + const ledger = (output: number) => + claudeModelLedger({ "claude-sonnet-4-6": { inputTokens: 100, outputTokens: output } }); + expect(claudeLedgerDelta(ledger(10), ledger(25))).toEqual({ inputTokens: 0, outputTokens: 15 }); + expect(claudeLedgerDelta(ledger(25), ledger(10))).toBeUndefined(); + expect(claudeLedgerDelta(undefined, ledger(10))).toBeUndefined(); + expect(claudeModelLedger({})).toBeUndefined(); + }); + it("adds Claude steering segments to the final measured result once", () => { expect( normalizeClaudeTurnTokenUsage( diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d0d51a0b241ba..9d7dc2f27b14d 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -47,7 +47,7 @@ import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewG import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import * as DelegatedTaskAnalytics from "./telemetry/DelegatedTaskAnalytics.ts"; -import * as ProviderEventIngestor from "./orchestration-v2/ProviderEventIngestor.ts"; +import * as ProviderUsageAnalytics from "./telemetry/ProviderUsageAnalytics.ts"; import * as ModelManifest from "./provider/ModelManifest.ts"; import * as ResetCreditCoordinator from "./provider/resetCreditCoordinator.ts"; import * as EventNdjsonLogger from "./provider/EventNdjsonLogger.ts"; @@ -558,7 +558,7 @@ const layerScheduledTaskWebhookOrigin = Layer.effect( const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe( Layer.provide(layerScheduledTaskWebhookOrigin), - Layer.provide(ProviderEventIngestor.layerAnalytics), + Layer.provide(ProviderUsageAnalytics.layer), Layer.provide(layerCheckpointStore), Layer.provide(layerGitWorkflow), Layer.provide( diff --git a/apps/server/src/telemetry/ProviderDimensions.ts b/apps/server/src/telemetry/ProviderDimensions.ts index 4e0447a1e2c44..f81a22e844aef 100644 --- a/apps/server/src/telemetry/ProviderDimensions.ts +++ b/apps/server/src/telemetry/ProviderDimensions.ts @@ -4,6 +4,8 @@ import type { ServerProvider, } from "@t3tools/contracts"; +import { BUNDLED_MODEL_MANIFEST } from "../provider/ModelManifest.ts"; + /** * Drivers whose model catalogs are published by the vendor. Other drivers * (OpenCode, Pi, ACP agents) list models from the user's own configuration, @@ -39,6 +41,44 @@ export function providerDimensions( : { provider: provider.driver }; } +const DATED_SNAPSHOT = /-\d{8}$/u; + +// The bundled manifest is reviewed in this repo. Codex lists whatever its configured +// model provider serves, so only the manifest vouches for Codex, Claude, and Antigravity. +const MANIFEST_LABELS: ReadonlyMap = new Map( + Object.values(BUNDLED_MODEL_MANIFEST.providers ?? {}).flatMap((catalog) => + catalog.models.flatMap((model) => + [model.slug, ...(model.aliases ?? [])].map((name) => [name, model.slug] as const), + ), + ), +); +const REGISTRY_LABEL_DRIVERS: ReadonlySet = new Set(["cursor", "grok"]); + +/** + * The vendor catalog slug that a native or routed model id names, such as + * `anthropic/claude-opus-5-5` or a dated snapshot. Models outside the bundled + * manifest and the Cursor and Grok catalogs, including user-added ones, return undefined. + */ +export function catalogModelLabel( + providers: ReadonlyArray, + model: string, +): string | undefined { + const leaf = model.slice(model.lastIndexOf("/") + 1); + const candidates = [model, leaf, leaf.replace(DATED_SNAPSHOT, "")]; + for (const candidate of candidates) { + const label = MANIFEST_LABELS.get(candidate); + if (label !== undefined) return label; + } + for (const provider of providers) { + if (!REGISTRY_LABEL_DRIVERS.has(provider.driver)) continue; + const match = provider.models.find( + (entry) => !entry.isCustom && candidates.includes(entry.slug), + ); + if (match !== undefined) return match.slug; + } + return undefined; +} + /** The thread fields agent analytics reads. Ids are used for lookups, never reported. */ export type AgentThread = Pick< OrchestrationV2ThreadShell, diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts new file mode 100644 index 0000000000000..4e277af4d11a6 --- /dev/null +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts @@ -0,0 +1,323 @@ +import { + NodeId, + ProviderInstanceId, + ProviderThreadId, + ProviderTurnId, + RunId, + type OrchestrationV2ProviderTurn, + type ServerProvider, + type TurnTokenUsage, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as AnalyticsService from "./AnalyticsService.ts"; +import { catalogModelLabel } from "./ProviderDimensions.ts"; +import { + ProviderTurnAnalytics, + RequestUsageLedger, + layer, + providerTurnProperties, + type ProviderTurnAnalyticsContext, + type ProviderTurnSegment, +} from "./ProviderUsageAnalytics.ts"; + +const providers = [ + // Codex lists whatever its configured model provider serves, including private deployments. + { driver: "codex", models: [{ slug: "gpt-6-sol" }, { slug: "acme-azure-deployment" }] }, + { driver: "claudeAgent", models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }] }, + { driver: "opencode", models: [{ slug: "ollama/acme-internal" }] }, +].map( + ({ driver, models }) => + ({ + instanceId: ProviderInstanceId.make(driver), + driver, + models: models.map((model) => ({ ...model, isCustom: false })), + }) as unknown as ServerProvider, +); +const label = (model: string) => catalogModelLabel(providers, model); + +const at = (ms: number) => DateTime.makeUnsafe(ms); +const complete = (input: number, output: number, extra: Partial = {}) => + ({ + usageStatus: "complete", + usageScope: "main_agent", + hasSubagents: false, + inputTokens: input, + outputTokens: output, + ...extra, + }) as TurnTokenUsage; + +const turn = ( + id: string, + usage: TurnTokenUsage | undefined, + status: OrchestrationV2ProviderTurn["status"] = "completed", +): OrchestrationV2ProviderTurn => ({ + id: ProviderTurnId.make(id), + providerThreadId: ProviderThreadId.make("provider-thread"), + nodeId: NodeId.make(`node:${id}`), + runAttemptId: null, + nativeTurnRef: null, + ordinal: 1, + status, + startedAt: at(1_000), + completedAt: at(4_000), + ...(usage === undefined ? {} : { turnTokenUsage: usage }), +}); + +const context = ( + runId: string, + segment: ProviderTurnSegment, + model = "gpt-6-sol", +): ProviderTurnAnalyticsContext => ({ + runId: RunId.make(runId), + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model, + options: [{ id: "reasoningEffort", value: "xhigh" }], + }, + runtimeMode: "full-access", + interactionMode: "default", + origin: { createdBy: "user", creationSource: "web", scheduled: false, subagent: false }, + segment, +}); + +const settled = (runId: string, childrenRunning = false) => ({ + runId: RunId.make(runId), + status: "completed" as const, + completedAt: at(9_000), + childrenRunning, +}); + +describe("provider usage reporting", () => { + it.effect( + "records one request across a continuation, a child, a replay, and a late child", + () => { + const recorded: Array = []; + const layerTest = layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(AnalyticsService.AnalyticsService)({ + record: (event, properties) => + Effect.sync(() => void recorded.push([event, properties])), + }), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed(providers), + }), + ), + ), + ); + return Effect.gen(function* () { + const analytics = yield* ProviderTurnAnalytics; + const root = context("run-a", "initial"); + yield* analytics.runStarted({ runId: RunId.make("run-a"), driver: "codex", context: root }); + const first = { driver: "codex", context: root }; + const firstTurn = turn("root", complete(100, 10, { models: ["gpt-6-sol"] })); + yield* analytics.turnCompleted({ ...first, providerTurn: firstTurn }); + yield* analytics.turnCompleted({ ...first, providerTurn: firstTurn }); + yield* analytics.turnCompleted({ + driver: "codex", + context: context("run-a", "continuation"), + providerTurn: turn("goal", complete(50, 5, { models: ["gpt-6-sol"] })), + }); + yield* analytics.turnCompleted({ + driver: "codex", + context: context("run-a", "native_child"), + providerTurn: turn("child", complete(20, 2)), + }); + yield* analytics.runSettled(settled("run-a")); + yield* analytics.turnCompleted({ + driver: "codex", + context: context("run-a", "native_child"), + providerTurn: turn("late-child", complete(7, 1)), + }); + yield* analytics.runSettled(settled("run-a")); + yield* analytics.runStarted({ + runId: RunId.make("run-b"), + driver: "codex", + context: context("run-b", "initial"), + }); + yield* analytics.runSettled(settled("run-b")); + + const requests = recorded.filter(([event]) => event === "provider.request.completed"); + expect(recorded.filter(([event]) => event === "provider.turn.completed")).toHaveLength(5); + expect(requests).toHaveLength(2); + // The whole payload: no run, turn, or thread ids, prompts, or raw model names. + expect(requests[0]?.[1]).toEqual({ + reportVersion: 2, + provider: "codex", + requestKind: "user", + terminalStatus: "completed", + lifecycleObserved: true, + model: "gpt-6-sol", + effort: "xhigh", + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "user", + creationSource: "web", + scheduled: false, + subagent: false, + providerTurns: 2, + continuations: 1, + steeringRestarts: 0, + usageStatus: "complete", + inputTokens: 150, + outputTokens: 15, + nativeChildTurns: 1, + childUsageStatus: "complete", + childInputTokens: 20, + childOutputTokens: 2, + durationMs: 8_000, + }); + expect(requests[1]?.[1]).toMatchObject({ providerTurns: 0, usageStatus: "unavailable" }); + }).pipe(Effect.provide(layerTest)); + }, + ); + + it("keeps a request partial when its start, a steered segment, or a counter is missing", () => { + const ledger = new RequestUsageLedger(); + ledger.start(RunId.make("restarted"), "codex", { + ...context("restarted", "initial"), + restartContinuation: true, + }); + ledger.add({ + driver: "codex", + context: context("restarted", "initial"), + providerTurn: turn("after-restart", complete(10, 1)), + }); + expect(ledger.settle(settled("restarted"), label)).toMatchObject({ + restartContinuation: true, + lifecycleObserved: false, + usageStatus: "partial", + inputTokens: 10, + }); + + ledger.start(RunId.make("steered"), "claudeAgent", context("steered", "initial")); + ledger.add({ + driver: "claudeAgent", + context: context("steered", "initial"), + providerTurn: turn( + "steered-away", + { usageStatus: "partial", usageScope: "main_agent", hasSubagents: false, outputTokens: 4 }, + "interrupted", + ), + }); + ledger.add({ + driver: "claudeAgent", + context: context("steered", "steering_restart"), + providerTurn: turn("steered-to", complete(30, 6)), + }); + expect(ledger.settle(settled("steered"), label)).toMatchObject({ + usageStatus: "partial", + steeringRestarts: 1, + inputTokens: 30, + outputTokens: 10, + }); + + ledger.start(RunId.make("silent"), "grok", context("silent", "initial")); + ledger.add({ + driver: "grok", + context: context("silent", "initial"), + providerTurn: turn("silent", undefined), + }); + const silent = ledger.settle(settled("silent", true), label); + expect(silent).toMatchObject({ + usageStatus: "unavailable", + childrenRunning: true, + childUsageStatus: "unavailable", + }); + expect(silent).not.toHaveProperty("outputTokens"); + }); + + it("confirms only the models a provider reported", () => { + const opus = context("models", "initial", "claude-opus-5-5"); + const properties = (usage: TurnTokenUsage | undefined) => + providerTurnProperties( + { driver: "claudeAgent", context: opus, providerTurn: turn("t", usage) }, + label, + ); + expect(properties(complete(1, 1, { models: ["claude-haiku-4-5-20251001"] }))).toMatchObject({ + model: "claude-opus-5-5", + observedModel: "claude-haiku-4-5", + mixedModels: false, + }); + const unconfirmed = properties(complete(1, 1)); + expect(unconfirmed).toMatchObject({ model: "claude-opus-5-5" }); + expect(unconfirmed).not.toHaveProperty("mixedModels"); + expect(properties(complete(1, 1, { models: ["a", "b"] }))).toMatchObject({ mixedModels: true }); + + const ledger = new RequestUsageLedger(); + ledger.start(RunId.make("mixed"), "codex", context("mixed", "initial")); + ledger.add({ + driver: "codex", + context: context("mixed", "initial"), + providerTurn: turn("root", complete(1, 1, { models: ["gpt-6-sol"] })), + }); + ledger.add({ + driver: "codex", + context: context("mixed", "native_child"), + providerTurn: turn("child", complete(1, 1, { models: ["gpt-6-luna"] })), + }); + expect(ledger.settle(settled("mixed"), label)).toMatchObject({ mixedModels: true }); + }); + + it("keeps zero, absent, local-command, and ledger usage distinct", () => { + const properties = (usage: TurnTokenUsage | undefined) => + providerTurnProperties( + { driver: "claudeAgent", context: context("z", "initial"), providerTurn: turn("t", usage) }, + label, + ); + expect(properties(complete(0, 0))).toMatchObject({ + usageStatus: "complete", + usageReported: true, + inputTokens: 0, + outputTokens: 0, + }); + const absent = properties(undefined); + expect(absent).toMatchObject({ usageStatus: "unavailable", usageReported: false }); + expect(absent).not.toHaveProperty("outputTokens"); + expect( + properties( + complete(0, 0, { localCommand: true, otherUsage: { inputTokens: 900, outputTokens: 80 } }), + ), + ).toMatchObject({ localCommand: true, otherInputTokens: 900, otherOutputTokens: 80 }); + expect(properties(complete(74_167, 236, { reasoningTokens: 30 }))).toMatchObject({ + outputTokens: 236, + reasoningTokens: 30, + }); + }); + + it("reports routed catalog models and closed efforts only", () => { + const routed = (model: string, variant: string) => + providerTurnProperties( + { + driver: "opencode", + context: { + modelSelection: { + instanceId: ProviderInstanceId.make("opencode"), + model, + options: [{ id: "variant", value: variant }], + }, + }, + providerTurn: turn("t", complete(1, 1, { models: [model] })), + }, + label, + ); + expect(routed("my-proxy/claude-opus-5-5", "high")).toMatchObject({ + model: "claude-opus-5-5", + observedModel: "claude-opus-5-5", + effort: "high", + }); + for (const local of [ + routed("ollama/acme-internal", "secret-variant"), + routed("acme-azure-deployment", "high"), + ]) { + expect(local).not.toHaveProperty("model"); + expect(local).not.toHaveProperty("observedModel"); + } + expect(routed("ollama/acme-internal", "secret-variant")).not.toHaveProperty("effort"); + }); +}); diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.ts new file mode 100644 index 0000000000000..96a00d596554d --- /dev/null +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.ts @@ -0,0 +1,407 @@ +/** + * Provider token reporting: one `provider.turn.completed` per provider turn and one + * `provider.request.completed` per run, built from the same turns so each counts once. + * + * @module ProviderUsageAnalytics + */ +import type { + ModelSelection, + OrchestrationV2Actor, + OrchestrationV2CreationSource, + OrchestrationV2ProviderTurn, + OrchestrationV2RunAttempt, + ProviderInteractionMode, + RunId, + RuntimeMode, + TurnTokenUsage, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as AnalyticsService from "./AnalyticsService.ts"; +import { catalogModelLabel } from "./ProviderDimensions.ts"; + +// Bump when a field changes meaning, so reports can split old and new rows. +const REPORT_VERSION = 2; + +/** + * Where the run's starting message came from. Most turns start without a + * person (provider continuations, agent sends, delegated subagents), so + * reports need this to tell user turns apart. + */ +export interface ProviderTurnOrigin { + readonly createdBy: OrchestrationV2Actor; + readonly creationSource: OrchestrationV2CreationSource; + readonly scheduled: boolean; + readonly subagent: boolean; +} + +/** What started this provider turn inside its run. */ +export type ProviderTurnSegment = + | OrchestrationV2RunAttempt["reason"] + | "continuation" + | "native_child"; + +export interface ProviderTurnAnalyticsContext { + readonly runId?: RunId; + readonly modelSelection: ModelSelection; + readonly runtimeMode?: RuntimeMode; + readonly interactionMode?: ProviderInteractionMode; + readonly origin?: ProviderTurnOrigin; + readonly segment?: ProviderTurnSegment; + readonly restartContinuation?: boolean; +} + +export interface ProviderTurnReport { + readonly driver: string; + readonly providerTurn: OrchestrationV2ProviderTurn; + readonly context?: ProviderTurnAnalyticsContext; +} + +export interface RunSettledReport { + readonly runId: RunId; + readonly status: OrchestrationV2ProviderTurn["status"]; + readonly completedAt: DateTime.Utc; + // Run-owned children were still open when the run settled; their later turns are not added. + readonly childrenRunning: boolean; +} + +type Properties = Readonly>; +/** Maps a native model id to a vendor catalog label, or undefined to keep it out. */ +export type ModelLabeler = (model: string) => string | undefined; + +const TERMINAL_STATUSES: ReadonlySet = new Set([ + "completed", + "failed", + "interrupted", + "cancelled", +]); + +const REPORTED_EFFORTS: ReadonlySet = new Set([ + "none", + "minimal", + "low", + "medium", + "high", + "xhigh", + "max", + "ultrathink", + "ultracode", + "brutal", +]); + +const defined = (entries: Properties): Properties => + Object.fromEntries(Object.entries(entries).filter(([, value]) => value !== undefined)); + +// OpenCode names its effort option `variant`, and variants can be user-defined. +function selectedEffort(selection: ModelSelection): string | undefined { + const effort = + getModelSelectionStringOptionValue(selection, "reasoningEffort") ?? + getModelSelectionStringOptionValue(selection, "effort") ?? + getModelSelectionStringOptionValue(selection, "variant"); + return effort !== undefined && REPORTED_EFFORTS.has(effort) ? effort : undefined; +} + +/** + * Confirmed models across counted work. Unknown when any piece of work has no + * reported model, unless two distinct models were already seen. + */ +function modelObservation( + models: ReadonlyArray | undefined>, + label: ModelLabeler, +): Properties { + const distinct = new Set(models.flatMap((entry) => entry ?? [])); + if (distinct.size > 1) return { mixedModels: true }; + if (distinct.size === 0 || models.some((entry) => entry === undefined || entry.length === 0)) { + return {}; + } + return defined({ mixedModels: false, observedModel: label([...distinct][0]!) }); +} + +function selectionProperties( + context: ProviderTurnAnalyticsContext | undefined, + label: ModelLabeler, +) { + const selection = context?.modelSelection; + return defined({ + model: selection === undefined ? undefined : label(selection.model), + effort: selection === undefined ? undefined : selectedEffort(selection), + runtimeMode: context?.runtimeMode, + interactionMode: context?.interactionMode, + ...context?.origin, + }); +} + +function childKind(context: ProviderTurnAnalyticsContext | undefined) { + if (context?.segment === "native_child") return "native"; + return context?.origin?.subagent === true ? "t3" : undefined; +} + +function counters(usage: TurnTokenUsage | undefined): Properties { + return defined({ + inputTokens: usage?.inputTokens, + cachedInputTokens: usage?.cachedInputTokens, + cacheCreationTokens: usage?.cacheCreationTokens, + outputTokens: usage?.outputTokens, + reasoningTokens: usage?.reasoningTokens, + }); +} + +export function providerTurnProperties( + report: ProviderTurnReport, + label: ModelLabeler, +): Properties { + const { providerTurn, context } = report; + const usage = providerTurn.turnTokenUsage; + return defined({ + reportVersion: REPORT_VERSION, + provider: report.driver, + terminalStatus: providerTurn.status, + usageStatus: usage?.usageStatus ?? "unavailable", + usageScope: usage?.usageScope ?? "main_agent", + usageReported: usage !== undefined, + hasSubagents: usage?.hasSubagents, + ...counters(usage), + localCommand: usage?.localCommand === true ? true : undefined, + otherInputTokens: usage?.otherUsage?.inputTokens, + otherOutputTokens: usage?.otherUsage?.outputTokens, + ...selectionProperties(context, label), + ...modelObservation([usage?.models], label), + segment: context?.segment, + childKind: childKind(context), + durationMs: + providerTurn.startedAt && providerTurn.completedAt + ? Math.max( + 0, + DateTime.toEpochMillis(providerTurn.completedAt) - + DateTime.toEpochMillis(providerTurn.startedAt), + ) + : undefined, + }); +} + +/** How the request reached the provider; only `user` counts as a person asking. */ +function requestKind(origin: ProviderTurnOrigin | undefined) { + if (origin === undefined) return "unknown"; + if (origin.scheduled) return "scheduled"; + if (origin.subagent) return "t3_child"; + if (origin.createdBy === "user") return "user"; + if (origin.creationSource === "provider") return "provider_continuation"; + return origin.createdBy; +} + +function sumOf( + usages: ReadonlyArray, + field: + | "inputTokens" + | "cachedInputTokens" + | "cacheCreationTokens" + | "outputTokens" + | "reasoningTokens", + requireAll: boolean, +): number | undefined { + const values = usages.map((usage) => usage[field]); + const known = values.filter((value) => value !== undefined); + if (known.length === 0 || (requireAll && known.length < values.length)) return undefined; + return known.reduce((sum, value) => sum + value, 0); +} + +/** complete only when every turn is complete; partial when any turn has counts. */ +function combinedStatus(usages: ReadonlyArray) { + if (usages.length > 0 && usages.every((usage) => usage?.usageStatus === "complete")) { + return "complete"; + } + return usages.some( + (usage) => usage?.inputTokens !== undefined || usage?.outputTokens !== undefined, + ) + ? "partial" + : "unavailable"; +} + +interface RequestTurn { + readonly child: boolean; + readonly segment: ProviderTurnSegment | undefined; + readonly providerTurn: OrchestrationV2ProviderTurn; +} + +interface RequestEntry { + driver: string | undefined; + context: ProviderTurnAnalyticsContext | undefined; + readonly lifecycleObserved: boolean; + readonly turns: Map; +} + +const MAX_TRACKED_RUNS = 2048; + +/** + * Collects terminal provider turns per run in this process. A replayed turn + * replaces its earlier copy, a settled run ignores late turns, and a run whose + * initial attempt started before this process reports `lifecycleObserved: false`. + */ +export class RequestUsageLedger { + private readonly open = new Map(); + private readonly settled = new Set(); + + start(runId: RunId, driver: string, context: ProviderTurnAnalyticsContext): void { + if (this.settled.has(runId) || this.open.has(runId)) return; + // A restart continuation carries on a run whose earlier turns this process never saw. + const lifecycleObserved = context.restartContinuation !== true; + this.open.set(runId, { driver, context, lifecycleObserved, turns: new Map() }); + evictOldest(this.open); + } + + add(report: ProviderTurnReport): void { + const runId = report.context?.runId; + if (runId === undefined || this.settled.has(runId)) return; + if (!TERMINAL_STATUSES.has(report.providerTurn.status)) return; + let entry = this.open.get(runId); + if (entry === undefined) { + entry = { driver: undefined, context: undefined, lifecycleObserved: false, turns: new Map() }; + this.open.set(runId, entry); + evictOldest(this.open); + } + const child = report.context?.segment === "native_child"; + if (!child) { + entry.driver ??= report.driver; + entry.context ??= report.context; + } + entry.turns.set(String(report.providerTurn.id), { + child, + segment: report.context?.segment, + providerTurn: report.providerTurn, + }); + } + + settle(report: RunSettledReport, label: ModelLabeler): Properties | undefined { + if (this.settled.has(report.runId)) return undefined; + this.settled.add(report.runId); + evictOldest(this.settled); + const entry = this.open.get(report.runId); + this.open.delete(report.runId); + if (entry === undefined) return undefined; + + const turns = [...entry.turns.values()]; + const root = turns.filter((turn) => !turn.child); + const children = turns.filter((turn) => turn.child); + const rootUsage = root.map((turn) => turn.providerTurn.turnTokenUsage); + const childUsage = children.map((turn) => turn.providerTurn.turnTokenUsage); + const { lifecycleObserved } = entry; + const measuredRoot = rootUsage.filter((usage) => usage !== undefined); + const status = combinedStatus(rootUsage); + const rootComplete = status === "complete"; + const otherUsage = measuredRoot.map((usage) => usage.otherUsage); + const allOtherKnown = otherUsage.length > 0 && otherUsage.every((usage) => usage !== undefined); + const anyRootSubagents = measuredRoot.some((usage) => usage.hasSubagents); + const measuredChildren = childUsage.filter((usage) => usage !== undefined); + const childStatus = + children.length === 0 && !anyRootSubagents && !report.childrenRunning + ? "none" + : children.length === 0 + ? "unavailable" + : report.childrenRunning && combinedStatus(childUsage) === "complete" + ? "partial" + : combinedStatus(childUsage); + const startedAt = turns + .map((turn) => turn.providerTurn.startedAt) + .filter((value) => value !== null) + .map(DateTime.toEpochMillis); + + return defined({ + reportVersion: REPORT_VERSION, + provider: entry.driver ?? "unknown", + requestKind: requestKind(entry.context?.origin), + restartContinuation: entry.context?.restartContinuation === true ? true : undefined, + terminalStatus: report.status, + lifecycleObserved, + ...selectionProperties(entry.context, label), + providerTurns: root.length, + continuations: root.filter((turn) => turn.segment === "continuation").length, + steeringRestarts: root.filter((turn) => turn.segment === "steering_restart").length, + usageStatus: lifecycleObserved || status === "unavailable" ? status : "partial", + inputTokens: sumOf(measuredRoot, "inputTokens", rootComplete), + cachedInputTokens: sumOf(measuredRoot, "cachedInputTokens", true), + cacheCreationTokens: sumOf(measuredRoot, "cacheCreationTokens", true), + outputTokens: sumOf(measuredRoot, "outputTokens", rootComplete), + reasoningTokens: sumOf(measuredRoot, "reasoningTokens", true), + localCommand: measuredRoot.some((usage) => usage.localCommand === true) ? true : undefined, + otherInputTokens: allOtherKnown + ? otherUsage.reduce((sum, usage) => sum + (usage?.inputTokens ?? 0), 0) + : undefined, + otherOutputTokens: allOtherKnown + ? otherUsage.reduce((sum, usage) => sum + (usage?.outputTokens ?? 0), 0) + : undefined, + nativeChildTurns: children.length, + childUsageStatus: childStatus, + childInputTokens: sumOf(measuredChildren, "inputTokens", false), + childOutputTokens: sumOf(measuredChildren, "outputTokens", false), + childrenRunning: report.childrenRunning ? true : undefined, + ...modelObservation( + [...rootUsage, ...childUsage].map((usage) => usage?.models), + label, + ), + durationMs: + startedAt.length === 0 + ? undefined + : Math.max(0, DateTime.toEpochMillis(report.completedAt) - Math.min(...startedAt)), + }); + } +} + +function evictOldest(collection: Map | Set) { + if (collection.size <= MAX_TRACKED_RUNS) return; + const oldest = collection.keys().next().value; + if (oldest !== undefined) collection.delete(oldest); +} + +export class ProviderTurnAnalytics extends Context.Reference<{ + readonly runStarted: (input: { + readonly runId: RunId; + readonly driver: string; + readonly context: ProviderTurnAnalyticsContext; + }) => Effect.Effect; + readonly turnCompleted: (report: ProviderTurnReport) => Effect.Effect; + readonly runSettled: (report: RunSettledReport) => Effect.Effect; +}>("t3/telemetry/ProviderTurnAnalytics", { + defaultValue: () => ({ + runStarted: () => Effect.void, + turnCompleted: () => Effect.void, + runSettled: () => Effect.void, + }), +}) {} + +export const layer = Layer.effect( + ProviderTurnAnalytics, + Effect.gen(function* () { + const analytics = yield* AnalyticsService.AnalyticsService; + const registry = yield* ProviderRegistry.ProviderRegistry; + const ledger = new RequestUsageLedger(); + const labeler = Effect.map( + registry.getProviders, + (providers): ModelLabeler => + (model) => + catalogModelLabel(providers, model), + ); + return { + runStarted: Effect.fn("ProviderTurnAnalytics.runStarted")((input) => + Effect.sync(() => ledger.start(input.runId, input.driver, input.context)), + ), + turnCompleted: Effect.fn("ProviderTurnAnalytics.turnCompleted")(function* (report) { + ledger.add(report); + yield* analytics.record( + "provider.turn.completed", + providerTurnProperties(report, yield* labeler), + ); + }), + runSettled: Effect.fn("ProviderTurnAnalytics.runSettled")(function* (report) { + const properties = ledger.settle(report, yield* labeler); + if (properties !== undefined) { + yield* analytics.record("provider.request.completed", properties); + } + }), + }; + }), +); diff --git a/docs/internals/product-analytics.md b/docs/internals/product-analytics.md index 3369d5832c493..2c6055d811a74 100644 --- a/docs/internals/product-analytics.md +++ b/docs/internals/product-analytics.md @@ -53,22 +53,61 @@ A command whose id was already accepted is a retry, so it records nothing again. One identity can appear in several client groups during a period; adding those groups double-counts users. -Provider send and completion counts need not match. Most completions start -without a person: provider continuations, agent sends, and delegated subagents. -`provider.turn.completed` carries the starting message's `createdBy` and -`creationSource`, plus `scheduled` and `subagent`; filter on them to count user -turns. Collection is best effort, with no scan or backfill of provider history. - -Token totals cover the main agent. Child agents and model rerouting prevent a turn -from representing one provider/model combination's full cost. For provider -comparisons, require complete usage, no observed subagents, and no mixed models; -compare matching model, effort, interaction mode, and terminal status. Aggregate -output/input ratios should divide the summed totals. Averaging per-turn ratios -lets small-input turns dominate. - -Unknown counts stay absent. Partial usage contains valid observed counts but -cannot establish a whole-turn total. Keep these distinctions when changing token -normalization or building reports. +Provider send and completion counts need not match. `provider.turn.completed` +is one provider turn, and `segment` says what started it: the run's first +attempt (`initial`), a `steering_restart`, a provider `continuation` such as a +Codex goal turn, or a `native_child` subagent. `createdBy`, `creationSource`, +`scheduled`, and `subagent` describe the run's starting message, and `childKind` +separates native subagents from T3-managed child threads. Use this event for +per-turn measurements, not for counting requests. + +`provider.request.completed` is one run, recorded when the run settles in the +server process that ran it. It adds each root turn once, so continuations, +steering, and replayed provider events do not add rows. `requestKind: "user"` +counts what people asked for. Native subagent turns are summed apart from the +root (`childUsageStatus`, `childInputTokens`); T3-managed child threads report +their own requests as `t3_child`. A child still running at settlement is never +added later, and the summary sets `childrenRunning`. A server restart loses the +summary of a run in progress. A run that continues after a restart reports its +own usage with `restartContinuation` and `lifecycleObserved: false`; it cannot +recover the original request's count or kind. A run whose provider session never +opens has no summary, and a start the provider rejects reports +`providerTurns: 0`. A Stop that lands while a steering restart is starting ends +the run without a summary. Collection is best effort, with no scan or backfill of +provider history. + +Counts cover the main agent. `otherInputTokens` and `otherOutputTokens` are what +a provider's own ledger recorded beyond it during the turn: Claude's per-process +`modelUsage` growth, which covers native subagents, compaction, and helper +calls. They need a baseline from the same process, so they stay absent when it +is unknown or the ledger goes backwards, and background work that ends between +turns lands in the next one. Claude subagents have no turns of their own, so +this never overlaps child turns. + +`model` and `effort` are what the run selected. `observedModel` and +`mixedModels` appear only when the provider reported the models for the counted +work (Codex thread settings and reroutes, Claude root messages, OpenCode steps). +`mixedModels: false` without `reportVersion` was never checked. Model labels +come from the bundled model manifest and the Cursor and Grok catalogs, also for +routed ids such as `anthropic/claude-opus-5-5`, and efforts come from a closed +list, so user-configured names stay out. + +Status and counters answer different questions. `usageReported: false` means +the adapter attached no usage; a harness where every row says so is unsupported, +not idle. `partial` keeps valid counts that cannot establish a whole-turn total, +such as an OpenCode step that ended without a report, an OpenCode stream +reconnect, or an interrupted segment. +Explicit zeros are sent and unknown counts stay absent. `localCommand` marks a +provider-local command such as Claude's `/compact`, whose result counters are not +model work. Reasoning tokens are a subset of output. + +Charts built on these events should say "output tokens per measured provider +completion", compare matching provider, observed model, effort, interaction mode, +and terminal status, and show eligible and measured counts by harness, origin, +and status so unknown models and unsupported adapters stay in the denominator. +Divide summed totals for output/input ratios; averaging per-turn ratios lets +small-input turns dominate. Rows without `reportVersion` keep their missing +fields unknown; a missing origin is never a person. `feature.used` counts WebSocket requests that start a feature. RPCs are observed in the RPC authorization middleware after the request succeeds; dispatched commands diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md index 9e70561332e17..3b7e8f9d5a27e 100644 --- a/docs/user/telemetry.md +++ b/docs/user/telemetry.md @@ -5,11 +5,12 @@ associated with a hashed account or installation identifier. To count how many i uses, the server also sends hashed account identifiers: your T3 Connect account, your OpenAI and Claude accounts when you are signed in, and a random identifier for each device that connects. The endpoint keeps a copy of each event and forwards events to PostHog. Events include the provider, model, reasoning effort, -permission mode, turn result, duration, release channel, and main-agent token totals when -available. +permission mode, turn and request results, duration, release channel, and token counts when +available. Child-agent token counts are reported separately from the main agent's. Model names +are sent only when they appear in a provider's public model list. Events do not include prompts, responses, file contents, authentication tokens, conversation IDs, -raw provider events, or child-agent output. Child-agent token use is excluded from the totals. +raw provider events, or child-agent output. T3 Code also sends relay connection traces to Axiom to diagnose T3 Connect connectivity. diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index 4740a9fd0ccf7..4769bfd7955c7 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -60,6 +60,14 @@ const TurnTokenUsageCommonFields = { cacheCreationTokens: Schema.optional(NonNegativeInt), reasoningTokens: Schema.optional(NonNegativeInt), hasSubagents: Schema.Boolean, + // Native model ids the provider reported for the main agent's work. Absent means unknown. + models: Schema.optional(Schema.Array(TrimmedNonEmptyStringSchema)), + // The provider ran a local command; its counters describe that result, not model work. + localCommand: Schema.optional(Schema.Boolean), + // Provider-ledger counts beyond the main agent, such as native subagents and compaction. + otherUsage: Schema.optional( + Schema.Struct({ inputTokens: NonNegativeInt, outputTokens: NonNegativeInt }), + ), }; export const TurnTokenUsage = Schema.Union([ Schema.Struct({ diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 74695bf6061aa..f49de61b24690 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -209,7 +209,12 @@ interface ActiveTurn { output: number; reasoning: number; }; + // Steps OpenCode started; a step that ends without tokens leaves the total partial. + startedSteps: number; + // A reconnect dropped events, so steps may have ended unseen. + missedEvents: boolean; steps: number; + readonly models: Set; lastStep: Tokens | undefined; before: string | null | undefined; compaction: { readonly nativeId: string; readonly startedAt: DateTime.Utc } | undefined; @@ -629,16 +634,26 @@ const skillsNamed = (text: string, known: ReadonlySet) => [ ), ]; -const turnTokenUsage = (turn: ActiveTurn, status: OrchestrationV2ProviderTurn["status"]) => - turn.steps === 0 +const turnTokenUsage = (turn: ActiveTurn, status: OrchestrationV2ProviderTurn["status"]) => { + // A step whose start was missed, in a reconnect gap or as an unreadable event, ran on an unreported model. + const models = + turn.models.size === 0 || turn.missedEvents || turn.steps > turn.startedSteps + ? {} + : { models: [...turn.models] }; + return turn.steps === 0 ? { usageScope: "main_agent" as const, usageStatus: "unavailable" as const, hasSubagents: turn.usedSubagents, + ...models, } : { + ...models, usageScope: "main_agent" as const, - usageStatus: status === "completed" ? ("complete" as const) : ("partial" as const), + usageStatus: + status === "completed" && !turn.missedEvents && turn.steps >= turn.startedSteps + ? ("complete" as const) + : ("partial" as const), inputTokens: turn.usage.input, cachedInputTokens: turn.usage.cached, cacheCreationTokens: turn.usage.cacheWrite, @@ -646,6 +661,7 @@ const turnTokenUsage = (turn: ActiveTurn, status: OrchestrationV2ProviderTurn["s reasoningTokens: turn.usage.reasoning, hasSubagents: turn.usedSubagents, }; +}; export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: ProviderInstanceId) { const server = yield* OpenCode2Server.OpenCode2Server; @@ -1111,7 +1127,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ordinals: new Map(), nextOrdinal: providerTurn.ordinal * 100 + 1, usage: { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }, + startedSteps: 0, + missedEvents: false, steps: 0, + models: new Set(), lastStep: undefined, before: undefined, compaction: undefined, @@ -2101,6 +2120,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr return yield* emitCompaction(state, turn, "completed", event.data.text); case "session.compaction.failed": return yield* emitCompaction(state, turn, "failed"); + case "session.step.started": + turn.startedSteps += 1; + turn.models.add(`${event.data.model.providerID}/${event.data.model.id}`); + return; case "session.step.ended": case "session.step.failed": { const tokens = event.data.tokens; @@ -2568,6 +2591,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr for (const [sessionId, state] of running) { const turn = state.active; if (turn === undefined) continue; + turn.missedEvents = true; const ended = yield* backfill(sessionId, state); if (sessionId in active || state.active !== turn) continue; yield* finishTurn( From ddfc4a92edbdc934fede54c32f19be9ff5af1bb4 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 1 Nov 2026 19:01:53 -0800 Subject: [PATCH 006/163] update the claude entrypoint identifier for accuracy (#28410) --- .../Adapters/ClaudeAdapterV2.ts | 8 ++++-- apps/server/src/provider/ClaudeProvider.ts | 4 +-- .../src/provider/Drivers/ClaudeDriver.ts | 4 +-- .../src/provider/Drivers/ClaudeHome.test.ts | 28 +++++++++++++++++++ .../server/src/provider/Drivers/ClaudeHome.ts | 25 ++++++++++++++++- .../src/provider/Drivers/ClaudeSkills.ts | 27 +++++++++--------- 6 files changed, 75 insertions(+), 21 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 5b4a4ad84d435..bc90fcb2189b4 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -162,6 +162,7 @@ import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; import { claudeSignedOutMessage, makeClaudeEnvironment, + mergeClaudeProcessEnvironment, resolveClaudeHomePath, } from "../../provider/Drivers/ClaudeHome.ts"; import { @@ -182,7 +183,6 @@ import { type ClaudeScopedLimitNames, } from "../../provider/claudeUsageLimits.ts"; import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot"; -import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH, T3_CODE_ORCHESTRATION_INSTRUCTIONS, @@ -11661,7 +11661,11 @@ export const createClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2Driver.create")( const queryRunner = yield* ClaudeAgentSdkQueryRunner; const serverConfig = yield* ServerConfig.ServerConfig; const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests; - const baseEnvironment = yield* mergeProviderInstanceEnvironment(environment, hostEnvironment); + const baseEnvironment = yield* mergeClaudeProcessEnvironment( + config, + environment, + hostEnvironment, + ); const claudeEnvironment = yield* makeClaudeEnvironment(config, baseEnvironment); const path = yield* Path.Path; const crypto = yield* Crypto.Crypto; diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index 95f5c6709a4ea..a596f6131035c 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -37,7 +37,7 @@ import { } from "@t3tools/provider-core/server/snapshotProbe"; import { resolveClaudeSdkExecutablePath } from "./Drivers/ClaudeExecutable.ts"; import { hasClaudeManagedMcpConfig, makeClaudeEnvironment } from "./Drivers/ClaudeHome.ts"; -import { discoverClaudeSkills, readClaudeSettingsBaseUrl } from "./Drivers/ClaudeSkills.ts"; +import { discoverClaudeSkills, readClaudeSettingsEnv } from "./Drivers/ClaudeSkills.ts"; import type { ProviderWorkspaceSnapshot } from "@t3tools/provider-core/server/driver"; import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits"; import { @@ -601,7 +601,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( // First-party account fields cannot verify custom endpoint credentials. const baseUrl = - (yield* readClaudeSettingsBaseUrl(claudeSettings, cwd, resolvedEnvironment)) ?? + (yield* readClaudeSettingsEnv(claudeSettings, cwd, resolvedEnvironment)).ANTHROPIC_BASE_URL ?? resolvedEnvironment.ANTHROPIC_BASE_URL; const endpoint = URL.parse(baseUrl?.trim() ?? ""); const customApiEndpoint = diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index e1fbcd30080fd..d4a16a2220465 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -42,7 +42,6 @@ import { type ProviderInstance, } from "@t3tools/provider-core/server/driver"; import { withInstanceIdentity } from "@t3tools/provider-core/server/instanceIdentity"; -import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { enrichProviderSnapshotWithVersionAdvisory, makeCachedProviderMaintenanceResolution, @@ -58,6 +57,7 @@ import { import { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey, + mergeClaudeProcessEnvironment, resolveClaudeHomePath, } from "./ClaudeHome.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -134,7 +134,7 @@ export const ClaudeDriver: ProviderDriver { }), ); }); + + it.effect("labels Claude processes t3-code unless instance env or Claude settings set one", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const homePath = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-home-" }); + const host = { CLAUDE_CODE_ENTRYPOINT: "claude-desktop", KEEP: "1" }; + const instance = [{ name: "CLAUDE_CODE_ENTRYPOINT", value: "instance", sensitive: false }]; + + expect(yield* mergeClaudeProcessEnvironment({ homePath }, undefined, host)).toMatchObject({ + CLAUDE_CODE_ENTRYPOINT: "t3-code", + KEEP: "1", + }); + expect( + (yield* mergeClaudeProcessEnvironment({ homePath }, instance, host)).CLAUDE_CODE_ENTRYPOINT, + ).toBe("instance"); + + yield* fileSystem.writeFileString( + path.join(homePath, "settings.json"), + JSON.stringify({ env: { CLAUDE_CODE_ENTRYPOINT: "custom" } }), + ); + expect( + (yield* mergeClaudeProcessEnvironment({ homePath }, instance, host)).CLAUDE_CODE_ENTRYPOINT, + ).toBe("custom"); + }), + ); }); diff --git a/apps/server/src/provider/Drivers/ClaudeHome.ts b/apps/server/src/provider/Drivers/ClaudeHome.ts index bd81aa10bce7a..29b530ff444e4 100644 --- a/apps/server/src/provider/Drivers/ClaudeHome.ts +++ b/apps/server/src/provider/Drivers/ClaudeHome.ts @@ -1,12 +1,15 @@ -import type { ClaudeSettings } from "@t3tools/contracts"; +import type { ClaudeSettings, ProviderInstanceEnvironment } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { readClaudeSettingsEnv } from "./ClaudeSkills.ts"; + const quotePath = Schema.encodeSync(Schema.fromJsonString(Schema.String)); export const resolveClaudeHomePath = Effect.fn("resolveClaudeHomePath")(function* ( @@ -42,6 +45,26 @@ export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function }; }); +/** + * Base env for the Claude processes T3 Code runs, before `makeClaudeEnvironment`. + * Claude Code reads its entrypoint from the process env, not its settings `env`, so T3 Code applies that override itself. + */ +export const mergeClaudeProcessEnvironment = Effect.fn("mergeClaudeProcessEnvironment")(function* ( + config: Pick, + instanceEnvironment: ProviderInstanceEnvironment | undefined, + hostEnvironment: NodeJS.ProcessEnv, +) { + const environment = yield* mergeProviderInstanceEnvironment(instanceEnvironment, { + ...hostEnvironment, + CLAUDE_CODE_ENTRYPOINT: "t3-code", + }); + const settingsEntrypoint = (yield* readClaudeSettingsEnv(config, undefined, environment)) + .CLAUDE_CODE_ENTRYPOINT; + return settingsEntrypoint + ? { ...environment, CLAUDE_CODE_ENTRYPOINT: settingsEntrypoint } + : environment; +}); + /** managed-mcp.json excludes other MCP config and forbids --strict-mcp-config; omit the flag when present. */ export const hasClaudeManagedMcpConfig = Effect.fn("hasClaudeManagedMcpConfig")(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.ts b/apps/server/src/provider/Drivers/ClaudeSkills.ts index 6aff76d250a76..c73385374fbc0 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.ts @@ -428,24 +428,25 @@ const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(funct return path.join(home, ".claude"); }); -const SettingsBaseUrl = fromLenientJson( - Schema.Struct({ - env: Schema.optional(Schema.Struct({ ANTHROPIC_BASE_URL: Schema.optional(Schema.String) })), - }), +const SettingsEnv = Schema.Struct({ + ANTHROPIC_BASE_URL: Schema.optional(Schema.String), + CLAUDE_CODE_ENTRYPOINT: Schema.optional(Schema.String), +}); +const decodeSettingsEnv = Schema.decodeUnknownEffect( + fromLenientJson(Schema.Struct({ env: Schema.optional(SettingsEnv) })), ); -const decodeSettingsBaseUrl = Schema.decodeUnknownEffect(SettingsBaseUrl); -/** ANTHROPIC_BASE_URL from Claude's settings `env`, which Claude Code applies over the process env. */ -export const readClaudeSettingsBaseUrl = Effect.fn("readClaudeSettingsBaseUrl")(function* ( +/** The `env` values T3 Code reads from Claude's user and managed settings; later files win. */ +export const readClaudeSettingsEnv = Effect.fn("readClaudeSettingsEnv")(function* ( config: Pick, cwd: string | undefined, environment: NodeJS.ProcessEnv, -): Effect.fn.Return { +): Effect.fn.Return { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const platform = yield* HostProcess.Platform; const configDirPath = yield* resolveClaudeConfigDirPath(config, environment, cwd); - let baseUrl: string | undefined; + const settingsEnv: typeof SettingsEnv.Type = {}; for (const settingsPath of claudeSettingsPaths( path, configDirPath, @@ -457,12 +458,10 @@ export const readClaudeSettingsBaseUrl = Effect.fn("readClaudeSettingsBaseUrl")( .readFileString(settingsPath) .pipe(Effect.orElseSucceed(() => undefined)); if (contents === undefined) continue; - const parsed = yield* decodeSettingsBaseUrl(contents).pipe( - Effect.orElseSucceed(() => undefined), - ); - baseUrl = parsed?.env?.ANTHROPIC_BASE_URL ?? baseUrl; + const parsed = yield* decodeSettingsEnv(contents).pipe(Effect.orElseSucceed(() => undefined)); + Object.assign(settingsEnv, parsed?.env); } - return baseUrl; + return settingsEnv; }); // Claude's --add-dir is repeatable and variadic; parseCliArgs keeps only one value. From 4a5251b1c4b867ad2d89bf59d7a062ca8c40f2a6 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 1 Nov 2026 21:22:13 -0600 Subject: [PATCH 007/163] fix(web): keep pending pull request actions scoped to each request (#29005) --- .../usePullRequestActions.browser.test.tsx | 74 +++++++++++++++++++ .../pullRequest/usePullRequestActions.ts | 24 ++++-- 2 files changed, 91 insertions(+), 7 deletions(-) create mode 100644 apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx new file mode 100644 index 0000000000000..48e1f7412702a --- /dev/null +++ b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx @@ -0,0 +1,74 @@ +import { EnvironmentId, ProjectId, type PullRequestRef } from "@t3tools/contracts"; +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; +import { expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import { act, render } from "../../../test/render"; +import { usePullRequestActionRunner } from "./usePullRequestActions"; + +const state = vi.hoisted(() => ({ runAction: vi.fn() })); +vi.mock(import("~/state/use-atom-command"), () => ({ + useAtomCommand: (() => state.runAction) as never, +})); + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +function MergeButton({ reference }: { reference: PullRequestRef }) { + const { actionPending, perform } = usePullRequestActionRunner({ + environmentId: EnvironmentId.make("environment"), + reference, + terminology: sourceControlClients.get(undefined).changeRequest, + }); + return ( + + ); +} + +it("keeps pending merges with their pull request when navigating between threads", async () => { + const first: PullRequestRef = { + projectId: ProjectId.make("project"), + repository: "owner/repo", + number: 1, + }; + const second = { ...first, number: 2 }; + const firstResult = deferred<{ _tag: "Success"; value: void }>(); + const secondResult = deferred<{ _tag: "Success"; value: void }>(); + state.runAction + .mockReset() + .mockReturnValueOnce(firstResult.promise) + .mockReturnValueOnce(secondResult.promise); + await using screen = await render(); + const button = screen.getByRole("button"); + + await userEvent.click(button); + await expect.element(button).toHaveTextContent("Merging..."); + await screen.rerender(); + await expect.element(button).toHaveTextContent("Merge"); + await expect.element(button).toBeEnabled(); + await userEvent.click(button); + expect(state.runAction).toHaveBeenCalledTimes(2); + + await screen.rerender(); + await expect.element(button).toHaveTextContent("Merging..."); + await expect.element(button).toBeDisabled(); + await act(async () => { + firstResult.resolve({ _tag: "Success", value: undefined }); + await firstResult.promise; + }); + await expect.element(button).toHaveTextContent("Merge"); + await screen.rerender(); + await expect.element(button).toHaveTextContent("Merging..."); + await act(async () => { + secondResult.resolve({ _tag: "Success", value: undefined }); + await secondResult.promise; + }); + await expect.element(button).toHaveTextContent("Merge"); +}); diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index d2d2e39ac2e34..82ce86ab8f429 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -140,13 +140,23 @@ export function usePullRequestActionRunner({ const runAction = useAtomCommand(pullRequestEnvironment.runAction, { reportFailure: false, }); - const [actionPending, setActionPending] = useState(false); - const pendingRef = useRef(false); + const pendingRef = useRef(new Set()); + const [pendingKeys, setPendingKeys] = useState>(() => new Set()); + const actionKey = + reference === null + ? null + : JSON.stringify([ + environmentId, + reference.host ?? null, + reference.repository, + reference.number, + ]); + const actionPending = actionKey !== null && pendingKeys.has(actionKey); const perform = async (action: PullRequestAction, method?: PullRequestMergeMethod) => { - if (pendingRef.current || reference === null) return; - pendingRef.current = true; - setActionPending(true); + if (actionKey === null || reference === null || pendingRef.current.has(actionKey)) return; + pendingRef.current.add(actionKey); + setPendingKeys(new Set(pendingRef.current)); const result = await runAction({ environmentId, input: { @@ -155,8 +165,8 @@ export function usePullRequestActionRunner({ ...(method ? { mergeMethod: method } : resolveMergeMethod ? { resolveMergeMethod } : {}), }, }); - pendingRef.current = false; - setActionPending(false); + pendingRef.current.delete(actionKey); + setPendingKeys(new Set(pendingRef.current)); if (result._tag === "Failure") { toastManager.add({ type: "error", From 7a760a9a88662274f29b20ae812b3ae05fca9078 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 1 Nov 2026 21:37:38 -0600 Subject: [PATCH 008/163] fix(desktop): load the renderer while the backend starts (#28715) --- apps/desktop/src/app/DesktopApp.ts | 10 ++ .../src/app/DesktopStartupRecovery.test.ts | 133 +++++++++++++++++- .../desktop/src/app/DesktopStartupRecovery.ts | 28 +++- apps/desktop/src/app/DesktopWebLinks.test.ts | 6 + apps/desktop/src/app/DesktopWebLinks.ts | 4 +- .../src/backend/DesktopBackendManager.test.ts | 43 ++++++ .../src/backend/DesktopBackendManager.ts | 76 +++++----- .../DesktopLocalEnvironmentAuth.test.ts | 21 ++- .../backend/DesktopLocalEnvironmentAuth.ts | 5 +- apps/desktop/src/window/DesktopWindow.test.ts | 77 ++++++++++ apps/desktop/src/window/DesktopWindow.ts | 59 +++++--- .../environments/primary/httpLayer.test.ts | 24 +++- 12 files changed, 419 insertions(+), 67 deletions(-) diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index d49d2cdebb701..3442a54d60c4a 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -245,6 +245,16 @@ const bootstrap = Effect.gen(function* () { } yield* primaryBackend.start; yield* logBootstrapInfo("bootstrap backend start requested"); + // WSL-only fallback can change the primary endpoint before readiness. + const config = yield* primaryBackend.currentConfig; + if ( + !environment.isDevelopment && + !settings.wslOnly && + Option.isSome(config) && + Option.isNone(config.value.preflightFailure) + ) { + yield* desktopWindow.ensureMain; + } yield* appActivation.start.pipe( Effect.tap(() => logBootstrapInfo("desktop app control socket ready")), Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })), diff --git a/apps/desktop/src/app/DesktopStartupRecovery.test.ts b/apps/desktop/src/app/DesktopStartupRecovery.test.ts index d8a0ef1a999cc..12d5289af67c7 100644 --- a/apps/desktop/src/app/DesktopStartupRecovery.test.ts +++ b/apps/desktop/src/app/DesktopStartupRecovery.test.ts @@ -1,8 +1,23 @@ import type { DesktopUpdateState } from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; +import * as DesktopEnvironment from "./DesktopEnvironment.ts"; +import * as DesktopState from "./DesktopState.ts"; +import * as ElectronApp from "../electron/ElectronApp.ts"; +import * as ElectronShell from "../electron/ElectronShell.ts"; +import * as ElectronTheme from "../electron/ElectronTheme.ts"; +import * as ElectronWindow from "../electron/ElectronWindow.ts"; +import * as DesktopUpdates from "../updates/DesktopUpdates.ts"; import { createInitialDesktopUpdateState } from "../updates/updateMachine.ts"; -import { resolveStartupRecoveryOffer } from "./DesktopStartupRecovery.ts"; +import { listen, resolveStartupRecoveryOffer } from "./DesktopStartupRecovery.ts"; const updateState = (patch: Partial): DesktopUpdateState => ({ ...createInitialDesktopUpdateState( @@ -68,3 +83,117 @@ describe("resolveStartupRecoveryOffer", () => { }); }); }); + +it.effect.each([ + { visible: false, started: false, closeMain: false }, + { visible: true, started: false, closeMain: false }, + { visible: true, started: true, closeMain: false }, + { visible: true, started: false, closeMain: true }, +])("closes recovery safely with closeMain=$closeMain", ({ visible, started, closeMain }) => + Effect.scoped( + Effect.gen(function* () { + const checked = yield* Deferred.make(); + const remembered = yield* Deferred.make(); + const shouldRecover = !visible || !started; + const closed = Promise.withResolvers(); + const loaded: string[] = []; + const appListeners = new Map void>(); + const mainListeners = new Map void>(); + let closeCount = 0; + let mainVisible = visible; + const main = { + isDestroyed: () => false, + isVisible: () => mainVisible, + on: (event: string, listener: () => void) => mainListeners.set(event, listener), + once: (event: string, listener: () => void) => mainListeners.set(event, listener), + } as unknown as Electron.BrowserWindow; + const mainRef = yield* Ref.make(Option.some(main)); + const recovery = { + isDestroyed: () => false, + close: () => { + closeCount++; + closed.resolve(); + }, + loadURL: (url: string) => { + loaded.push(url); + return Promise.resolve(); + }, + once: () => {}, + webContents: { setWindowOpenHandler: () => {}, on: () => {} }, + } as unknown as Electron.BrowserWindow; + const state = yield* DesktopState.DesktopState; + if (started) yield* SubscriptionRef.set(state.primaryBackendStartup, { _tag: "Ready" }); + yield* listen.pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + readFileString: () => Effect.succeed("0.1.2"), + writeFileString: () => Deferred.succeed(remembered, undefined).pipe(Effect.asVoid), + }), + Layer.succeed(DesktopEnvironment.DesktopEnvironment, { + appVersion: "0.1.3", + stateDir: "/task/state", + logDir: "/task/logs", + path: { join: (...parts: string[]) => parts.join("/") }, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + Layer.succeed(ElectronApp.ElectronApp, { + on: (event: string, listener: (...args: readonly unknown[]) => void) => + Effect.sync(() => { + appListeners.set(event, listener); + }), + } as unknown as ElectronApp.ElectronApp["Service"]), + Layer.succeed( + ElectronShell.ElectronShell, + {} as ElectronShell.ElectronShell["Service"], + ), + Layer.succeed(ElectronTheme.ElectronTheme, { + shouldUseDarkColors: Effect.succeed(false), + } as ElectronTheme.ElectronTheme["Service"]), + Layer.succeed(ElectronWindow.ElectronWindow, { + main: Ref.get(mainRef), + create: () => Effect.succeed(recovery), + } as unknown as ElectronWindow.ElectronWindow["Service"]), + Layer.succeed(DesktopUpdates.DesktopUpdates, { + subscribe: Effect.succeed({ + latest: updateState({ status: "disabled" }), + changes: Stream.empty, + }), + check: () => Deferred.succeed(checked, undefined), + } as unknown as DesktopUpdates.DesktopUpdates["Service"]), + ), + ), + ); + appListeners.get("browser-window-created")?.({}, main); + if (started) yield* Deferred.await(remembered); + yield* SubscriptionRef.set(state.primaryBackendStartup, { + _tag: "Failing", + reason: "Server failed before readiness", + output: "Failure details", + }); + yield* Deferred.await(checked); + expect(loaded.length).toBe(shouldRecover ? 1 : 0); + if (shouldRecover) { + expect(decodeURIComponent(loaded[0]!)).toContain("Failure details"); + if (closeMain) yield* Ref.set(mainRef, Option.none()); + yield* SubscriptionRef.set(state.primaryBackendStartup, { _tag: "Ready" }); + yield* Deferred.await(remembered); + if (closeMain || !visible) { + expect(closeCount).toBe(0); + if (closeMain) { + yield* Ref.set(mainRef, Option.some(main)); + mainVisible = false; + appListeners.get("browser-window-created")?.({}, main); + } + mainListeners.get("ready-to-show")?.(); + expect(closeCount).toBe(0); + mainVisible = true; + const show = mainListeners.get("show"); + expect(show).toBeDefined(); + show!(); + } + yield* Effect.promise(() => closed.promise); + expect(closeCount).toBe(1); + } + }), + ).pipe(Effect.provide(DesktopState.layer)), +); diff --git a/apps/desktop/src/app/DesktopStartupRecovery.ts b/apps/desktop/src/app/DesktopStartupRecovery.ts index 4d2dbcfb14409..ae94fd5b4c135 100644 --- a/apps/desktop/src/app/DesktopStartupRecovery.ts +++ b/apps/desktop/src/app/DesktopStartupRecovery.ts @@ -167,6 +167,7 @@ export const listen: Effect.Effect< const failureRef = yield* Ref.make(Option.none()); const renderedHtmlRef = yield* Ref.make(""); const checkedRef = yield* Ref.make(false); + let backendHasStarted = false; const { latest, changes: updateChanges } = yield* updates.subscribe; const updateStateRef = yield* Ref.make(latest); @@ -230,8 +231,15 @@ export const listen: Effect.Effect< const show = Effect.fn("desktop.startupRecovery.show")( function* () { if (yield* Ref.get(quitting)) return; - // A backend that crashes after the app opened is reported by the app itself. - if (Option.isSome(yield* electronWindow.main)) return; + // A visible boot shell still needs recovery if the backend has never started. + const main = yield* electronWindow.main; + if ( + backendHasStarted && + Option.isSome(main) && + !main.value.isDestroyed() && + main.value.isVisible() + ) + return; const existing = yield* Ref.get(windowRef); if (Option.isSome(existing) && !existing.value.isDestroyed()) { yield* electronWindow.reveal(existing.value); @@ -285,6 +293,19 @@ export const listen: Effect.Effect< if (Option.isSome(window) && !window.value.isDestroyed()) window.value.close(); }); + const closeWhenMainReady = Effect.gen(function* () { + if ((yield* SubscriptionRef.get(primaryBackendStartup))._tag !== "Ready") return; + const main = yield* electronWindow.main; + if (Option.isSome(main) && !main.value.isDestroyed() && main.value.isVisible()) yield* close; + }); + + yield* electronApp.on( + "browser-window-created", + (_event: Electron.Event, window: Electron.BrowserWindow) => { + window.on("show", () => runFork(closeWhenMainReady)); + }, + ); + const rememberStartedVersion = Effect.gen(function* () { if (lastStartedVersion === environment.appVersion) return; yield* fileSystem.writeFileString(lastStartedVersionPath, environment.appVersion); @@ -303,8 +324,9 @@ export const listen: Effect.Effect< Stream.runForEach( Effect.fn("desktop.startupRecovery.onStartupChange")(function* (startup) { if (startup._tag === "Ready") { + backendHasStarted = true; yield* Ref.set(failureRef, Option.none()); - yield* close; + yield* closeWhenMainReady; yield* rememberStartedVersion; return; } diff --git a/apps/desktop/src/app/DesktopWebLinks.test.ts b/apps/desktop/src/app/DesktopWebLinks.test.ts index 9b5bc89148dea..e4259f66fb5e0 100644 --- a/apps/desktop/src/app/DesktopWebLinks.test.ts +++ b/apps/desktop/src/app/DesktopWebLinks.test.ts @@ -4,6 +4,7 @@ import * as NodeEvents from "node:events"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; import { WEB_LINK_OPEN_CHANNEL } from "../ipc/channels.ts"; import * as DesktopWebLinks from "./DesktopWebLinks.ts"; @@ -21,6 +22,11 @@ const makeWindow = () => { const reload = () => webContents.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false }); const layer = DesktopWebLinks.layer.pipe( + Layer.provide( + Layer.succeed(DesktopWindow.DesktopWindow, { + activate: Effect.sync(() => void revealed.push(window)), + } as unknown as DesktopWindow.DesktopWindow["Service"]), + ), Layer.provide( Layer.succeed( ElectronWindow.ElectronWindow, diff --git a/apps/desktop/src/app/DesktopWebLinks.ts b/apps/desktop/src/app/DesktopWebLinks.ts index ce63a710f7f7e..c1932c5ce9055 100644 --- a/apps/desktop/src/app/DesktopWebLinks.ts +++ b/apps/desktop/src/app/DesktopWebLinks.ts @@ -3,6 +3,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; import { WEB_LINK_OPEN_CHANNEL } from "../ipc/channels.ts"; @@ -24,6 +25,7 @@ export class DesktopWebLinks extends Context.Service< const make = Effect.gen(function* () { const electronWindow = yield* ElectronWindow.ElectronWindow; + const desktopWindow = yield* DesktopWindow.DesktopWindow; const pending: Array = []; let listening: Electron.WebContents | null = null; let detachListening: (() => void) | null = null; @@ -43,7 +45,7 @@ const make = Effect.gen(function* () { return; } for (const url of pending.splice(0)) listening.send(WEB_LINK_OPEN_CHANNEL, url); - yield* electronWindow.reveal(window.value); + yield* desktopWindow.activate.pipe(Effect.ignore); }); const startListening = Effect.gen(function* () { diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index 220143d6cf45c..a5c12043d9aaa 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -192,6 +192,49 @@ function makeTestInstance(input: MakeInstanceInput) { } describe("DesktopBackendManager", () => { + it.effect("notifies readiness waiters on HTTP readiness and stop without clock advancement", () => + Effect.scoped( + Effect.gen(function* () { + const probe = yield* Deferred.make(); + const ready = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.acquireRelease( + Effect.succeed( + makeProcess({ + exitCode: Deferred.await(exit), + kill: () => + Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid), + }), + ), + () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)), + ), + ), + ), + httpClientLayer: Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Deferred.succeed(probe, undefined).pipe( + Effect.andThen(Deferred.await(ready)), + Effect.as(HttpClientResponse.fromWeb(request, new Response("{}"))), + ), + ), + ), + }); + yield* instance.start; + yield* Deferred.await(probe); + const waiter = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild); + yield* Deferred.succeed(ready, undefined); + assert.isTrue(yield* Fiber.join(waiter)); + yield* instance.stop(); + assert.isFalse(yield* instance.waitForReady(Duration.seconds(15))); + }), + ), + ); + it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index 1930be355513f..aa3b4d59ef1bf 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -8,7 +8,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; -import * as Schedule from "effect/Schedule"; +import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Scope from "effect/Scope"; @@ -629,7 +629,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const httpClient = yield* HttpClient.HttpClient; - const state = yield* Ref.make(initialState); + const state = yield* SubscriptionRef.make(initialState); const mutex = yield* Semaphore.make(1); const outputTail = yield* Ref.make(""); // One streaming decoder per stream keeps UTF-8 characters split across chunks intact. @@ -644,9 +644,9 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`); const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) => - Ref.update(state, withActiveRun(runId, f)); + SubscriptionRef.update(state, withActiveRun(runId, f)); - const snapshot = Ref.get(state).pipe( + const snapshot = SubscriptionRef.get(state).pipe( Effect.map((current): DesktopBackendSnapshot => ({ desiredRunning: current.desiredRunning, ready: current.ready, @@ -655,10 +655,10 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( restartScheduled: Option.isSome(current.restartFiber), })), ); - const currentConfig = Ref.get(state).pipe(Effect.map((current) => current.config)); + const currentConfig = SubscriptionRef.get(state).pipe(Effect.map((current) => current.config)); const cancelRestart = Effect.gen(function* () { - const restartFiber = yield* Ref.modify(state, (current) => [ + const restartFiber = yield* SubscriptionRef.modify(state, (current) => [ current.restartFiber, { ...current, @@ -675,10 +675,10 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( const start: Effect.Effect = Effect.suspend(() => mutex.withPermits(1)( Effect.gen(function* () { - const current = yield* Ref.get(state); + const current = yield* SubscriptionRef.get(state); if (Option.isSome(current.active)) { if (!current.desiredRunning) { - yield* Ref.update(state, (latest) => ({ + yield* SubscriptionRef.update(state, (latest) => ({ ...latest, desiredRunning: true, })); @@ -688,7 +688,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( if (current.ready) { yield* spec.onShutdown?.() ?? Effect.void; - yield* Ref.update(state, (latest) => + yield* SubscriptionRef.update(state, (latest) => latest.ready ? { ...latest, ready: false } : latest, ); } @@ -713,7 +713,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( const resetFatalPreflightCounter = !current.desiredRunning && current.preflightFailureAttempt > 0; yield* cancelRestart; - yield* Ref.update(state, (latest) => ({ + yield* SubscriptionRef.update(state, (latest) => ({ ...latest, desiredRunning: true, ready: false, @@ -725,7 +725,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( if (Option.isSome(preflightFailure)) { const { reason, fatal, retryLimit } = preflightFailure.value; if (!fatal && retryLimit === undefined) { - yield* Ref.update(state, (latest) => + yield* SubscriptionRef.update(state, (latest) => latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 }, @@ -734,7 +734,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( return; } const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS; - const attempt = yield* Ref.modify(state, (latest) => { + const attempt = yield* SubscriptionRef.modify(state, (latest) => { const next = latest.preflightFailureAttempt + 1; return [next, { ...latest, preflightFailureAttempt: next }] as const; }); @@ -743,7 +743,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( reason, attempt, }); - yield* Ref.update(state, (latest) => ({ + yield* SubscriptionRef.update(state, (latest) => ({ ...latest, desiredRunning: false, ready: false, @@ -761,7 +761,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( if (shouldRestart) { yield* scheduleRestart(reason); } else { - yield* Ref.update(state, (latest) => ({ + yield* SubscriptionRef.update(state, (latest) => ({ ...latest, desiredRunning: false, ready: false, @@ -772,7 +772,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( yield* scheduleRestart(reason); return; } - yield* Ref.update(state, (latest) => + yield* SubscriptionRef.update(state, (latest) => latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 }, ); @@ -782,7 +782,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( } const runScope = yield* Scope.make("sequential"); - const runId = yield* Ref.modify(state, (latest) => [ + const runId = yield* SubscriptionRef.modify(state, (latest) => [ latest.nextRunId, { ...latest, @@ -806,7 +806,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( yield* mutex.withPermits(1)( Effect.gen(function* () { const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } = - yield* Ref.modify( + yield* SubscriptionRef.modify( state, ( latest, @@ -873,7 +873,10 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( if (isCurrentRun && nextState.desiredRunning) { if (stateDirOwned && !stopRequested) { - yield* Ref.update(state, (latest) => ({ ...latest, desiredRunning: false })); + yield* SubscriptionRef.update(state, (latest) => ({ + ...latest, + desiredRunning: false, + })); yield* (spec.onStateDirOwned?.() ?? Effect.void).pipe(Effect.ignore); return; } @@ -907,7 +910,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( exitObserved: true, })), onReady: Effect.fn("desktop.backendInstance.onReady")(function* () { - const isCurrentRun = yield* Ref.modify(state, (latest) => { + const isCurrentRun = yield* SubscriptionRef.modify(state, (latest) => { const activeRun = Option.getOrUndefined(latest.active); if (activeRun?.id !== runId) { return [false, latest] as const; @@ -978,7 +981,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* ( reason: string, ) { - const scheduled = yield* Ref.modify(state, (latest) => { + const scheduled = yield* SubscriptionRef.modify(state, (latest) => { if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) { return [Option.none<{ delay: Duration.Duration; attempt: number }>(), latest] as const; } @@ -1006,7 +1009,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( const restartFiber = yield* Effect.forkIn( Effect.sleep(delay).pipe( Effect.andThen( - Ref.modify(state, (latest) => { + SubscriptionRef.modify(state, (latest) => { const shouldRestart = latest.desiredRunning; return [ shouldRestart, @@ -1026,7 +1029,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( ), parentScope, ); - yield* Ref.update(state, (latest) => + yield* SubscriptionRef.update(state, (latest) => Option.isNone(latest.restartFiber) ? { ...latest, @@ -1043,7 +1046,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( }) { const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)( Effect.gen(function* () { - const result = yield* Ref.modify(state, (latest) => { + const result = yield* SubscriptionRef.modify(state, (latest) => { const active = Option.map(latest.active, (run) => run.exitObserved ? run : { ...run, stopRequested: true }, ); @@ -1082,7 +1085,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( return; } const cleanup = yield* mutex.withPermits(1)( - Ref.modify( + SubscriptionRef.modify( state, ( latest, @@ -1130,23 +1133,16 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( }); }); - const waitForReady: (timeout: Duration.Duration) => Effect.Effect = Effect.fn( - "DesktopBackendManager.waitForReady", - )( - function* (_timeout: Duration.Duration) { - const current = yield* Ref.get(state); - if (!current.desiredRunning) return { done: true, ready: false }; - return current.ready ? { done: true, ready: true } : { done: false, ready: false }; - }, - (effect, timeout) => - effect.pipe( - Effect.repeat({ - until: (status) => status.done, - schedule: Schedule.spaced(Duration.millis(100)), - }), - Effect.map((status) => status.ready), + const waitForReady = Effect.fn("DesktopBackendManager.waitForReady")( + (timeout: Duration.Duration) => + SubscriptionRef.changes(state).pipe( + Stream.filter((current) => current.ready || !current.desiredRunning), + Stream.map((current) => current.ready), + Stream.runHead, Effect.timeoutOption(timeout), - Effect.map(Option.getOrElse(() => false)), + Effect.map( + (result) => Option.isSome(result) && Option.getOrElse(result.value, () => false), + ), ), ); diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts index 348d3a7050f70..be16c4ecc43ee 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts @@ -1,4 +1,5 @@ import { assert, describe, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -40,6 +41,8 @@ describe("DesktopLocalEnvironmentAuth", () => { it.effect("exchanges the desktop bootstrap credential only once", () => Effect.gen(function* () { const requestCount = yield* Ref.make(0); + const waiting = yield* Deferred.make(); + const ready = yield* Deferred.make(); const layerHttpClient = Layer.succeed( HttpClient.HttpClient, HttpClient.make((request) => @@ -68,6 +71,11 @@ describe("DesktopLocalEnvironmentAuth", () => { id: PRIMARY_LOCAL_ENVIRONMENT_ID, label: Effect.succeed("Windows"), currentConfig: Effect.succeedSome(config), + waitForReady: (timeout: Duration.Duration) => + Deferred.succeed(waiting, undefined).pipe( + Effect.andThen(Deferred.await(ready)), + Effect.timeout(timeout), + ), }, ]), } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]); @@ -77,13 +85,20 @@ describe("DesktopLocalEnvironmentAuth", () => { const [first, second] = yield* Effect.gen(function* () { const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth; - return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]); + const tokens = yield* Effect.all([auth.getBearerToken, auth.getBearerToken]).pipe( + Effect.forkChild, + ); + yield* Deferred.await(waiting); + yield* TestClock.adjust(Duration.seconds(16)); + assert.strictEqual(yield* Ref.get(requestCount), 0); + yield* Deferred.succeed(ready, true); + return yield* Fiber.join(tokens); }).pipe(Effect.provide(layerTest)); assert.strictEqual(first, "desktop-bearer-token"); assert.strictEqual(second, "desktop-bearer-token"); assert.strictEqual(yield* Ref.get(requestCount), 1); - }), + }).pipe(Effect.provide(TestClock.layer())), ); it.effect( @@ -120,6 +135,7 @@ describe("DesktopLocalEnvironmentAuth", () => { { id: PRIMARY_LOCAL_ENVIRONMENT_ID, label: Effect.succeed("Windows"), + waitForReady: () => Effect.succeed(true), currentConfig: Effect.succeedSome({ ...config, bootstrap: { ...config.bootstrap, desktopBootstrapSecret: "desktop-secret" }, @@ -167,6 +183,7 @@ describe("DesktopLocalEnvironmentAuth", () => { id: PRIMARY_LOCAL_ENVIRONMENT_ID, label: Effect.succeed("Windows"), currentConfig: Effect.succeedSome(config), + waitForReady: () => Effect.succeed(true), }, ]), } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]); diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts index 6481bfd64c897..e916b35053e8f 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts @@ -80,7 +80,10 @@ export const make = Effect.gen(function* () { const instances = yield* pool.list; const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID); - const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig; + if (primary === undefined || !(yield* primary.waitForReady(Duration.infinity))) { + return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError(); + } + const configOption = yield* primary.currentConfig; if (Option.isNone(configOption)) { return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError(); } diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 0dcb2b85ac2c5..4f8949823e354 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -549,6 +549,79 @@ describe("DesktopWindow", () => { }), ); + it.effect.each(["before", "after"] as const)( + "keeps a closed startup window closed until activation %s backend readiness", + (activation) => + Effect.gen(function* () { + const fake = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + yield* windows.ensureMain; + fake.windowListeners.get("ready-to-show")?.(); + fake.isDestroyed.mockReturnValue(true); + fake.windowListeners.get("closed")?.(); + assert.isTrue(Option.isNone(yield* Ref.get(mainWindow))); + if (activation === "after") { + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + assert.equal(yield* Ref.get(createCount), 1); + } + fake.isDestroyed.mockReturnValue(false); + yield* windows.activate; + assert.equal(yield* Ref.get(createCount), 2); + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + assert.equal(yield* Ref.get(createCount), 2); + }).pipe(Effect.provide(layerTest({ window: fake.window, createCount, mainWindow }))); + }), + ); + + it.effect.each(["renderer", "backend"] as const)( + "reveals the painted boot shell when %s becomes ready first", + (first) => + Effect.gen(function* () { + const fake = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const reveal = vi.fn(); + const painted = Promise.withResolvers(); + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + yield* windows.ensureMain; + assert.equal(fake.loadURL.mock.calls.length, 1); + yield* windows.activate; + yield* windows.revealOrCreateMain; + yield* windows.dispatchMenuAction("open-settings"); + assert.equal(reveal.mock.calls.length, 0); + if (first === "backend") { + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + assert.equal(reveal.mock.calls.length, 0); + } + fake.windowListeners.get("ready-to-show")?.(); + yield* Effect.promise(() => painted.promise); + assert.equal(reveal.mock.calls.length, 1); + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + assert.equal(yield* Ref.get(createCount), 1); + assert.equal(reveal.mock.calls.length, 1); + yield* windows.handleBackendNotReady; + yield* windows.activate; + assert.equal(reveal.mock.calls.length, 2); + }).pipe( + Effect.provide( + layerTest({ + window: fake.window, + createCount, + mainWindow, + onReveal: () => { + reveal(); + painted.resolve(); + }, + }), + ), + ); + }), + ); + it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1133,6 +1206,10 @@ describe("DesktopWindow", () => { yield* Effect.gen(function* () { const desktopWindow = yield* DesktopWindow.DesktopWindow; yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + fakeWindow.windowListeners.get("ready-to-show")?.(); + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + operations.length = 0; + foreground = "Discord"; yield* desktopWindow.dispatchSnapShotEvent({ type: "started", id: captureOne }); assert.equal(foreground, "T3 Code"); foreground = "Explorer"; diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 10801089841d1..5e02f4cfd8bbe 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -5,6 +5,7 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; +import * as Semaphore from "effect/Semaphore"; import * as Electron from "electron"; @@ -306,10 +307,17 @@ export const make = Effect.gen(function* () { const electronApp = yield* ElectronApp.ElectronApp; const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory; const backendReadyRef = yield* Ref.make(false); + let backendHasStarted = false; + let mainClosedDuringStartup = false; const splashWindowRef = yield* Ref.make>(Option.none()); const context = yield* Effect.context(); const runFork = Effect.runForkWith(context); const runPromise = Effect.runPromiseWith(context); + const mainWindowMutex = yield* Semaphore.make(1); + const pendingMainReveals = new WeakMap>(); + const revealMain = Effect.fn("desktop.window.revealMain")((window: Electron.BrowserWindow) => + Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)), + ); let flushMainWindowBounds: Effect.Effect = Effect.void; const dismissConnectingSplash = Effect.gen(function* () { @@ -407,6 +415,7 @@ export const make = Effect.gen(function* () { return Option.none(); } + pendingMainReveals.set(window, Effect.void); yield* rendererHistory.register(window.webContents, { surface: "main" }); if (environment.platform === "darwin") { window.setAutoHideCursor(false); @@ -822,14 +831,27 @@ export const make = Effect.gen(function* () { if (environment.platform === "linux") { revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire)); } + let rendererReady = false; + let firstRevealComplete = false; + const revealWhenReady = Effect.gen(function* () { + if ( + !rendererReady || + firstRevealComplete || + window.isDestroyed() || + (yield* Ref.get(desktopState.quitting)) + ) + return; + firstRevealComplete = true; + pendingMainReveals.delete(window); + window.webContents.setBackgroundThrottling(true); + if (persistedSettings.mainWindowMaximized) window.maximize(); + yield* electronWindow.reveal(window); + yield* dismissConnectingSplash; + }); + pendingMainReveals.set(window, revealWhenReady); bindFirstRevealTrigger(revealSubscribers, () => { - if (!window.isDestroyed()) { - window.webContents.setBackgroundThrottling(true); - } - if (persistedSettings.mainWindowMaximized) { - window.maximize(); - } - void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash)); + rendererReady = true; + void runPromise(revealWhenReady); }); loadApplication(); @@ -838,6 +860,7 @@ export const make = Effect.gen(function* () { } window.on("closed", () => { + if (!backendHasStarted) mainClosedDuringStartup = true; clearDevelopmentLoadRetry(); clearBoundsPersist(); void runPromise(electronWindow.clearMain(Option.some(window))); @@ -850,6 +873,7 @@ export const make = Effect.gen(function* () { const window = yield* createWindow(); if (Option.isSome(window)) { yield* electronWindow.setMain(window.value); + mainClosedDuringStartup = false; yield* logWindowInfo("main window created"); } return window; @@ -862,7 +886,7 @@ export const make = Effect.gen(function* () { return existingWindow; } return yield* createMain; - }).pipe(Effect.withSpan("desktop.window.ensureMain")); + }).pipe(mainWindowMutex.withPermits(1), Effect.withSpan("desktop.window.ensureMain")); const requireWindow = (window: Option.Option) => Option.match(window, { @@ -872,7 +896,7 @@ export const make = Effect.gen(function* () { const revealOrCreateMain = Effect.gen(function* () { const window = yield* ensureMain.pipe(Effect.flatMap(requireWindow)); - yield* electronWindow.reveal(window); + yield* revealMain(window); return window; }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain")); @@ -884,9 +908,7 @@ export const make = Effect.gen(function* () { const createMainIfBackendReady = Effect.gen(function* () { if (yield* Ref.get(desktopState.quitting)) return; if (yield* waitingForBackend) return; - const existingWindow = yield* currentMainWindow; - if (Option.isSome(existingWindow)) return; - yield* createMain; + yield* ensureMain; }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady")); const showConnectingSplash = Effect.gen(function* () { @@ -956,7 +978,7 @@ export const make = Effect.gen(function* () { }); // Send before best-effort reveal; another process may refuse to yield foreground focus. const dispatch = reveal - ? send.pipe(Effect.andThen(electronWindow.reveal(targetWindow).pipe(Effect.ignoreCause))) + ? send.pipe(Effect.andThen(revealMain(targetWindow).pipe(Effect.ignoreCause))) : send; if (targetWindow.webContents.isLoadingMainFrame()) { targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch)); @@ -971,7 +993,7 @@ export const make = Effect.gen(function* () { revealOrCreateMain, prepareCaptureReveal: Effect.gen(function* () { const existingWindow = yield* currentMainWindow; - if (Option.isSome(existingWindow)) { + if (Option.isSome(existingWindow) && !pendingMainReveals.has(existingWindow.value)) { yield* electronWindow.prepareReveal(existingWindow.value); } }), @@ -979,7 +1001,11 @@ export const make = Effect.gen(function* () { if (yield* Ref.get(desktopState.quitting)) return; const existingWindow = yield* currentMainWindow; if (Option.isSome(existingWindow)) { - yield* electronWindow.reveal(existingWindow.value); + yield* revealMain(existingWindow.value); + return; + } + if (mainClosedDuringStartup) { + yield* ensureMain; return; } const backendReady = yield* Ref.get(backendReadyRef); @@ -995,9 +1021,10 @@ export const make = Effect.gen(function* () { createMainIfBackendReady, showConnectingSplash, handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) { + backendHasStarted = true; yield* Ref.set(backendReadyRef, true); yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href }); - yield* createMainIfBackendReady; + if (!mainClosedDuringStartup) yield* createMainIfBackendReady; }), handleBackendNotReady: Ref.set(backendReadyRef, false).pipe( Effect.withSpan("desktop.window.handleBackendNotReady"), diff --git a/apps/web/src/environments/primary/httpLayer.test.ts b/apps/web/src/environments/primary/httpLayer.test.ts index 4e75873b4c523..43f72400eb92e 100644 --- a/apps/web/src/environments/primary/httpLayer.test.ts +++ b/apps/web/src/environments/primary/httpLayer.test.ts @@ -1,11 +1,20 @@ import type { DesktopBridge } from "@t3tools/contracts"; import { afterEach, describe, expect, it, vi } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import { HttpClient } from "effect/http"; import { __resetDesktopPrimaryAuthForTests } from "./desktopAuth"; import * as PrimaryEnvironmentHttpLayer from "./httpLayer"; +function createSignal() { + let resolve!: (value: A) => void; + const promise = new Promise((complete) => { + resolve = complete; + }); + return { promise, resolve }; +} + describe("primary environment HTTP layer", { concurrent: false }, () => { afterEach(() => { __resetDesktopPrimaryAuthForTests(); @@ -36,6 +45,8 @@ describe("primary environment HTTP layer", { concurrent: false }, () => { }); it.effect("uses bearer auth without cookies for desktop-managed primaries", () => { + const requested = createSignal(); + const bearerToken = createSignal(); const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 })); vi.stubGlobal("fetch", fetchMock); Object.defineProperty(globalThis, "window", { @@ -49,13 +60,22 @@ describe("primary environment HTTP layer", { concurrent: false }, () => { wsBaseUrl: "ws://127.0.0.1:3773", bootstrapToken: "desktop-bootstrap-token", }), - getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"), + getLocalEnvironmentBearerToken: () => { + requested.resolve(undefined); + return bearerToken.promise; + }, } as unknown as DesktopBridge, }, }); return Effect.gen(function* () { - yield* HttpClient.get("http://127.0.0.1:3773/api/connect/link-state"); + const requestFiber = yield* HttpClient.get( + "http://127.0.0.1:3773/api/connect/link-state", + ).pipe(Effect.forkChild); + yield* Effect.promise(() => requested.promise); + expect(fetchMock).not.toHaveBeenCalled(); + bearerToken.resolve("desktop-bearer-token"); + yield* Fiber.join(requestFiber); const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]); expect(request.credentials).not.toBe("include"); From 91f66f88de342b0485e7f5a20296b4073725b984 Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 1 Nov 2026 21:50:07 -0600 Subject: [PATCH 009/163] fix(web): settings search no longer jumps or clears on an IME Enter or Escape (#28298) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- ...ngsSidebarNav.composition.browser.test.tsx | 44 +++++++++++++++++++ .../settings/SettingsSidebarNav.tsx | 4 +- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx diff --git a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx new file mode 100644 index 0000000000000..5191b94cf49f8 --- /dev/null +++ b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx @@ -0,0 +1,44 @@ +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { act, render } from "../../../test/render"; +import { SidebarProvider } from "../ui/sidebar"; +import { SettingsSidebarNav } from "./SettingsSidebarNav"; + +vi.mock("./useAvailableSettingsSearchItems", () => ({ + useAvailableSettingsSearchItems: () => [ + { id: "theme", title: "Theme", to: "/settings/appearance" }, + ], +})); + +it("ignores composing keys in the search", async () => { + await using screen = await render( + + + , + { router: "/settings/general" }, + ); + const search = page.getByRole("combobox", { name: "Search settings" }); + await search.fill("theme"); + await expect.element(page.getByRole("option", { name: /Theme/ })).toBeVisible(); + + for (const composition of [ + { key: "Enter", isComposing: true, keyCode: 13 }, + { key: "Enter", isComposing: false, keyCode: 229 }, + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + { key: "ArrowDown", isComposing: true, keyCode: 40 }, + { key: "ArrowUp", isComposing: true, keyCode: 38 }, + ]) { + const event = new KeyboardEvent("keydown", { ...composition, bubbles: true, cancelable: true }); + await act(() => search.element().dispatchEvent(event)); + expect(event.defaultPrevented, JSON.stringify(composition)).toBe(false); + expect(screen.router?.state.location.pathname).toBe("/settings/general"); + await expect.element(search).toHaveValue("theme"); + } + + await userEvent.keyboard("{Enter}"); + await vi.waitFor(() => + expect(screen.router?.state.location.pathname).toBe("/settings/appearance"), + ); +}); diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index ee061be1ebf78..a9c8b01f077e1 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -227,6 +227,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { }; const handleSearchKeyDown = (event: KeyboardEvent) => { + if (event.nativeEvent.isComposing || event.keyCode === 229) return; if (event.key === "Escape" && isSearching) { event.preventDefault(); event.stopPropagation(); @@ -271,10 +272,11 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { )} > + {/* Native search inputs clear on Escape even during IME composition. */} { setQuery(event.currentTarget.value); From d890e5c40120769badcf18bff6d1ac983c8f40c7 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Mon, 2 Nov 2026 09:37:20 +0530 Subject: [PATCH 010/163] fix(mobile): explain why voice input is unavailable (#28698) Co-authored-by: PR Batch Tester Co-authored-by: Claude Opus 5.5 --- .../SettingsMicrophoneRouteScreen.tsx | 30 +++++++++++++++++++ docs/user/composer.md | 4 +++ 2 files changed, 34 insertions(+) diff --git a/apps/mobile/src/features/settings/SettingsMicrophoneRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsMicrophoneRouteScreen.tsx index 0af6eacd30c2c..480ae40232e39 100644 --- a/apps/mobile/src/features/settings/SettingsMicrophoneRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsMicrophoneRouteScreen.tsx @@ -18,6 +18,7 @@ import { microphoneEntryKey, microphoneOrder, } from "../../lib/microphonePriority"; +import { getLocalVoiceTranscriber } from "../../native/voiceTranscription"; import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; import { ListRowLayout } from "../../components/ui/ListRowLayout"; import { ThreadSwipeable } from "../home/thread-swipe-actions"; @@ -89,6 +90,35 @@ const KINDS: Record< }; export function SettingsMicrophoneRouteScreen() { + return getLocalVoiceTranscriber() === null ? : ; +} + +function VoiceInputUnavailable() { + const insets = useSafeAreaInsets(); + return ( + + + + + + + T3 Code's voice input uses Apple's on-device speech transcription, which needs iOS 26 or + later on a device that supports it. Without it, the composer has no microphone button, and + allowing microphone access won't add one. Apple keyboard dictation is separate and isn't + affected. + + + + ); +} + +function MicrophoneSettings() { const insets = useSafeAreaInsets(); const preferencesResult = useAtomValue(mobilePreferencesAtom); const savePreferences = useAtomSet(updateMobilePreferencesAtom); diff --git a/docs/user/composer.md b/docs/user/composer.md index 49f49a87e3690..e0c8e69bab664 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -182,6 +182,10 @@ On supported iPhones with iOS 26 or later, use the composer's microphone to reco then confirm to transcribe. Text is inserted where your selection was when recording started, ready for you to review and edit before sending. +Voice input depends on Apple's on-device speech transcription. On a device without +it, the composer has no microphone button and **Settings → Microphone** says voice +input isn't available. + The first use may download Apple's speech model and needs a network connection. Later transcription works offline for that language. Recordings can be up to five minutes long. Canceling, leaving the screen, or an audio interruption discards the From 0c4454ca6adc09058f3d311db6744788507d6af5 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 1 Nov 2026 20:56:32 -0800 Subject: [PATCH 011/163] perf(server): Codex calls t3_thread_wait directly instead of from Code Mode (#29026) Co-authored-by: Claude Opus 5.5 --- .../Adapters/CodexAdapterV2.test.ts | 8 ++++++ .../Adapters/CodexAdapterV2.ts | 28 +++++++++++++------ .../orchestrator-mcp-server.md | 23 +++++++-------- .../shared/src/t3McpToolPresentation.test.ts | 1 + 4 files changed, 41 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 54a4c2e2bf28e..1734f9e0af88b 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1530,6 +1530,14 @@ describe("CodexAdapterV2 post-settle continuation", () => { url: "http://127.0.0.1:43123/mcp", tool_timeout_sec: 3_900, http_headers: { Authorization: "Bearer secret-codex-token" }, + disabled_tools: ["t3_thread_wait"], + }, + "mcp_servers.t3code": { + url: "http://127.0.0.1:43123/mcp", + tool_timeout_sec: 3_900, + http_headers: { Authorization: "Bearer secret-codex-token" }, + enabled_tools: ["t3_thread_wait"], + omit_tools_from: ["code_mode", "deferred"], }, }, }, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index fa6bb58a9dcbe..bda631ec99c66 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1334,6 +1334,9 @@ export const CODEX_THREAD_CONFIG = { // T3 waits can block for an hour; keep Codex's MCP timeout above that. const CODEX_T3_MCP_TOOL_TIMEOUT_SEC = 65 * 60; +// Calls arrive as `t3code.`; t3McpToolPresentation.ts must keep resolving that form. +const CODEX_T3_WAIT_MCP_SERVER = "t3code"; +const CODEX_DIRECT_ONLY_T3_TOOL = "t3_thread_wait"; function codexThreadRuntimeParams(input: { readonly threadId: ThreadId | null; @@ -1346,6 +1349,14 @@ function codexThreadRuntimeParams(input: { readonly config: Readonly>; } { const { mcpSession } = input; + const t3Server = + mcpSession === undefined + ? undefined + : { + url: mcpSession.endpoint, + tool_timeout_sec: CODEX_T3_MCP_TOOL_TIMEOUT_SEC, + http_headers: { Authorization: mcpSession.authorizationHeader }, + }; return { ...(input.runtimePolicy?.cwd == null ? {} : { cwd: input.runtimePolicy.cwd }), ...(input.modelSelection === undefined ? {} : { model: input.modelSelection.model }), @@ -1355,16 +1366,17 @@ function codexThreadRuntimeParams(input: { ...(input.threadId === null ? {} : { [`shell_environment_policy.set.${PortScanner.AGENT_THREAD_ENV}`]: input.threadId }), - ...(mcpSession === undefined + ...(t3Server === undefined ? {} : { - // Override only T3's server so launch-argument MCP servers survive. - "mcp_servers.t3-code": { - url: mcpSession.endpoint, - tool_timeout_sec: CODEX_T3_MCP_TOOL_TIMEOUT_SEC, - http_headers: { - Authorization: mcpSession.authorizationHeader, - }, + // Override only T3's servers so launch-argument MCP servers survive. + "mcp_servers.t3-code": { ...t3Server, disabled_tools: [CODEX_DIRECT_ONLY_T3_TOOL] }, + // Code Mode runs a blocking wait as a nested call, and the model keeps working + // around it. A second, direct-only registration makes it a plain tool call. + [`mcp_servers.${CODEX_T3_WAIT_MCP_SERVER}`]: { + ...t3Server, + enabled_tools: [CODEX_DIRECT_ONLY_T3_TOOL], + omit_tools_from: ["code_mode", "deferred"], }, }), }, diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index f46803f9d67b6..77f95873f06a6 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -58,17 +58,18 @@ check the `orchestration` capability before reading or mutating state. ### Codex V2 -Codex app-server receives the remote MCP server through command-line config -overrides: - -```text --c mcp_servers.t3-code.url=http://127.0.0.1:/mcp --c mcp_servers.t3-code.bearer_token_env_var="T3_MCP_BEARER_TOKEN" -``` - -The provider-session token is placed in `T3_MCP_BEARER_TOKEN`. Both the -production Codex launcher and the injectable test launcher use the same -projection helper. +Codex gets T3's MCP server in each thread's `thread/start`, `thread/resume`, +and `thread/fork` config, with the provider-session token in an +`Authorization` header. The same server is registered twice: + +- `t3-code`: every tool except `t3_thread_wait`. +- `t3code`: only `t3_thread_wait`, with `omit_tools_from = ["code_mode", "deferred"]`. + +Code Mode runs a nested call as part of a script, so the model keeps working +while a blocking wait runs. The second entry makes the wait a direct tool call, +like Codex's own wait tools. Codex reports calls as `.`, so +`packages/shared/src/t3McpToolPresentation.ts` must resolve both server names. +Tool display and pending-work detection depend on it. ### Claude Agent SDK V2 diff --git a/packages/shared/src/t3McpToolPresentation.test.ts b/packages/shared/src/t3McpToolPresentation.test.ts index 1c2683753656c..cd27e5cc452bd 100644 --- a/packages/shared/src/t3McpToolPresentation.test.ts +++ b/packages/shared/src/t3McpToolPresentation.test.ts @@ -16,6 +16,7 @@ describe("resolveT3McpToolPresentation", () => { "mcp__t3_code__", "mcp__t3code__", "T3-code.", + "t3code.", "t3_code/", "t3code:", "mcp_t3-code_", From 23075af981e40f7c1071871782d489896c3919f6 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 1 Nov 2026 21:07:01 -0800 Subject: [PATCH 012/163] refactor(server): name Codex's direct-only T3 MCP server t3-code-direct (#29068) Co-authored-by: Claude Opus 5.5 --- .../Adapters/CodexAdapterV2.test.ts | 2 +- .../orchestration-v2/Adapters/CodexAdapterV2.ts | 7 ++++--- docs/orchestration-v2/orchestrator-mcp-server.md | 2 +- .../shared/src/t3McpToolPresentation.test.ts | 2 ++ packages/shared/src/t3McpToolPresentation.ts | 16 ++++++++++++---- 5 files changed, 20 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 1734f9e0af88b..2d14fa9518de6 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1532,7 +1532,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { http_headers: { Authorization: "Bearer secret-codex-token" }, disabled_tools: ["t3_thread_wait"], }, - "mcp_servers.t3code": { + "mcp_servers.t3-code-direct": { url: "http://127.0.0.1:43123/mcp", tool_timeout_sec: 3_900, http_headers: { Authorization: "Bearer secret-codex-token" }, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index bda631ec99c66..f81a3809b35fe 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1334,8 +1334,9 @@ export const CODEX_THREAD_CONFIG = { // T3 waits can block for an hour; keep Codex's MCP timeout above that. const CODEX_T3_MCP_TOOL_TIMEOUT_SEC = 65 * 60; -// Calls arrive as `t3code.`; t3McpToolPresentation.ts must keep resolving that form. -const CODEX_T3_WAIT_MCP_SERVER = "t3code"; +// Holds T3 tools Codex must call directly, never from Code Mode. Calls arrive as +// `t3-code-direct.`; t3McpToolPresentation.ts must keep resolving that form. +const CODEX_T3_DIRECT_MCP_SERVER = "t3-code-direct"; const CODEX_DIRECT_ONLY_T3_TOOL = "t3_thread_wait"; function codexThreadRuntimeParams(input: { @@ -1373,7 +1374,7 @@ function codexThreadRuntimeParams(input: { "mcp_servers.t3-code": { ...t3Server, disabled_tools: [CODEX_DIRECT_ONLY_T3_TOOL] }, // Code Mode runs a blocking wait as a nested call, and the model keeps working // around it. A second, direct-only registration makes it a plain tool call. - [`mcp_servers.${CODEX_T3_WAIT_MCP_SERVER}`]: { + [`mcp_servers.${CODEX_T3_DIRECT_MCP_SERVER}`]: { ...t3Server, enabled_tools: [CODEX_DIRECT_ONLY_T3_TOOL], omit_tools_from: ["code_mode", "deferred"], diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 77f95873f06a6..11e7bd9a8d06e 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -63,7 +63,7 @@ and `thread/fork` config, with the provider-session token in an `Authorization` header. The same server is registered twice: - `t3-code`: every tool except `t3_thread_wait`. -- `t3code`: only `t3_thread_wait`, with `omit_tools_from = ["code_mode", "deferred"]`. +- `t3-code-direct`: only `t3_thread_wait`, with `omit_tools_from = ["code_mode", "deferred"]`. Code Mode runs a nested call as part of a script, so the model keeps working while a blocking wait runs. The second entry makes the wait a direct tool call, diff --git a/packages/shared/src/t3McpToolPresentation.test.ts b/packages/shared/src/t3McpToolPresentation.test.ts index cd27e5cc452bd..4d30e4972d605 100644 --- a/packages/shared/src/t3McpToolPresentation.test.ts +++ b/packages/shared/src/t3McpToolPresentation.test.ts @@ -17,6 +17,8 @@ describe("resolveT3McpToolPresentation", () => { "mcp__t3code__", "T3-code.", "t3code.", + "t3-code-direct.", + "mcp__t3_code_direct__", "t3_code/", "t3code:", "mcp_t3-code_", diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index 3fc2db1648e96..864bcd8950d41 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -86,7 +86,14 @@ function tool( return { displayName, labels, icon, summaryAction }; } -const T3_MCP_SERVER_ALIASES = new Set(["t3-code", "t3_code", "t3code"]); +// Codex registers "t3-code-direct" for T3 tools kept out of Code Mode. +const T3_MCP_SERVER_ALIASES = new Set([ + "t3-code", + "t3_code", + "t3code", + "t3-code-direct", + "t3_code_direct", +]); const T3_MCP_TOOLS: Readonly> = { link_pull_request: tool( @@ -386,9 +393,10 @@ function resolveT3McpToolName(value: string): string | null { : null; } - const namespaceMatch = /^(?t3-code|t3_code|t3code)(?:[.:/]|\s*·\s*)(?.+)$/i.exec( - label, - ); + const namespaceMatch = + /^(?t3[-_]code[-_]direct|t3-code|t3_code|t3code)(?:[.:/]|\s*·\s*)(?.+)$/i.exec( + label, + ); if (namespaceMatch?.groups) { return namespaceMatch.groups.tool ?? null; } From b12ab30950b7231c50410703befb922464292e8b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 1 Nov 2026 21:25:46 -0800 Subject: [PATCH 013/163] fix(mobile): files with brackets in their names attach on Android (#28983) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/lib/composerImages.test.ts | 32 +++++++++++++++++++++- apps/mobile/src/lib/composerImages.ts | 6 ++-- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts index cac785d299dfe..ac01bb09b4261 100644 --- a/apps/mobile/src/lib/composerImages.test.ts +++ b/apps/mobile/src/lib/composerImages.test.ts @@ -59,6 +59,19 @@ vi.mock("expo-file-system", () => ({ return files.get(this.uri)?.mimeType ?? ""; } + get size(): number | null { + const entry = files.get(this.uri); + return entry && !entry.deleted + ? Math.floor((entry.base64.replace(/=+$/, "").length * 3) / 4) + : null; + } + + async copy(destination: { readonly uri: string }): Promise { + const entry = files.get(this.uri); + if (!entry) throw new Error("missing file"); + files.set(destination.uri, { ...entry }); + } + async base64(): Promise { const entry = files.get(this.uri); if (!entry || entry.deleted) { @@ -98,6 +111,7 @@ vi.mock("expo-file-system", () => ({ create(): void {} }, + FileMode: { ReadOnly: "r", WriteOnly: "w" }, Paths: { document: "file:///documents" }, })); @@ -105,7 +119,7 @@ vi.mock("./uuid", () => ({ uuidv4: () => "attachment-id", })); -import { convertPastedImagesToAttachments } from "./composerImages"; +import { convertPastedImagesToAttachments, persistComposerAttachmentFile } from "./composerImages"; describe("native pasted image cleanup", () => { beforeEach(() => { @@ -204,6 +218,22 @@ describe("native pasted image cleanup", () => { }); }); +describe("persistComposerAttachmentFile", () => { + beforeEach(() => { + files.clear(); + }); + + it("stores picked files under a name Android's java.net.URI accepts", async () => { + const source = "file:///cache/DocumentPicker/Report [draft].pdf"; + files.set(source, { base64: "JVBERg==", deleted: false }); + + const fileUri = await persistComposerAttachmentFile(source, "Report [draft].pdf"); + + // expo-file-system encodes spaces and `%` but leaves `[`, `]`, `|` and `^` raw. + expect(fileUri.split("/").at(-1)).toMatch(/^[\w\-.!~*'();:@&=+$, %]+\.pdf$/); + }); +}); + describe("composerStripAttachments", () => { const image = { id: "img-1", diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index a32298b74beb9..5b8b0b803d3fa 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -127,10 +127,8 @@ export async function persistComposerAttachmentFile( const { Directory, File, FileMode, Paths } = await import("expo-file-system"); const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY); directory.create({ idempotent: true, intermediates: true }); - const safeName = - Array.from(name, (character) => - character === "/" || character === "\\" || character.charCodeAt(0) < 32 ? "-" : character, - ).join("") || "file"; + // Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`. + const safeName = name.replace(/[^\w. -]/g, "-") || "file"; const destination = new File(directory, `${uuidv4()}-${safeName}`); const source = new File(uri); const sourceSize = source.size; From 5f2c27e706de72c9f4dcb80f9a30db1bdfdc6e51 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 1 Nov 2026 21:26:21 -0800 Subject: [PATCH 014/163] fix(server): Stop ends a run whose provider turn already finished (#28520) Co-authored-by: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 23 +++--- .../src/orchestration-v2/ThreadStop.test.ts | 78 +++++++++++++++++++ 2 files changed, 91 insertions(+), 10 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 1fed13e08ad0b..2dc0a5a66d5b0 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -10448,7 +10448,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio rootNode === undefined || run.activeAttemptId !== attempt.id || run.status !== "running" || - attempt.status !== "running" + attempt.status === "pending" ) return; const emitEvent = emit(input.events, input.command); @@ -10470,15 +10470,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, }); } - yield* emitEvent({ - ...base, - type: "run-attempt.updated", - payload: { - ...attempt, - status: "interrupted", - completedAt: input.now, - }, - }); + // An attempt that already ended keeps its status; only its run was left running. + if (attempt.status === "running") { + yield* emitEvent({ + ...base, + type: "run-attempt.updated", + payload: { + ...attempt, + status: "interrupted", + completedAt: input.now, + }, + }); + } const providerThread = input.projection.providerThreads.find( (candidate) => candidate.id === input.providerTurn.providerThreadId, ); diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index 16dcedaf8ac9c..6b3ea08a86449 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -1664,3 +1664,81 @@ it.effect("an unanswered Stop is flagged until Force stop ends the run with its assert.lengthOf(late.storedEvents, 0); }).pipe(Effect.provide(layerTest)), ); + +it.effect.each(["Stop", "Force stop"] as const)( + "%s ends a running run whose provider turn already completed", + (action) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread:stop-completed-turn"); + yield* createWatchingThread(threadId, 7); + yield* send(threadId, "go", "start_immediately"); + const now = yield* DateTime.now; + const started = yield* orchestrator.getThreadProjection(threadId); + const run = started.runs[0]!; + const attempt = started.attempts[0]!; + const providerThreadId = run.providerThreadId!; + const providerTurnId = ProviderTurnId.make("provider-turn:stop-completed-turn"); + const apply = (event: Omit) => + projections.apply({ + ...event, + id: EventId.make(`event:stop-completed-turn:${event.type}`), + threadId, + } as OrchestrationV2DomainEvent); + yield* apply({ + type: "run.updated", + runId: run.id, + occurredAt: now, + payload: { ...run, status: "running", startedAt: now, activeAttemptId: attempt.id }, + }); + yield* apply({ + type: "run-attempt.updated", + occurredAt: now, + payload: { ...attempt, status: "completed", startedAt: now, completedAt: now }, + }); + yield* apply({ + type: "provider-turn.updated", + occurredAt: now, + payload: { + id: providerTurnId, + providerThreadId, + nodeId: run.rootNodeId!, + runAttemptId: attempt.id, + nativeTurnRef: null, + ordinal: 1, + status: "completed", + startedAt: now, + completedAt: now, + }, + }); + // The provider session was already released. + yield* apply({ + type: "provider-thread.updated", + occurredAt: now, + payload: { + ...started.providerThreads.find((thread) => thread.id === providerThreadId)!, + providerSessionId: ProviderSessionId.make("session:gone"), + }, + }); + yield* send(threadId, "follow", "queue_after_active"); + + if (action === "Stop") { + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("stop-completed-turn"), + threadId, + }); + } else { + const threads = yield* ThreadManagementService.ThreadManagementService; + yield* threads.forceStopThread({ threadId }); + } + const stopped = yield* orchestrator.getThreadProjection(threadId); + assert.notEqual(stopped.runs[0]?.status, "running", "the stopped run is still running"); + assert.deepInclude(stopped.attempts[0], { status: "completed", completedAt: now }); + assert.isTrue( + stopped.turnItems.some((item) => item.type === "run_interrupt_result"), + "the stopped run has no interrupt result", + ); + }).pipe(Effect.provide(layerTest)), +); From 83d2b8e3478b85cbe9691b7e4941e06b81856be7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 1 Nov 2026 21:26:26 -0800 Subject: [PATCH 015/163] fix(server): a linked retry closes the waiting link card it names (#28387) Co-authored-by: Claude Opus 5.5 --- apps/server/src/peer/PeerLinkRequests.test.ts | 29 +++++++ apps/server/src/peer/PeerLinkRequests.ts | 78 +++++++++++++++---- 2 files changed, 91 insertions(+), 16 deletions(-) diff --git a/apps/server/src/peer/PeerLinkRequests.test.ts b/apps/server/src/peer/PeerLinkRequests.test.ts index ed45167a3536a..208de28a52b78 100644 --- a/apps/server/src/peer/PeerLinkRequests.test.ts +++ b/apps/server/src/peer/PeerLinkRequests.test.ts @@ -951,6 +951,35 @@ it.live("naming a machine that is already linked returns the link at once, with ), ); +it.live("a retry naming a machine linked meanwhile closes the card it left as linked", () => + withBoth((a, b) => + Effect.gen(function* () { + yield* seedThread(a); + yield* a.call({ url: b.url, clientRequestId: "link-box" }); + yield* pendingCard(a); + // Linked from Settings meanwhile, not through the card. + const pairing = yield* b.auth.issuePairingCredential(); + yield* a.links.link({ url: b.url, pairingCode: pairing.credential, access: "auto" }); + + const retried = yield* a.call({ + environmentId: box.environmentId, + clientRequestId: "link-box", + }); + expect(retried.structuredContent).toEqual({ + status: "linked", + environmentId: box.environmentId, + label: "Box", + access: "auto", + }); + expect(yield* cardOf(a)).toMatchObject({ + linkStatus: "linked", + linkedEnvironmentId: box.environmentId, + }); + expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toBeNull(); + }), + ), +); + it.live("a link that expired goes through the card, so the user can link it again", () => withBoth((a, b) => Effect.gen(function* () { diff --git a/apps/server/src/peer/PeerLinkRequests.ts b/apps/server/src/peer/PeerLinkRequests.ts index 15f4877873276..faf36e2fe8f62 100644 --- a/apps/server/src/peer/PeerLinkRequests.ts +++ b/apps/server/src/peer/PeerLinkRequests.ts @@ -136,6 +136,42 @@ const make = Effect.gen(function* () { ...(wake === undefined ? {} : { wake }), }); + const linkedOutcome = (linked: PeerLink): LinkRequestOutcome => ({ + linkStatus: "linked", + linkedEnvironmentId: linked.environmentId, + linkedLabel: linked.label, + linkedAccess: linked.access, + }); + + // One answer per card at a time: two answers racing on one card must not + // both link. Other cards go on while a slow peer holds one. + const answerLocks = yield* KeyedLock.make(); + + /** + * Closes a card still waiting when its agent retries naming a machine linked + * meanwhile. Nothing wakes the agent: the retry itself returns the link. + */ + const closeAsLinked = (threadId: ThreadId, turnItemId: TurnItemId, linked: PeerLink) => + answerLocks.withLock( + turnItemId, + Effect.gen(function* () { + const card = yield* readCard(threadId, turnItemId); + if ( + card === undefined || + card.linkStatus !== "pending" || + card.runId === null || + card.nodeId === null + ) { + return; + } + yield* record( + { ...card, runId: card.runId, nodeId: card.nodeId }, + linkedOutcome(linked), + CommandId.make(`link-request:${card.id}:linked-on-retry`), + ); + }), + ); + const request: PeerLinkRequests["Service"]["request"] = Effect.fn("PeerLinkRequests.request")( function* (scope, input) { // The card is shown in, and answered from, the caller's own thread. @@ -171,6 +207,21 @@ const make = Effect.gen(function* () { ), ); if (Option.isSome(linked)) { + if (input.clientRequestId !== undefined) { + yield* closeAsLinked( + threadId, + cardId(threadId, scope.requestNamespace, input.clientRequestId), + linked.value, + ).pipe( + Effect.mapError( + (error) => + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: `Could not close the link request: ${errorMessage(error)}`, + }), + ), + ); + } return { status: "linked", environmentId: linked.value.environmentId, @@ -180,12 +231,8 @@ const make = Effect.gen(function* () { } } const key = input.clientRequestId ?? (yield* crypto.randomUUIDv4().pipe(Effect.orDie)); - // Turn item ids are global; scope the key to this thread and provider - // session, since a later session may reuse it. A retry with the same - // clientRequestId finds this card and records nothing. - const turnItemId = TurnItemId.make( - `turn-item:link-request:${encodeURIComponent(threadId)}:${encodeURIComponent(scope.requestNamespace)}:${encodeURIComponent(key)}`, - ); + // A retry with the same clientRequestId finds this card and records nothing. + const turnItemId = cardId(threadId, scope.requestNamespace, key); if (input.clientRequestId !== undefined) { const existing = yield* readCard(threadId, turnItemId).pipe(Effect.mapError(unreadable)); if (existing !== undefined) return resultOf(existing); @@ -244,13 +291,6 @@ const make = Effect.gen(function* () { Effect.withSpan("PeerLinkRequests.request"), ); - const linkedOutcome = (linked: PeerLink): LinkRequestOutcome => ({ - linkStatus: "linked", - linkedEnvironmentId: linked.environmentId, - linkedLabel: linked.label, - linkedAccess: linked.access, - }); - /** Links the machine the user picked, or finds the link they chose to keep. */ const answerOutcome = ( answer: PeerLinkRequestAnswerInput["answer"], @@ -300,9 +340,6 @@ const make = Effect.gen(function* () { } }; - // One answer per card at a time: two answers racing on one card must not - // both link. Other cards go on while a slow peer holds one. - const answerLocks = yield* KeyedLock.make(); const answer: PeerLinkRequests["Service"]["answer"] = Effect.fn("PeerLinkRequests.answer")( function* (input) { yield* Effect.annotateCurrentSpan({ @@ -345,6 +382,15 @@ const make = Effect.gen(function* () { return PeerLinkRequests.of({ request, answer }); }); +/** + * Turn item ids are global; scope the key to this thread and provider session, + * since a later session may reuse it. + */ +const cardId = (threadId: ThreadId, requestNamespace: string, key: string) => + TurnItemId.make( + `turn-item:link-request:${encodeURIComponent(threadId)}:${encodeURIComponent(requestNamespace)}:${encodeURIComponent(key)}`, + ); + const pendingResult = (turnItemId: TurnItemId): OrchestratorMcpEnvironmentLinkResult => ({ status: "pending", turnItemId, From 1973e0a68f45a11b642d521724543431585d5f9e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 1 Nov 2026 21:30:54 -0800 Subject: [PATCH 016/163] fix(server): a stored boolean settledOverride no longer stops startup (#28314) Co-authored-by: Claude Opus 5.5 --- apps/server/src/persistence/Migrations.ts | 2 + .../077_RepairBooleanSettledOverride.test.ts | 88 +++++++++++++++++++ .../077_RepairBooleanSettledOverride.ts | 14 +++ .../reconcileV2PreviewMigration.test.ts | 2 + 4 files changed, 106 insertions(+) create mode 100644 apps/server/src/persistence/Migrations/077_RepairBooleanSettledOverride.test.ts create mode 100644 apps/server/src/persistence/Migrations/077_RepairBooleanSettledOverride.ts diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index e13c2b449d9e7..feab4ef823f00 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -79,6 +79,7 @@ import Migration0073 from "./Migrations/073_ActiveTurnItemIndexes.ts"; import Migration0074 from "./Migrations/074_ExcludeAttachmentPlaceholdersFromSearch.ts"; import Migration0075 from "./Migrations/075_SubagentDeliveryState.ts"; import Migration0076 from "./Migrations/076_ProjectionProjectsPinArchive.ts"; +import Migration0077 from "./Migrations/077_RepairBooleanSettledOverride.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -158,6 +159,7 @@ const migrationEntries = [ [74, "ExcludeAttachmentPlaceholdersFromSearch", Migration0074], [75, "SubagentDeliveryState", Migration0075], [76, "ProjectionProjectsPinArchive", Migration0076], + [77, "RepairBooleanSettledOverride", Migration0077], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/077_RepairBooleanSettledOverride.test.ts b/apps/server/src/persistence/Migrations/077_RepairBooleanSettledOverride.test.ts new file mode 100644 index 0000000000000..02c51df5782b3 --- /dev/null +++ b/apps/server/src/persistence/Migrations/077_RepairBooleanSettledOverride.test.ts @@ -0,0 +1,88 @@ +import { assert, it } from "@effect/vitest"; +import { OrchestrationV2AppThreadJson } from "@t3tools/contracts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; + +const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" })); +const createdAt = "2026-09-01T00:00:00.000Z"; +const decodeThreadPayload = Schema.decodeUnknownEffect( + Schema.fromJsonString(OrchestrationV2AppThreadJson), +); + +layer("077_RepairBooleanSettledOverride", (it) => { + it.effect("canonicalizes boolean settled overrides so recovery can decode them", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 76 }); + const overrides: ReadonlyArray = [ + ["true", true], + ["false", false], + ["settled", "settled"], + ["active", "active"], + ["null", null], + ["absent", undefined], + ]; + for (const [id, settledOverride] of overrides) { + const payload = { + id, + projectId: "project-1", + title: id, + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "user", + creationSource: "web", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id }, + forkedFrom: null, + createdAt, + updatedAt: createdAt, + archivedAt: null, + deletedAt: null, + settledOverride, + settledAt: settledOverride === true ? createdAt : null, + }; + yield* sql` + INSERT INTO orchestration_v2_projection_threads ( + thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, + created_at, updated_at, payload_json + ) VALUES ( + ${id}, 'project-1', ${id}, 'codex', 'full-access', 'default', + ${createdAt}, ${createdAt}, ${JSON.stringify(payload)} + ) + `; + } + const rows = sql<{ readonly thread_id: string; readonly payload_json: string }>` + SELECT thread_id, payload_json FROM orchestration_v2_projection_threads ORDER BY thread_id + `; + const before = new Map((yield* rows).map((row) => [row.thread_id, row.payload_json])); + + yield* runMigrations({ toMigrationInclusive: 77 }); + const after = new Map((yield* rows).map((row) => [row.thread_id, row.payload_json])); + for (const id of ["settled", "active", "null", "absent"]) { + assert.strictEqual(after.get(id), before.get(id)); + } + const repaired = yield* sql` + SELECT thread_id, + json_type(payload_json, '$.settledOverride') AS type, + json_extract(payload_json, '$.settledOverride') AS settled_override, + json_extract(payload_json, '$.settledAt') AS settled_at + FROM orchestration_v2_projection_threads WHERE thread_id IN ('true', 'false') + ORDER BY thread_id + `; + assert.deepStrictEqual(repaired, [ + { thread_id: "false", type: "null", settled_override: null, settled_at: null }, + { thread_id: "true", type: "text", settled_override: "settled", settled_at: createdAt }, + ]); + const thread = yield* decodeThreadPayload(after.get("true")); + assert.strictEqual(thread.settledOverride, "settled"); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/077_RepairBooleanSettledOverride.ts b/apps/server/src/persistence/Migrations/077_RepairBooleanSettledOverride.ts new file mode 100644 index 0000000000000..e84473964fc61 --- /dev/null +++ b/apps/server/src/persistence/Migrations/077_RepairBooleanSettledOverride.ts @@ -0,0 +1,14 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +// Thread projections may hold a boolean settledOverride, which the thread schema rejects. +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql` + UPDATE orchestration_v2_projection_threads + SET payload_json = json_set(payload_json, '$.settledOverride', + IIF(json_type(payload_json, '$.settledOverride') = 'true', 'settled', NULL)) + WHERE json_valid(payload_json) + AND json_type(payload_json, '$.settledOverride') IN ('true', 'false') + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 08c5094bf49c8..4083978758ce0 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -56,6 +56,7 @@ describe("V2 preview upgrade", () => { [74, "ExcludeAttachmentPlaceholdersFromSearch"], [75, "SubagentDeliveryState"], [76, "ProjectionProjectsPinArchive"], + [77, "RepairBooleanSettledOverride"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -155,6 +156,7 @@ describe("V2 preview upgrade", () => { [74, "ExcludeAttachmentPlaceholdersFromSearch"], [75, "SubagentDeliveryState"], [76, "ProjectionProjectsPinArchive"], + [77, "RepairBooleanSettledOverride"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From da2d6ec2c881aaca225e7219e232e7a07a41b6fd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 1 Nov 2026 21:32:05 -0800 Subject: [PATCH 017/163] fix(server): remote updates no longer fail when the staged preflight is slow on a loaded host (#28201) Co-authored-by: Claude Opus 5.5 --- apps/server/src/cloud/selfUpdate.test.ts | 39 ++++++++++++++++++++++++ apps/server/src/cloud/selfUpdate.ts | 3 +- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/apps/server/src/cloud/selfUpdate.test.ts b/apps/server/src/cloud/selfUpdate.test.ts index 8070ea2af7368..9e1aee9c095aa 100644 --- a/apps/server/src/cloud/selfUpdate.test.ts +++ b/apps/server/src/cloud/selfUpdate.test.ts @@ -3,6 +3,7 @@ import { expect, it } from "@effect/vitest"; import type { ManagedPolicyDocument } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; @@ -26,6 +27,8 @@ interface HarnessOptions { readonly mode?: "web" | "desktop"; readonly managed?: boolean; readonly preflight?: "ready" | "blocked"; + readonly preflightDuration?: Duration.Input; + readonly preflightStarted?: Deferred.Deferred; readonly beforeDownload?: Effect.Effect; readonly requestUpdate?: ServiceLauncherClient.ServiceLauncherClient["Service"]["requestUpdate"]; readonly desktopAppUpdate?: DesktopAppUpdate.DesktopAppUpdate["Service"]; @@ -78,6 +81,21 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* ( stderrInvalidUtf8: false, }; } + if (options.preflightStarted) yield* Deferred.succeed(options.preflightStarted, undefined); + if (options.preflightDuration !== undefined) { + // Like the real runner, fail once the caller's timeout elapses. + const timeout = Duration.fromInputUnsafe(input.timeout ?? "60 seconds"); + const finished = yield* Effect.sleep(options.preflightDuration).pipe( + Effect.timeoutOption(timeout), + ); + if (finished._tag === "None") { + return yield* new ProcessRunner.ProcessTimeoutError({ + command: input.command, + argumentCount: input.args.length, + timeoutMs: Duration.toMillis(timeout), + }); + } + } order.push("preflight"); const result = options.preflight === "blocked" @@ -240,6 +258,27 @@ it.layer(NodeServices.layer)("server self update", (it) => { }), ); + // regression: #28198 a slow staged preflight on a loaded host no longer fails the update + it.effect("waits for a staged preflight that takes a minute on a loaded host", () => + Effect.gen(function* () { + const preflightStarted = yield* Deferred.make(); + const { selfUpdate, order } = yield* makeHarness({ + preflightDuration: "60 seconds", + preflightStarted, + }); + const update = yield* Effect.forkChild(selfUpdate.update({ targetVersion: "1.1.0" }), { + startImmediately: true, + }); + yield* Deferred.await(preflightStarted); + yield* TestClock.adjust("60 seconds"); + const exit = yield* Fiber.await(update); + expect(exit._tag === "Failure" ? String(exit.cause) : "launcher handoff").toBe( + "launcher handoff", + ); + expect(order).toEqual(["download", "extract", "preflight", "accept"]); + }), + ); + it.effect("keeps preparing after the progress stream closes", () => Effect.gen(function* () { const releaseDownload = yield* Deferred.make(); diff --git a/apps/server/src/cloud/selfUpdate.ts b/apps/server/src/cloud/selfUpdate.ts index 67e3e1f9413bd..1f285b9b6522e 100644 --- a/apps/server/src/cloud/selfUpdate.ts +++ b/apps/server/src/cloud/selfUpdate.ts @@ -45,7 +45,8 @@ import { decodeServicePreflightResult } from "./servicePreflight.ts"; import * as ServiceLauncherClient from "./serviceLauncherClient.ts"; import { isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts"; -const PREFLIGHT_TIMEOUT = Duration.seconds(30); +// A staged runtime's cold start can take over a minute on a loaded, swapping host. +const PREFLIGHT_TIMEOUT = Duration.minutes(3); export function resolveServerSelfUpdateCapability(input: { readonly desktopManaged: boolean; From 79f3ee139b99a932178c4bd7c191c4a7f5cf0481 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 1 Nov 2026 21:32:48 -0800 Subject: [PATCH 018/163] fix(server): idle compaction survives a late update for an earlier run (#28102) Co-authored-by: Claude Opus 5.5 --- .../orchestration-v2/IdleCompaction.test.ts | 85 +++++++++++++++++++ .../orchestration-v2/IdleCompactionService.ts | 14 ++- 2 files changed, 97 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/IdleCompaction.test.ts b/apps/server/src/orchestration-v2/IdleCompaction.test.ts index 65360492bd2df..3c13452e98e7f 100644 --- a/apps/server/src/orchestration-v2/IdleCompaction.test.ts +++ b/apps/server/src/orchestration-v2/IdleCompaction.test.ts @@ -308,4 +308,89 @@ describe("IdleCompactionService", () => { ); }, ); + + it.effect("keeps the latest run's compaction when an earlier run reports completed again", () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const base = records({ cacheExpiresInMs: 10 * MINUTE_MS }); + const laterRunId = RunId.make("run-2"); + const laterMessageId = MessageId.make("message-2"); + const earlierRun = base.runs[0]!; + const laterRun = { + ...earlierRun, + id: laterRunId, + ordinal: 2, + userMessageId: laterMessageId, + }; + const data: OrchestrationV2ThreadProjection = { + ...base, + runs: [earlierRun, laterRun], + messages: [ + ...base.messages, + { ...base.messages[0]!, id: laterMessageId, runId: laterRunId, text: "Keep going" }, + ], + providerThreads: [{ ...base.providerThreads[0]!, lastRunOrdinal: 2 }], + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + plans: [], + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + visibleTurnItems: [], + updatedAt: at(), + }; + const completed = (run: typeof earlierRun) => ({ + id: EventId.make(`completed-${run.id}`), + type: "run.updated" as const, + threadId, + runId: run.id, + occurredAt: at(), + payload: run, + }); + const dispatched: Array = []; + const streamDone = yield* Deferred.make(); + const dependencies = Layer.mergeAll( + Layer.mock(Orchestrator.OrchestratorV2)({ + // A delegated completion on the earlier run lands after the later run completed. + streamDomainEvents: Stream.make(completed(laterRun), completed(earlierRun)).pipe( + Stream.ensuring(Deferred.succeed(streamDone, undefined)), + ), + dispatch: (command) => + Effect.sync(() => { + dispatched.push(command.commandId); + return { sequence: 1, storedEvents: [] }; + }), + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThread: () => Effect.succeed(data.thread), + getThreadRecords: (_threadId, _keys, options) => + Effect.succeed({ + ...data, + messages: data.messages.filter( + (message) => + options?.messageRunIds === undefined || + (message.runId !== null && options.messageRunIds.includes(message.runId)), + ), + }), + }), + Layer.mock(ServerSettings.ServerSettingsService)({ + getSettings: Effect.succeed({ + ...DEFAULT_SERVER_SETTINGS, + idleCompaction: "beforeCacheExpires", + }), + }), + ); + yield* Effect.gen(function* () { + const service = yield* IdleCompactionService.make; + yield* service.start(); + yield* Deferred.await(streamDone); + yield* TestClock.adjust(9 * MINUTE_MS); + }).pipe(Effect.provide(dependencies)); + expect(dispatched).toEqual(["server:idle-compact:idle-thread:run-2"]); + }), + ), + ); }); diff --git a/apps/server/src/orchestration-v2/IdleCompactionService.ts b/apps/server/src/orchestration-v2/IdleCompactionService.ts index 415bb14fa1a88..ce47b0f697700 100644 --- a/apps/server/src/orchestration-v2/IdleCompactionService.ts +++ b/apps/server/src/orchestration-v2/IdleCompactionService.ts @@ -31,8 +31,9 @@ export const make = Effect.gen(function* () { const settings = yield* ServerSettings.ServerSettingsService; const compactWhenDue = Effect.fn("IdleCompactionService.compactWhenDue")( - function* (threadId: ThreadId, runId: RunId) { - // Loops once after the wait: the thread may have moved on. + function* (threadId: ThreadId, completedRunId: RunId) { + let runId = completedRunId; + // Loops after the wait or a retarget: the thread may have moved on. while (true) { const current = yield* settings.getSettings; const thread = yield* projections.getThread(threadId); @@ -72,6 +73,15 @@ export const make = Effect.gen(function* () { ) ) return; + const latestRun = records.runs.reduce<(typeof records.runs)[number] | undefined>( + (latest, run) => (latest === undefined || run.ordinal > latest.ordinal ? run : latest), + undefined, + ); + // A late update for an earlier run replaced the latest run's timer, so take it over. + if (latestRun?.status === "completed" && latestRun.id !== runId) { + runId = latestRun.id; + continue; + } const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const window = idleCompactionWindow(records, nowMs); if (window?.runId !== runId) return; From a51164c52b12356bb10ed142a72550003ce8ddb9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 1 Nov 2026 21:33:21 -0800 Subject: [PATCH 019/163] fix(server): usage prices bare model names at the maker's rate when a reseller marks them up (#28004) Co-authored-by: Claude Opus 5.5 --- apps/server/src/usage/usagePricing.test.ts | 28 ++++++++++++++++++++++ apps/server/src/usage/usagePricing.ts | 24 ++++++++++++++----- 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.ts index 2ce6d6f74eff7..b22625b7e490c 100644 --- a/apps/server/src/usage/usagePricing.test.ts +++ b/apps/server/src/usage/usagePricing.test.ts @@ -258,4 +258,32 @@ describe("usage pricing", () => { expect(lookupRate(table, "provider-b/example-model")?.inputCostPerToken).toBe(3); expect(lookupRate(table, "example-model")).toBeNull(); }); + + it("prices a bare name at the model maker's rate when a reseller marks it up", () => { + const reseller = { "kyma/gemini-4-argon": rate(5.4e-6) }; + const makers = { + "gemini/gemini-4-argon": rate(2e-6, 1e-7), + "vertex_ai/gemini-4-argon": rate(2e-6, 1e-7), + }; + + for (const document of [ + { ...reseller, ...makers }, + { ...makers, ...reseller }, + ]) { + const table = parseRateTable(document); + expect(lookupRate(table, "gemini-4-argon")).toEqual( + lookupRate(table, "gemini/gemini-4-argon"), + ); + } + }); + + it("leaves a bare name unpriced when model makers' own entries disagree", () => { + const table = parseRateTable({ + "openai/example-model": rate(1), + "xai/example-model": rate(3), + "kyma/example-model": rate(1), + }); + + expect(lookupRate(table, "example-model")).toBeNull(); + }); }); diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index fa512218d7c0c..1f515abb736c8 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -89,6 +89,17 @@ function fastMultiplier(entry: LiteLlmEntry): number | null { return fast !== null && fast > 0 ? fast : null; } +// LiteLLM prefixes for the model makers' own APIs; their price beats a cloud's or reseller's for a bare name. +const FIRST_PARTY_PROVIDERS = new Set([ + "anthropic", + "deepseek", + "gemini", + "meta", + "mistral", + "openai", + "xai", +]); + /** Drops models missing input or output rates to avoid understating cost. */ export function parseRateTable(document: unknown): RateTable { const table = new Map(); @@ -113,18 +124,19 @@ export function parseRateTable(document: unknown): RateTable { }); } - const aliasCandidates = new Map(); + const aliasCandidates = new Map(); for (const [key, rate] of table) { const alias = bareModelName(key); if (alias.length === 0 || alias === key || table.has(alias)) continue; + const firstParty = FIRST_PARTY_PROVIDERS.has(key.slice(0, key.indexOf("/"))); const held = aliasCandidates.get(alias); - if (held === undefined) { - aliasCandidates.set(alias, rate); - } else if (held !== null) { - aliasCandidates.set(alias, mergeAliasRate(held, rate)); + if (held === undefined || (firstParty && !held.firstParty)) { + aliasCandidates.set(alias, { rate, firstParty }); + } else if (held.rate !== null && firstParty === held.firstParty) { + aliasCandidates.set(alias, { rate: mergeAliasRate(held.rate, rate), firstParty }); } } - for (const [alias, rate] of aliasCandidates) { + for (const [alias, { rate }] of aliasCandidates) { if (rate !== null) table.set(alias, rate); } From 72f05f6d8e64aca11df8e76331bab560485dfe65 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 1 Nov 2026 21:33:34 -0800 Subject: [PATCH 020/163] fix(web): model picker uses the full window height in short windows (#29017) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/chat/ProviderModelPicker.tsx | 6 +++++- apps/web/src/components/ui/popover.tsx | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 848b1ee4532db..2e47b4c2fe3b4 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -415,7 +415,11 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { }} initialFocus={searchInputRef} align={props.popupAlign ?? "start"} - collisionAvoidance={docked ? { align: "shift", fallbackAxisSide: "none" } : undefined} + // Docked, the popup opens above the composer and slides over it when that space is short, + // so a short window gets its full height (Floating UI sizes to the viewport) instead of a sliver. + {...(docked + ? { side: "top" as const, collisionAvoidance: { side: "shift", align: "shift" } as const } + : {})} className="before:hidden" padding="none" touchBackdrop diff --git a/apps/web/src/components/ui/popover.tsx b/apps/web/src/components/ui/popover.tsx index 2261b1a8f54c3..788c8a1043def 100644 --- a/apps/web/src/components/ui/popover.tsx +++ b/apps/web/src/components/ui/popover.tsx @@ -78,7 +78,7 @@ function PopoverPopup({ collisionAvoidance={collisionAvoidance} collisionPadding={variant === "panel" ? 0 : undefined} className={cn( - "h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-transform data-instant:transition-none", + "h-(--positioner-height) max-h-(--available-height) w-(--positioner-width) max-w-(--available-width) transition-transform data-instant:transition-none", variant === "panel" ? "z-(--z-sheet) w-[min(calc(var(--thread-details-panel-width)+--spacing(4)),calc(var(--anchor-width)---spacing(2)))] transition-[top] duration-150 ease-out data-instant:transition-[top] motion-reduce:transition-none motion-reduce:data-instant:transition-none" : "z-[130]", From 5fc5a1d095cf7bb324115aed4f3df08581079dfc Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 1 Nov 2026 21:34:05 -0800 Subject: [PATCH 021/163] fix(server): open clients no longer stay on "Updating" after a provider update (#27992) Co-authored-by: Claude Opus 5.5 --- .../src/provider/ProviderRegistry.test.ts | 161 ++++++++++++++++++ apps/server/src/provider/ProviderRegistry.ts | 3 +- 2 files changed, 163 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 5e1bc9e962b5f..f04db9118ecc3 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -1904,6 +1904,167 @@ it.layer( }), ); + it.effect("streams the terminal update state when it lands during a slow cache write", () => + Effect.gen(function* () { + const claudeDriver = ProviderDriverKind.make("claude"); + const claudeInstanceId = ProviderInstanceId.make("claude"); + const initialProvider = { + instanceId: claudeInstanceId, + driver: claudeDriver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-04-14T00:00:00.000Z", + version: "2.1.300", + models: [], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const verifyingProvider = { ...initialProvider, checkedAt: "2026-04-14T00:01:00.000Z" }; + const laterProvider = { ...initialProvider, checkedAt: "2026-04-14T00:02:00.000Z" }; + const changes = yield* PubSub.unbounded(); + const instance = { + instanceId: claudeInstanceId, + driverKind: claudeDriver, + continuationIdentity: { + driverKind: claudeDriver, + continuationKey: "claude:instance:claude", + }, + displayName: undefined, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: claudeDriver, + packageName: null, + }), + ), + getSnapshot: Effect.succeed(initialProvider), + refresh: Effect.succeed(initialProvider), + streamChanges: Stream.fromPubSub(changes), + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + const layerInstanceRegistry = Layer.succeed( + ProviderInstanceRegistry.ProviderInstanceRegistry, + { + getInstance: (instanceId) => + Effect.succeed(instanceId === claudeInstanceId ? instance : undefined), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => + PubSub.subscribe(pubsub), + ), + }, + ); + const writeStarted = yield* Deferred.make(); + const releaseWrite = yield* Deferred.make(); + const gatedCachePath = yield* Ref.make(undefined); + const layerGatedFileSystem = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return { + ...fileSystem, + rename: (from, to) => + Ref.modify(gatedCachePath, (path) => + path === to ? [true, undefined] : [false, path], + ).pipe( + Effect.flatMap((gated) => + gated + ? Deferred.succeed(writeStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseWrite)), + ) + : Effect.void, + ), + Effect.andThen(fileSystem.rename(from, to)), + ), + } satisfies FileSystem.FileSystem; + }), + ).pipe(Layer.provide(NodeServices.layer)); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const runtimeServices = yield* Layer.build( + ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), + Layer.provideMerge(layerInstanceRegistry), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-update-state-race-", + }), + ), + Layer.provideMerge(layerBackgroundPolicyAlwaysRun), + Layer.provideMerge(layerGatedFileSystem), + Layer.provideMerge(NodeServices.layer), + ), + ).pipe(Scope.provide(scope)); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry.ProviderRegistry; + const config = yield* ServerConfig.ServerConfig; + const running = { + status: "running", + startedAt: "2026-04-14T00:00:30.000Z", + finishedAt: null, + message: "Verifying the installed version", + output: null, + } as const; + const unchanged = { + ...running, + status: "unchanged", + finishedAt: "2026-04-14T00:01:30.000Z", + message: + "Update command completed, but T3 Code still detects an outdated provider version.", + } as const; + yield* registry.setProviderMaintenanceActionState({ + instanceId: claudeInstanceId, + action: "update", + state: running, + }); + const streamed = yield* registry.streamChanges.pipe( + Stream.takeUntil((providers) => + providers.some((provider) => provider.checkedAt === laterProvider.checkedAt), + ), + Stream.runCollect, + Effect.forkScoped({ startImmediately: true }), + ); + + yield* Ref.set( + gatedCachePath, + yield* resolveProviderStatusCachePath({ + cacheDir: config.providerStatusCacheDir, + instanceId: claudeInstanceId, + }), + ); + yield* PubSub.publish(changes, verifyingProvider); + yield* Deferred.await(writeStarted); + yield* registry.setProviderMaintenanceActionState({ + instanceId: claudeInstanceId, + action: "update", + state: unchanged, + }); + yield* Deferred.succeed(releaseWrite, undefined); + // The snapshot stream is consumed in order, so this lands after the slow write publishes. + yield* PubSub.publish(changes, laterProvider); + + const updateStateOf = (providers: ReadonlyArray | undefined) => + providers?.find((provider) => provider.instanceId === claudeInstanceId)?.updateState; + const beforeLater = (yield* Fiber.join(streamed)).slice(0, -1); + assert.deepStrictEqual(updateStateOf(yield* registry.getProviders), unchanged); + assert.deepStrictEqual( + updateStateOf(beforeLater.at(-1)), + unchanged, + "the last streamed providers before the next snapshot should carry the terminal update state", + ); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + it.effect( "persists authoritative OpenCode removals without resurrecting them on a failed live refresh", () => diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 3234bfd61960a..e8a13a0617c34 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -524,7 +524,8 @@ export const layer = Layer.effect( }); } if (options?.publish !== false) { - yield* PubSub.publish(changesPubSub, providers); + // A newer upsert may have committed and published during the cache write; never republish an older array. + yield* PubSub.publish(changesPubSub, yield* Ref.get(providersRef)); } } From 333f7a6f6e6b074ba28aca662ff4052c99280d15 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 1 Nov 2026 21:37:08 -0800 Subject: [PATCH 022/163] ci(release): preview releases run from any branch (#27828) Co-authored-by: Claude Opus 5.5 --- .github/workflows/release.yml | 16 +++++++++++++++- docs/operations/release.md | 10 +++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c36d51bdadb1a..82f39f8034cc4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -395,8 +395,12 @@ jobs: (github.event_name != 'schedule' || needs.resolve_commit.outputs.has_changes == 'true') runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 5 + # Previews build any branch, but production admits only main and v* tags. + # The empty name runs previews with no environment, so their Clerk and relay + # ids come from .env.example. Everything else matches nightly: the tracing + # read below needs only repository-level Cloudflare credentials. environment: - name: production + name: ${{ inputs.channel != 'preview' && 'production' || '' }} outputs: clerk_publishable_key: ${{ steps.public_config.outputs.clerk_publishable_key }} clerk_jwt_template: ${{ steps.public_config.outputs.clerk_jwt_template }} @@ -462,9 +466,19 @@ jobs: - id: public_config name: Resolve production relay public config shell: bash + env: + PREVIEW: ${{ inputs.channel == 'preview' }} run: | set -euo pipefail + if [[ "$PREVIEW" == "true" ]]; then + env_example() { sed -n "s|^T3CODE_$1=||p" .env.example; } + CLERK_PUBLISHABLE_KEY="$(env_example CLERK_PUBLISHABLE_KEY)" + CLERK_JWT_TEMPLATE="$(env_example CLERK_JWT_TEMPLATE)" + CLERK_CLI_OAUTH_CLIENT_ID="$(env_example CLERK_CLI_OAUTH_CLIENT_ID)" + RELAY_DOMAIN="$(sed -n 's|^T3CODE_RELAY_URL=https://||p' .env.example)" + fi + relay_domain="${RELAY_DOMAIN:-}" if [[ -z "$relay_domain" && -n "${RELAY_API_ZONE_NAME:-}" ]]; then relay_domain="relay.$RELAY_API_ZONE_NAME" diff --git a/docs/operations/release.md b/docs/operations/release.md index 29b9a2b9bfb58..4dd489bfde064 100644 --- a/docs/operations/release.md +++ b/docs/operations/release.md @@ -106,9 +106,13 @@ The relay is a shared control plane versioned separately from client releases. S client builds must point at the same relay so users see the same linked environments when switching release channels. -`.github/workflows/deploy-relay.yml` deploys Alchemy stage `prod` on every push to `main`. The -release workflow reads the relay URL and Clerk client configuration from the existing `production` -GitHub Actions environment before building desktop, CLI, or hosted web artifacts. +`.github/workflows/deploy-relay.yml` deploys Alchemy stage `prod` on every push to `main`. Stable +and nightly releases read the relay URL and Clerk client configuration from the existing +`production` GitHub Actions environment before building desktop, CLI, or hosted web artifacts. That +environment admits only `main` and `v*` tags, so preview releases, which may run from any branch, +take the same public identifiers from `.env.example`; keep it in step with the `production` values. +Every channel reads the relay client tracing config from Alchemy state with the repository-level +`CLOUDFLARE_API_TOKEN`, so moving that token into `production` would break preview releases. Required repository variables shared by relay deployments: From 0338e99fe359ea6e4c1b93ef60245597f76cd522 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 1 Nov 2026 21:50:21 -0800 Subject: [PATCH 023/163] fix(desktop): save and copy any image the app can show (#29079) Co-authored-by: Claude Opus 5.5 --- apps/desktop/src/ipc/DesktopIpcHandlers.ts | 2 + apps/desktop/src/ipc/channels.ts | 1 + apps/desktop/src/ipc/methods/window.test.ts | 50 +++++++++++++++++++ apps/desktop/src/ipc/methods/window.ts | 42 ++++++++++++++++ apps/desktop/src/preload.ts | 1 + .../src/components/media/mediaContent.test.ts | 19 +++++++ apps/web/src/components/media/mediaContent.ts | 31 ++++++++---- packages/contracts/src/ipc.ts | 9 ++++ 8 files changed, 144 insertions(+), 11 deletions(-) diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index dc9c47e042742..a46dbafab0f41 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -40,6 +40,7 @@ import { getSystemLocale, getWindowFullscreenState, openExternal, + readMedia, openSystemSettings, checkSystemPermission, pasteAsText, @@ -141,6 +142,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(setTheme); yield* ipc.handle(showContextMenu); yield* ipc.handle(openExternal); + yield* ipc.handle(readMedia); yield* ipc.handle(receiveProviderAuthCallback); yield* ipc.handle(cancelProviderAuthCallback); yield* ipc.handle(openSystemSettings); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 538dd06b0b42a..0f125c05de307 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -5,6 +5,7 @@ export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files"; export const SET_THEME_CHANNEL = "desktop:set-theme"; export const CONTEXT_MENU_CHANNEL = "desktop:context-menu"; export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external"; +export const READ_MEDIA_CHANNEL = "desktop:read-media"; export const OPEN_SYSTEM_SETTINGS_CHANNEL = "desktop:open-system-settings"; export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors"; export const MENU_ACTION_CHANNEL = "desktop:menu-action"; diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index eacc92c94996d..2ddc672891755 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -9,6 +9,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import { vi } from "vite-plus/test"; +import type * as Electron from "electron"; const { focusedWebContents, ownerWindow } = vi.hoisted(() => ({ focusedWebContents: vi.fn(), @@ -33,6 +34,7 @@ import { installRelayTelemetryEnabled, pickProjectFavicon, probeRemoteEditors, + readMedia, } from "./window.ts"; const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = { @@ -234,6 +236,54 @@ describe("installRelayTelemetryEnabled", () => { ); }); +describe("readMedia", () => { + it.effect("reads http(s) media only for the main window", () => + Effect.gen(function* () { + const mib = new Uint8Array(1024 * 1024); + const fetch = vi.fn(async (url: string) => { + if (url.endsWith("/missing.png")) return new Response("Not Found", { status: 404 }); + if (url.endsWith("/small.png")) return new Response(new Uint8Array([1, 2])); + let sent = 0; + // 257 MiB from one reused chunk: over the cap without allocating it. + const huge = new ReadableStream({ + pull: (controller) => (sent++ < 257 ? controller.enqueue(mib) : controller.close()), + }); + return new Response(huge); + }); + const main = { + webContents: { id: 1, session: { fetch } }, + } as unknown as Electron.BrowserWindow; + const read = (url: string, senderId: number) => + readMedia + .handler(url, { sender: { id: senderId } }) + .pipe( + Effect.provide( + Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(main) }), + ), + ); + + assert.strictEqual(yield* read("https://example.com/a.png", 2), null); + assert.strictEqual(yield* read("file:///etc/passwd", 1), null); + assert.strictEqual(fetch.mock.calls.length, 0); + assert.deepEqual(yield* read("https://example.com/small.png", 1), { + status: 200, + mimeType: "", + data: Buffer.from([1, 2]), + }); + assert.deepEqual(yield* read("https://example.com/missing.png", 1), { + status: 404, + mimeType: "text/plain;charset=UTF-8", + data: new Uint8Array(), + }); + assert.deepEqual(yield* read("https://example.com/huge.mp4", 1), { + status: 413, + mimeType: "", + data: new Uint8Array(), + }); + }), + ); +}); + describe("pickProjectFavicon", () => { const pickerLayer = ( pickFiles: () => Effect.Effect>, diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 473d1874078be..63b8db03dad03 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -2,6 +2,7 @@ import { ContextMenuItemSchema, DesktopAppBrandingSchema, DesktopEnvironmentBootstrapSchema, + DesktopMediaReadSchema, DesktopThemeSchema, EDITORS, EditorId, @@ -311,6 +312,47 @@ export const openExternal = DesktopIpc.makeIpcMethod({ }), }); +const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024; + +// The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it. +export const readMedia = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.READ_MEDIA_CHANNEL, + payload: Schema.String, + result: Schema.NullOr(DesktopMediaReadSchema), + handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url, event) { + const window = yield* (yield* ElectronWindow.ElectronWindow).main; + if ( + event === undefined || + Option.isNone(window) || + window.value.webContents.id !== event.sender.id || + !/^https?:$/.test(URL.parse(url)?.protocol ?? "") + ) { + return null; + } + const session = window.value.webContents.session; + return yield* Effect.tryPromise(async () => { + // Like an , send the session's cookies. + const response = await session.fetch(url, { credentials: "include" }); + const mimeType = response.headers.get("content-type") ?? ""; + if (!response.ok || !response.body) { + await response.body?.cancel(); + return { status: response.status, mimeType, data: new Uint8Array() }; + } + // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory. + const chunks: Uint8Array[] = []; + let size = 0; + for await (const chunk of response.body) { + size += chunk.byteLength; + if (size > READ_MEDIA_MAX_BYTES) { + return { status: 413, mimeType, data: new Uint8Array() }; + } + chunks.push(chunk); + } + return { status: response.status, mimeType, data: Buffer.concat(chunks) }; + }).pipe(Effect.orElseSucceed(() => null)); + }), +}); + export const openSystemSettings = DesktopIpc.makeIpcMethod({ channel: IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL, payload: SystemSettingsPaneSchema, diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 950ed972c6453..da56807186ac5 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -202,6 +202,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { cancelProviderAuthCallback: (url: string) => ipcRenderer.invoke(IpcChannels.CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL, url), openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url), + readMedia: (url: string) => ipcRenderer.invoke(IpcChannels.READ_MEDIA_CHANNEL, url), checkSystemPermission: (pane: string) => ipcRenderer.invoke(IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL, pane), openSystemSettings: (pane: string) => diff --git a/apps/web/src/components/media/mediaContent.test.ts b/apps/web/src/components/media/mediaContent.test.ts index fb95a7e0eacda..03d5185bb90f6 100644 --- a/apps/web/src/components/media/mediaContent.test.ts +++ b/apps/web/src/components/media/mediaContent.test.ts @@ -55,3 +55,22 @@ it("keeps remote media on the fetch path", async () => { expect(await readMediaPng("https://example.com/image.png")).toEqual(png); expect(fetch).toHaveBeenCalledWith("https://example.com/image.png"); }); + +it("reads media the renderer cannot fetch through the desktop main process", async () => { + using fetch = vi.spyOn(globalThis, "fetch").mockRejectedValue(new TypeError("Failed to fetch")); + const readMedia = vi.fn().mockResolvedValue({ + status: 200, + mimeType: "image/png", + data: new Uint8Array(PNG_BYTES), + }); + vi.stubGlobal("window", { desktopBridge: { readMedia } }); + try { + const png = await readMediaPng("https://example.com/image.png"); + + expect(fetch).toHaveBeenCalledOnce(); + expect(readMedia).toHaveBeenCalledWith("https://example.com/image.png"); + expect([...new Uint8Array(await png.arrayBuffer())]).toEqual(PNG_BYTES); + } finally { + vi.unstubAllGlobals(); + } +}); diff --git a/apps/web/src/components/media/mediaContent.ts b/apps/web/src/components/media/mediaContent.ts index 4b1edab6a3d45..a5a4cec61143a 100644 --- a/apps/web/src/components/media/mediaContent.ts +++ b/apps/web/src/components/media/mediaContent.ts @@ -40,19 +40,28 @@ function readDataUrlBlob(src: string): Blob { } } +async function fetchMediaBlob(src: string): Promise { + const response = await fetch(src).catch(() => null); + if (response?.ok) return response.blob(); + // An can show media that fetch() may not read (CORS, CSP, cookies); desktop reads it natively. + const desktop = typeof window === "undefined" ? undefined : window.desktopBridge; + const native = + desktop && /^https?:/i.test(src) ? await desktop.readMedia(src).catch(() => null) : null; + if (native && native.status >= 200 && native.status < 300) { + return new Blob([new Uint8Array(native.data)], { type: native.mimeType }); + } + const status = native?.status ?? response?.status; + if (status !== undefined) throw new Error(`The file could not be fetched (HTTP ${status}).`); + throw new Error( + desktop + ? "The file could not be fetched. Check the connection and try again." + : "The file could not be fetched. The host may block browser access (CORS), or the connection may be unavailable.", + ); +} + async function readMediaBlob(src: string): Promise { if (/^data:/i.test(src)) return readDataUrlBlob(src); - let response: Response; - try { - response = await fetch(src); - } catch (cause) { - throw new Error( - "The file could not be fetched. The host may block browser access (CORS), or the connection may be unavailable.", - { cause }, - ); - } - if (!response.ok) throw new Error(`The file could not be fetched (HTTP ${response.status}).`); - const blob = await response.blob(); + const blob = await fetchMediaBlob(src); if (blob.type.split(";", 1)[0] === "text/html") { throw new Error("This link returned a web page instead of media. Open the original URL."); } diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 59f8fd12c3f1a..5aa9acf2773a7 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1012,6 +1012,13 @@ export const DesktopPreviewRecordingSaveInputSchema = Schema.Struct({ data: Schema.Uint8Array, }); +export const DesktopMediaReadSchema = Schema.Struct({ + status: Schema.Number, + mimeType: Schema.String, + data: Schema.Uint8Array, +}); +export type DesktopMediaRead = typeof DesktopMediaReadSchema.Type; + export const SystemSettingsPaneSchema = Schema.Literals(["full-disk-access"]); export type SystemSettingsPane = typeof SystemSettingsPaneSchema.Type; @@ -1099,6 +1106,8 @@ export interface DesktopBridge { receiveProviderAuthCallback: (authorizationUrl: string) => Promise; cancelProviderAuthCallback: (authorizationUrl: string) => Promise; openExternal: (url: string) => Promise; + /** Reads http(s) media in the main process, outside renderer CORS and CSP; null on network failure. */ + readMedia: (url: string) => Promise; openSystemSettings: (pane: SystemSettingsPane) => Promise; checkSystemPermission: (pane: SystemSettingsPane) => Promise; probeRemoteEditors: () => Promise; From c65f8d552baca1b51e15b5fb4737f07e18cce177 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 1 Nov 2026 21:53:04 -0800 Subject: [PATCH 024/163] feat(chat): threads show when you switch models or effort (#28995) Co-authored-by: Claude Opus 5.5 --- .../src/features/threads/ThreadFeed.tsx | 16 ++- .../threads/thread-context-divider.tsx | 6 +- .../features/threads/thread-handoff-row.tsx | 35 +++++- apps/mobile/src/lib/filePreview.test.ts | 2 +- .../src/orchestration-v2/Orchestrator.ts | 16 ++- .../SelectionRestart.integration.test.ts | 11 ++ .../SteeringCompletion.integration.test.ts | 49 ++++++++ .../src/orchestration-v2/modelSwitch.test.ts | 107 ++++++++++++++++++ .../src/orchestration-v2/modelSwitch.ts | 42 +++++++ .../chat/TimelineUserMessageRow.tsx | 15 +++ .../src/components/chat/V2LifecycleRow.tsx | 27 +++++ packages/client-runtime/src/handoff.test.ts | 97 ++++++++++++++++ packages/client-runtime/src/handoff.ts | 56 +++++++++ packages/contracts/src/orchestrationV2.ts | 9 ++ .../provider-core/src/server/notification.ts | 1 + 15 files changed, 483 insertions(+), 6 deletions(-) create mode 100644 apps/server/src/orchestration-v2/modelSwitch.test.ts create mode 100644 apps/server/src/orchestration-v2/modelSwitch.ts diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index b43e246fc9c4f..3eeda330ca0a6 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -15,7 +15,11 @@ import { enrichedSkillReference, } from "../../lib/enrichedLinkPresentation"; import { ThreadContextDivider } from "./thread-context-divider"; -import { ThreadHandoffDivider, ThreadHandoffRow } from "./thread-handoff-row"; +import { + ThreadHandoffDivider, + ThreadHandoffRow, + ThreadModelSwitchDivider, +} from "./thread-handoff-row"; import { GuestBubbleTint, GuestMessageName } from "./guestMessageStyle"; import { ThreadGuestPendingMessage, useThreadGuestShare } from "./ThreadGuestShareBar"; import { LinkRequestCard } from "./LinkRequestCard"; @@ -3590,6 +3594,16 @@ export const ThreadFeed = memo(function ThreadFeed({ workspaceRoot={props.workspaceRoot} > + {info.item.type === "message" && + !isCompactionCommandFeedEntry(info.item) && + info.item.message.projectedItem?.item.type === "user_message" && + info.item.message.projectedItem.item.modelSwitch ? ( + + ) : null} {renderFeedEntry(info, { userMessageGrouping: info.item.userMessageGrouping, environmentId: props.environmentId, diff --git a/apps/mobile/src/features/threads/thread-context-divider.tsx b/apps/mobile/src/features/threads/thread-context-divider.tsx index 082f655d11955..19c99f6e63e45 100644 --- a/apps/mobile/src/features/threads/thread-context-divider.tsx +++ b/apps/mobile/src/features/threads/thread-context-divider.tsx @@ -6,7 +6,7 @@ import { ShimmeringWorkContent } from "./thread-work-log"; export function ThreadContextDivider(props: { label: string; - icon: AppSymbolName; + icon?: AppSymbolName; iconColor: ColorValue; active?: boolean; failed?: boolean; @@ -16,7 +16,9 @@ export function ThreadContextDivider(props: { - + {props.icon ? ( + + ) : null} {props.active ? ( { + const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId); + const model = provider?.models.find((candidate) => candidate.slug === selection.model); + const modelName = + (model ? resolveModelShortName(model, provider?.driver) : undefined) ?? + model?.name ?? + selection.model; + return [change.modelChanged ? modelName : null, effort].filter(Boolean).join(" "); + }; + const { from, to } = props.modelSwitch; + return ( + + ); +} + export function ThreadHandoffRow(props: { environmentId: EnvironmentId; projectedItem: OrchestrationV2ProjectedTurnItem; diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index 0363f6862448f..61e69a6d9c7f9 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -269,7 +269,7 @@ vi.mock("./openExternalUrl", () => ({})); vi.mock("./attachmentDownload", () => ({})); vi.mock("./uuid", () => ({})); vi.mock("../features/threads/thread-context-divider", () => ({})); -vi.mock("../features/threads/thread-handoff-row", () => ({})); +vi.mock("../features/threads/thread-handoff-row", () => ({ ThreadModelSwitchDivider: () => null })); vi.mock("../features/threads/ThreadGuestShareBar", () => ({ useThreadGuestShare: () => null })); vi.mock("../features/threads/SecretRequestCard", () => ({})); vi.mock("../features/threads/LinkRequestCard", () => ({ LinkRequestCard: () => null })); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 2dc0a5a66d5b0..906cda379913e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -48,6 +48,7 @@ import { type OrchestrationV2ProviderThread, type OrchestrationV2ProviderTurn, type OrchestrationV2RemoteTaskChild, + type OrchestrationV2ModelSwitch, type OrchestrationV2Run, type OrchestrationV2RunAttempt, type OrchestrationV2ThreadShell, @@ -75,6 +76,7 @@ import { managedRuntimeModeCeilingMessage, } from "@t3tools/contracts"; import { modelSelectionsEqual } from "@t3tools/shared/model"; +import { modelSwitchSince } from "./modelSwitch.ts"; import { recordThreadOpen } from "@t3tools/shared/paletteSearch"; import { backgroundWorkHoldsCompletion, @@ -2055,6 +2057,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio startedAt: now, completedAt: now, updatedAt: now, + ...(activeHandoff === null ? modelSwitchSince(projection, queuedRun.modelSelection) : {}), }; const handoffTurnItem: OrchestrationV2TurnItem | null = activeHandoff === null @@ -4796,6 +4799,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio readonly providerTurnId: typeof providerTurn.id | null; readonly providerThreadId: OrchestrationV2ProviderThread["id"]; readonly providerInstanceId: ProviderInstanceId; + readonly modelSwitch?: OrchestrationV2ModelSwitch | undefined; }) { const message: OrchestrationV2ConversationMessage = { createdBy: input.createdBy, @@ -4851,6 +4855,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio text: input.text, attachments: input.attachments, ...(input.context ? { context: input.context } : {}), + ...(messageInput.modelSwitch === undefined + ? {} + : { modelSwitch: messageInput.modelSwitch }), }; yield* emitEvent({ type: "message.updated", @@ -5311,6 +5318,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerTurnId: null, providerThreadId: restartProviderThread.id, providerInstanceId: input.modelSelection.instanceId, + // Measured on the pre-restart projection, so the rewritten run is not its own baseline. + ...(restartHandoff === null ? modelSwitchSince(input.projection, input.modelSelection) : {}), }); const interruptedAttemptId = targetRun.activeAttemptId; if (interruptedAttemptId === null) { @@ -6424,6 +6433,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio text: dispatchText, ...(command.context ? { context: command.context } : {}), attachments: command.attachments, + ...(run.contextHandoffId === null ? modelSwitchSince(projection, modelSelection) : {}), }; const preparationTurnItem: OrchestrationV2TurnItem | null = dispatchMode.type === "defer_start" @@ -7175,6 +7185,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio text: dispatchText, ...(command.context ? { context: command.context } : {}), attachments: command.attachments, + ...(run.contextHandoffId === null + ? modelSwitchSince(projection, modelSelection, sourceRun?.modelSelection) + : {}), }; const activeHandoff = portableForkHandoff ?? mergeBackHandoff ?? providerSwitchHandoff; const handoffSourceRuns = @@ -9349,7 +9362,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio "runtimeRequests", "subagents", ], - { turnItemTypes: [], messageRoles: ["user"] }, + // User messages measure a restart's model switch. + { turnItemTypes: ["user_message"], messageRoles: ["user"] }, ); if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) { return yield* new OrchestratorDispatchError({ diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts index d059c4c20e9d7..4352d8b2d6477 100644 --- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts +++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts @@ -5,6 +5,7 @@ import { MessageId, type ModelSelection, type OrchestrationV2ProviderCapabilities, + type OrchestrationV2ThreadProjection, type OrchestrationV2ProviderSession, type OrchestrationV2ProviderThread, ProjectId, @@ -47,6 +48,10 @@ const seedSelection = { instanceId: providerInstanceId, model: "seed-model", } satisfies ModelSelection; +const modelSwitches = (projection: OrchestrationV2ThreadProjection) => + projection.turnItems.flatMap((item) => + item.type === "user_message" && item.modelSwitch !== undefined ? [item.modelSwitch] : [], + ); const pooledCapabilities: OrchestrationV2ProviderCapabilities = CodexProviderCapabilitiesV2; const exclusiveCapabilities: OrchestrationV2ProviderCapabilities = { ...CodexProviderCapabilitiesV2, @@ -407,6 +412,9 @@ it.live("retries a failed selection restart session open before completing", () "selection restart supersede must not project hard-Stop interrupt items", ); assert.equal(projection.runs.at(-1)?.modelSelection.model, replacementSelection.model); + assert.deepEqual(modelSwitches(projection), [ + { from: initialSelection, to: replacementSelection }, + ]); assert.equal(projection.runs.at(-1)?.status, "completed"); assert.isTrue(captured.failedReplacementOpen); assert.equal(captured.closedSessionCount, 0); @@ -690,6 +698,9 @@ it.live( const { projection, captured } = result; assert.lengthOf(projection.runs, 2); assert.equal(projection.runs[1]?.modelSelection.model, replacementSelection.model); + assert.deepEqual(modelSwitches(projection), [ + { from: seedSelection, to: replacementSelection }, + ]); assert.deepEqual(result.detachedSessionIds, [result.liveSessionId]); assert.equal(captured.closedSessionCount, 1); assert.deepEqual( diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 3297119852231..840a24a3da18a 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1175,6 +1175,55 @@ it.effect("steers a promoted queued message with the selection it was queued wit ), ); +it.effect("marks the model switch on a promoted message that restarts the turn", () => + Effect.scoped( + Effect.gen(function* () { + const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "promote-restart-switch", + true, + false, + ); + const otherSelection = { ...runSelection, model: "other-model" }; + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("queued"), + threadId, + messageId: MessageId.make("message:queued"), + text: "queued", + attachments: [], + modelSelection: otherSelection, + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "queued", + )!; + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: queuedRun.id, + targetRunId: started[0]!.runId, + }); + yield* worker.drain(); + + const promoted = (yield* orchestrator.getThreadProjection(threadId)).turnItems.find( + (item) => item.type === "user_message" && item.messageId === "message:queued", + ); + assert.deepEqual(promoted?.type === "user_message" ? promoted.modelSwitch : undefined, { + from: runSelection, + to: otherSelection, + }); + }).pipe(Effect.provide(layer)); + }), + ), +); + it.effect("keeps a queued message queued when promoted into a run that Stop reached", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/modelSwitch.test.ts b/apps/server/src/orchestration-v2/modelSwitch.test.ts new file mode 100644 index 0000000000000..940340074c1f2 --- /dev/null +++ b/apps/server/src/orchestration-v2/modelSwitch.test.ts @@ -0,0 +1,107 @@ +import { + ContextHandoffId, + MessageId, + ProviderInstanceId, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { modelSwitchSince } from "./modelSwitch.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const selection = (model: string) => ({ instanceId, model }); +const run = ( + message: string, + ordinal: number, + model: string, + status: OrchestrationV2ThreadProjection["runs"][number]["status"] = "completed", +) => + ({ + ordinal, + status, + completedAt: null, + contextHandoffId: null, + userMessageId: MessageId.make(message), + modelSelection: selection(model), + }) as OrchestrationV2ThreadProjection["runs"][number]; +const shown = (...messages: ReadonlyArray) => + messages.map((message) => ({ + type: "user_message", + messageId: MessageId.make(message), + inputIntent: "turn_start", + status: "completed", + text: message, + attachments: [], + })) as unknown as OrchestrationV2ThreadProjection["turnItems"]; + +describe("modelSwitchSince", () => { + it("measures from the latest run whose message is in the timeline", () => { + // B failed before it started; its message shows "a -> b", so the next one must show "b -> a". + expect( + modelSwitchSince( + { + runs: [ + run("first", 1, "a"), + run("failed", 2, "b", "failed"), + run("queued", 3, "c", "queued"), + run("undone", 4, "d", "rolled_back"), + ], + turnItems: shown("first", "failed", "queued", "undone"), + }, + selection("a"), + ), + ).toEqual({ modelSwitch: { from: selection("b"), to: selection("a") } }); + }); + + it("skips messages clients hide", () => { + const [first, pending, compact, answer] = shown( + "first", + "pending", + "/compact", + "async-answer:question", + ); + expect( + modelSwitchSince( + { + runs: [ + run("first", 1, "a"), + run("pending", 2, "b", "cancelled"), + run("/compact", 3, "c"), + run("async-answer:question", 4, "d"), + ], + turnItems: [ + first!, + { ...pending!, inputIntent: "queued_turn", status: "pending" }, + compact!, + answer!, + ] as OrchestrationV2ThreadProjection["turnItems"], + }, + selection("c"), + ), + ).toEqual({ modelSwitch: { from: selection("a"), to: selection("c") } }); + }); + + it("counts a wake whose handoff row shows the swap", () => { + const wake = { + ...run("wake", 2, "other"), + contextHandoffId: ContextHandoffId.make("handoff"), + }; + expect( + modelSwitchSince( + { runs: [run("first", 1, "a"), wake], turnItems: shown("first") }, + selection("other"), + ), + ).toEqual({}); + }); + + it("records nothing for a first run or an unchanged selection", () => { + expect(modelSwitchSince({ runs: [], turnItems: [] }, selection("a"))).toEqual({}); + // A fork's first message compares with the run it forked from. + expect(modelSwitchSince({ runs: [], turnItems: [] }, selection("a"), selection("b"))).toEqual({ + modelSwitch: { from: selection("b"), to: selection("a") }, + }); + expect( + modelSwitchSince({ runs: [run("first", 1, "a")], turnItems: shown("first") }, selection("a")), + ).toEqual({}); + }); +}); diff --git a/apps/server/src/orchestration-v2/modelSwitch.ts b/apps/server/src/orchestration-v2/modelSwitch.ts new file mode 100644 index 0000000000000..5b893cd0026d2 --- /dev/null +++ b/apps/server/src/orchestration-v2/modelSwitch.ts @@ -0,0 +1,42 @@ +import { + isCompactionCommandMessage, + type ModelSelection, + type OrchestrationV2ThreadProjection, + type OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import { modelSelectionsEqual } from "@t3tools/shared/model"; +import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; + +/** + * The model or effort change a new run brings, measured from the latest run the timeline shows + * through its message or its handoff row, so consecutive dividers always chain. `baseline` stands + * in when there is none, such as a fork's source run. Callers skip starts with a context handoff; + * the handoff item already shows those. + */ +export function modelSwitchSince( + projection: Pick, + to: ModelSelection, + baseline?: ModelSelection, +): Pick, "modelSwitch"> { + // Clients hide pending queued messages, fold async answers into their question, and replace + // `/compact` with a compaction row. + const shown = new Set( + projection.turnItems.flatMap((item) => + item.type === "user_message" && + !(item.inputIntent === "queued_turn" && item.status === "pending") && + !item.messageId.startsWith("async-answer:") && + !isCompactionCommandMessage({ role: "user", ...item }) + ? [item.messageId] + : [], + ), + ); + let previous: OrchestrationV2ThreadProjection["runs"][number] | undefined; + for (const run of projection.runs) { + if (run.status === "rolled_back" || run.status === "queued") continue; + // A wake shows as a notification, but its context handoff row still shows the swap. + if (!shown.has(run.userMessageId) && run.contextHandoffId === null) continue; + if (previous === undefined || runRanAfter(run, previous)) previous = run; + } + const from = previous?.modelSelection ?? baseline; + return from === undefined || modelSelectionsEqual(from, to) ? {} : { modelSwitch: { from, to } }; +} diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index dfda2a18938ee..bf52aad538e18 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -38,6 +38,7 @@ import { } from "lucide-react"; import { Link as LinkIconNode } from "lucide"; import { Button, InlineButton } from "../ui/button"; +import { ModelSwitchRow } from "./V2LifecycleRow"; import { useAssetUrlRefresh, useAssetUrls, useAssetUrlState } from "../../assets/assetUrls"; import { AttachmentImage } from "../media/AttachmentImage"; import { MediaVideoPlayer } from "../media/MediaVideoPlayer"; @@ -246,6 +247,20 @@ function UserVideoAttachment({ } export function UserMessageRow({ row }: { row: Extract }) { + const ctx = use(TimelineRowCtx); + const item = row.projectedItem?.item; + const modelSwitch = item?.type === "user_message" ? item.modelSwitch : undefined; + return ( + <> + {modelSwitch ? ( + + ) : null} + + + ); +} + +function UserMessageContent({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); return ctx.workflowOpening?.messageId === row.message.id ? ( ; } +/** A same-harness model or effort change. Shows only what changed. */ +export function ModelSwitchRow(props: { + readonly environmentId: EnvironmentId; + readonly modelSwitch: OrchestrationV2ModelSwitch; +}) { + const providers = + useAtomValue(serverEnvironment.providersValueAtom(props.environmentId)) ?? + EMPTY_SERVER_PROVIDERS; + const change = resolveModelSwitchChange(props.modelSwitch, providers); + if (change === null) return null; + const describe = (selection: ModelSelection, effort: string | undefined) => { + const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId); + const model = provider?.models.find((candidate) => candidate.slug === selection.model); + const modelName = model ? getTriggerDisplayModelName(model, provider?.driver) : selection.model; + return [change.modelChanged ? modelName : null, effort].filter(Boolean).join(" "); + }; + const { from, to } = props.modelSwitch; + return ( + + ); +} + export function HandoffRow(props: { readonly environmentId: EnvironmentId; readonly endpoints: HandoffEndpoints; diff --git a/packages/client-runtime/src/handoff.test.ts b/packages/client-runtime/src/handoff.test.ts index 508a2f5694d02..d2f5fb4e78903 100644 --- a/packages/client-runtime/src/handoff.test.ts +++ b/packages/client-runtime/src/handoff.test.ts @@ -8,6 +8,7 @@ import { import { describe, expect, it } from "vite-plus/test"; import { resolveHandoffEndpoints, + resolveModelSwitchChange, resolvePendingHandoff, type HandoffTimelineRun, } from "./handoff.ts"; @@ -173,3 +174,99 @@ describe("pending context handoff", () => { ).toBeNull(); }); }); + +describe("model switch change", () => { + const selection = (model: string, options?: Record) => ({ + instanceId: from, + model, + ...(options === undefined + ? {} + : { options: Object.entries(options).map(([id, value]) => ({ id, value })) }), + }); + const providers = [ + { + instanceId: from, + models: ["gpt", "mini"].map((slug) => ({ + slug, + capabilities: { + optionDescriptors: [ + { id: "serviceTier", type: "select", options: [{ id: "fast", label: "Fast" }] }, + { + id: "thought_level", + type: "select", + role: "reasoning", + options: [ + { id: "medium", label: "Medium", isDefault: true }, + { id: "high", label: "High" }, + ], + }, + ], + }, + })), + }, + ] as unknown as ServerProvider[]; + + it("shows only what changed, reading an unset effort as the default", () => { + expect( + resolveModelSwitchChange( + { from: selection("gpt"), to: selection("gpt", { thought_level: "high" }) }, + providers, + ), + ).toEqual({ modelChanged: false, effort: { from: "Medium", to: "High" } }); + expect( + resolveModelSwitchChange({ from: selection("gpt"), to: selection("mini") }, providers), + ).toEqual({ modelChanged: true, effort: null }); + }); + + it("ignores changes the user cannot see", () => { + expect( + resolveModelSwitchChange( + { from: selection("gpt"), to: selection("gpt", { thought_level: "medium" }) }, + providers, + ), + ).toBeNull(); + expect( + resolveModelSwitchChange( + { from: selection("gpt"), to: selection("gpt", { serviceTier: "fast" }) }, + providers, + ), + ).toBeNull(); + // A cataloged model without an effort control ignores stale effort options. + expect( + resolveModelSwitchChange( + { + from: selection("plain", { reasoningEffort: "low" }), + to: selection("plain", { reasoningEffort: "high" }), + }, + [{ instanceId: from, models: [{ slug: "plain" }] }] as unknown as ServerProvider[], + ), + ).toBeNull(); + }); + + it("falls back to stated efforts without a catalog", () => { + expect( + resolveModelSwitchChange( + { + from: selection("gpt", { reasoningEffort: "low" }), + to: selection("gpt", { reasoningEffort: "high" }), + }, + [], + ), + ).toEqual({ modelChanged: false, effort: { from: "low", to: "high" } }); + expect( + resolveModelSwitchChange( + { + from: selection("pi", { thinking: "low" }), + to: selection("pi", { thinking: "high" }), + }, + [], + ), + ).toEqual({ modelChanged: false, effort: { from: "low", to: "high" } }); + expect( + resolveModelSwitchChange( + { from: selection("gpt"), to: selection("gpt", { reasoningEffort: "high" }) }, + [], + ), + ).toBeNull(); + }); +}); diff --git a/packages/client-runtime/src/handoff.ts b/packages/client-runtime/src/handoff.ts index a26c018ad9cdf..c4e7b09595284 100644 --- a/packages/client-runtime/src/handoff.ts +++ b/packages/client-runtime/src/handoff.ts @@ -1,12 +1,20 @@ import type { ModelSelection, + OrchestrationV2ModelSwitch, OrchestrationV2Run, OrchestrationV2TurnItem, ProviderInstanceId, ServerProvider, + ServerProviderModel, } from "@t3tools/contracts"; +import { + getModelSelectionStringOptionValue, + getProviderOptionCurrentValue, +} from "@t3tools/shared/model"; +import { isReasoningSelect } from "./modelTraits.ts"; import type { ThreadStructure } from "./state/models.ts"; +import { REASONING_EFFORT_OPTION_IDS } from "./state/threadExecution.ts"; export type HandoffTimelineRun = Pick< OrchestrationV2Run, @@ -80,3 +88,51 @@ function latestRunModelBefore( } return latest?.modelSelection.model; } + +export interface ModelSwitchChange { + readonly modelChanged: boolean; + /** Effort labels, set only when the effort changed. */ + readonly effort: { readonly from: string; readonly to: string } | null; +} + +/** + * What a recorded model switch visibly changed, or null when it changed neither the model nor the + * effort. The composer omits an untouched effort, so an unset effort reads as the model's default. + */ +export function resolveModelSwitchChange( + { from, to }: OrchestrationV2ModelSwitch, + providers: ReadonlyArray, +): ModelSwitchChange | null { + const modelsOf = (selection: ModelSelection) => + providers.find((provider) => provider.instanceId === selection.instanceId)?.models; + const fromEffort = resolveEffort(from, modelsOf(from)); + const toEffort = resolveEffort(to, modelsOf(to)); + const modelChanged = from.model !== to.model; + const effort = + fromEffort && toEffort && fromEffort.value !== toEffort.value + ? { from: fromEffort.label, to: toEffort.label } + : null; + return modelChanged || effort ? { modelChanged, effort } : null; +} + +/** The composer's reasoning control for the model; stated values only when the catalog lacks it. */ +function resolveEffort( + selection: ModelSelection, + models: ReadonlyArray | undefined, +): { readonly value: string; readonly label: string } | undefined { + const model = models?.find((candidate) => candidate.slug === selection.model); + if (model === undefined) { + // Pi states its effort as `thinking`; the catalog would otherwise mark it a reasoning control. + const value = [...REASONING_EFFORT_OPTION_IDS, "thinking"] + .map((id) => getModelSelectionStringOptionValue(selection, id)) + .find((candidate) => candidate !== undefined); + return value === undefined ? undefined : { value, label: value }; + } + const descriptor = model.capabilities?.optionDescriptors?.find(isReasoningSelect); + if (descriptor === undefined) return undefined; + const value = + getModelSelectionStringOptionValue(selection, descriptor.id) ?? + getProviderOptionCurrentValue(descriptor, selection); + if (typeof value !== "string") return undefined; + return { value, label: descriptor.options.find((option) => option.id === value)?.label ?? value }; +} diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 1c80128f8bbc5..6734e9d55f272 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1480,6 +1480,13 @@ export const OrchestrationV2UserMessageInputIntent = Schema.Literals([ export type OrchestrationV2UserMessageInputIntent = typeof OrchestrationV2UserMessageInputIntent.Type; +/** A same-harness model or effort change that took effect with this message. */ +export const OrchestrationV2ModelSwitch = Schema.Struct({ + from: ModelSelection, + to: ModelSelection, +}); +export type OrchestrationV2ModelSwitch = typeof OrchestrationV2ModelSwitch.Type; + const OrchestrationV2TurnItemBaseFields = { /** Wire-only cursor for collapsed work; persisted items keep their complete history. */ deferredWork: Schema.optionalKey( @@ -1601,6 +1608,7 @@ export const OrchestrationV2TurnItem = Schema.Union([ textOmitted: DedupedBodyMarker, context: Schema.optional(OrchestrationMessageContext), attachments: Schema.Array(ChatAttachment), + modelSwitch: Schema.optional(OrchestrationV2ModelSwitch), }), Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, @@ -2431,6 +2439,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ text: Schema.String, context: Schema.optional(OrchestrationMessageContext), attachments: Schema.Array(ChatAttachment), + modelSwitch: Schema.optional(OrchestrationV2ModelSwitch), }), Schema.Struct({ ...OrchestrationV2TurnItemJsonBaseFields, diff --git a/packages/provider-core/src/server/notification.ts b/packages/provider-core/src/server/notification.ts index 30f6826278c7a..85cac547cfa37 100644 --- a/packages/provider-core/src/server/notification.ts +++ b/packages/provider-core/src/server/notification.ts @@ -217,6 +217,7 @@ export function notificationTurnItem( createdBy: _createdBy, creationSource: _creationSource, scheduledTaskId: _scheduledTaskId, + modelSwitch: _modelSwitch, ...base } = item; return { ...base, type: "notification", ...notification }; From ab8e488e10d883fa880b0ddcf01917b51839ab07 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 1 Nov 2026 22:32:20 -0800 Subject: [PATCH 025/163] feat(antigravity): runtime 1.4.5 with real turn failures and subagent work (#28629) Co-authored-by: Claude Opus 5.5 --- .../features/threads/NativeChildWorkSheet.tsx | 116 +++++ .../features/threads/ProviderSubagentBar.tsx | 13 +- .../features/threads/ThreadDetailScreen.tsx | 8 + apps/server/scripts/acp-mock-agent.ts | 2 +- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + .../Adapters/AcpAdapterV2.test.ts | 157 ++++++ .../Adapters/AntigravityAdapterV2.test.ts | 156 +++++- .../Adapters/AntigravityAdapterV2.ts | 49 +- .../NativeChildWorkQuery.test.ts | 117 +++++ .../orchestration-v2/NativeChildWorkQuery.ts | 116 +++++ .../src/provider/AntigravityProvider.test.ts | 103 +++- .../src/provider/AntigravityProvider.ts | 87 +++- .../src/provider/Drivers/AntigravityDriver.ts | 8 +- .../provider/acp/AcpJsonRpcConnection.test.ts | 14 + .../acp/AntigravityAcpSupport.test.ts | 162 +++++- .../src/provider/acp/AntigravityAcpSupport.ts | 117 ++++- .../provider/acp/AntigravityChildWork.test.ts | 344 +++++++++++++ .../acp/AntigravityChildWork.testkit.ts | 111 ++++ .../src/provider/acp/AntigravityChildWork.ts | 478 ++++++++++++++++++ .../acp/AntigravityEditLocation.test.ts | 245 +++++++++ .../provider/acp/AntigravityEditLocation.ts | 226 +++++++++ .../provider/acp/AntigravityProfilePaths.ts | 37 ++ .../provider/acp/AntigravityProtocol.test.ts | 130 +++++ .../src/provider/acp/AntigravityProtocol.ts | 77 ++- .../acp/AntigravityTurnOutcome.test.ts | 195 +++++++ .../provider/acp/AntigravityTurnOutcome.ts | 194 +++++++ .../server/src/provider/antigravityRelease.ts | 65 +-- apps/server/src/provider/model-manifest.json | 3 +- .../provider/providerCompatibility.test.ts | 30 +- apps/server/src/server.ts | 9 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 4 + apps/web/src/components/ChatView.tsx | 9 + .../components/chat/NativeChildWorkDialog.tsx | 131 +++++ .../components/chat/ProviderSubagentBar.tsx | 3 + docs/user/composer.md | 3 +- docs/user/providers-antigravity.md | 18 +- .../client-runtime/src/state/orchestration.ts | 7 + packages/contracts/src/orchestrationV2.ts | 52 ++ packages/contracts/src/rpc.ts | 11 + .../src/server/AcpSessionRuntime.ts | 22 +- packages/provider-acp/src/server/adapter.ts | 138 ++++- .../src/server/runtimeInstructions.test.ts | 11 + .../src/server/runtimeInstructions.ts | 10 +- 45 files changed, 3650 insertions(+), 142 deletions(-) create mode 100644 apps/mobile/src/features/threads/NativeChildWorkSheet.tsx create mode 100644 apps/server/src/orchestration-v2/NativeChildWorkQuery.test.ts create mode 100644 apps/server/src/orchestration-v2/NativeChildWorkQuery.ts create mode 100644 apps/server/src/provider/acp/AntigravityChildWork.test.ts create mode 100644 apps/server/src/provider/acp/AntigravityChildWork.testkit.ts create mode 100644 apps/server/src/provider/acp/AntigravityChildWork.ts create mode 100644 apps/server/src/provider/acp/AntigravityEditLocation.test.ts create mode 100644 apps/server/src/provider/acp/AntigravityEditLocation.ts create mode 100644 apps/server/src/provider/acp/AntigravityProfilePaths.ts create mode 100644 apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts create mode 100644 apps/server/src/provider/acp/AntigravityTurnOutcome.ts create mode 100644 apps/web/src/components/chat/NativeChildWorkDialog.tsx diff --git a/apps/mobile/src/features/threads/NativeChildWorkSheet.tsx b/apps/mobile/src/features/threads/NativeChildWorkSheet.tsx new file mode 100644 index 0000000000000..1133b866014d0 --- /dev/null +++ b/apps/mobile/src/features/threads/NativeChildWorkSheet.tsx @@ -0,0 +1,116 @@ +import type { + EnvironmentId, + OrchestrationV2GetNativeChildWorkResult, + OrchestrationV2NativeChildWork, + ThreadId, +} from "@t3tools/contracts"; +import { ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { Sheet } from "../../components/ui/Sheet"; +import { orchestrationEnvironment } from "../../state/orchestration"; +import { useEnvironmentQuery } from "../../state/query"; + +const stepLabel = (type: string) => { + const words = type.toLowerCase().replaceAll("_", " "); + return words.charAt(0).toUpperCase() + words.slice(1); +}; + +/** Read-only view of what a provider-native subagent's children did. Mount only while open. */ +export function NativeChildWorkSheet(props: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly onClose: () => void; +}) { + const insets = useSafeAreaInsets(); + const query = useEnvironmentQuery( + orchestrationEnvironment.nativeChildWork({ + environmentId: props.environmentId, + input: { threadId: props.threadId }, + }), + ); + const children = query.data?.children; + return ( + + + + Read only. These subagents cannot take messages. + + {query.error !== null ? ( + + {query.error} + + ) : children === undefined ? ( + Loading… + ) : children.length === 0 ? ( + + The provider has no record of which subagents this call started. + + ) : ( + children.map((child) => ) + )} + + + + + Subagent work + Read only. These subagents cannot take messages. + + {open ? : null} + + + ); +} + +function NativeChildWorkContent(props: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; +}) { + const query = useEnvironmentQuery( + orchestrationEnvironment.nativeChildWork({ + environmentId: props.environmentId, + input: { threadId: props.threadId }, + }), + ); + const children = query.data?.children; + return ( + <> + + {query.error !== null ? ( +

{query.error}

+ ) : children === undefined ? ( +

Loading…

+ ) : children.length === 0 ? ( +

+ The provider has no record of which subagents this call started. +

+ ) : ( + children.map((child) => ) + )} +
+ + + + + ); +} + +function NativeChild(props: { readonly child: OrchestrationV2NativeChildWork }) { + const { child } = props; + return ( +
+

{child.role || "Subagent"}

+

+ {child.prompt} +

+ {child.truncated ? ( +

Earlier steps are not shown.

+ ) : null} + {child.steps === null ? ( +

No transcript yet.

+ ) : ( +
    + {child.steps.map((step) => ( + + ))} +
+ )} +
+ ); +} + +function NativeChildStep(props: { readonly step: OrchestrationV2NativeChildStep }) { + const { step } = props; + return ( +
  • + + {stepLabel(step.type)} + {step.status !== null && step.status !== "DONE" ? ` · ${stepLabel(step.status)}` : ""} + + {step.toolCalls.length === 0 ? null : ( + + {step.toolCalls.map((call) => `${call.name} ${call.input}`).join("\n")} + + )} + {step.text === null ? null : ( +
    +          {step.text}
    +        
    + )} +
  • + ); +} diff --git a/apps/web/src/components/chat/ProviderSubagentBar.tsx b/apps/web/src/components/chat/ProviderSubagentBar.tsx index 6aa8799c70b7e..1b74e43284f23 100644 --- a/apps/web/src/components/chat/ProviderSubagentBar.tsx +++ b/apps/web/src/components/chat/ProviderSubagentBar.tsx @@ -4,6 +4,7 @@ import { } from "@t3tools/client-runtime/state/thread-execution"; import { isOrchestrationV2WorkActive } from "@t3tools/contracts"; import { ArrowUpLeftIcon } from "lucide-react"; +import type { ReactNode } from "react"; import { tickTextContent } from "~/lib/tickTextContent"; import type { ProviderInstanceEntry } from "../../providerInstances"; @@ -17,6 +18,7 @@ export function ProviderSubagentBar(props: { readonly effortLabel: string | null; readonly status: ProviderSubagentStatus | null; readonly onOpenParent: (() => void) | null; + readonly actions?: ReactNode; }) { const { status } = props; const live = status !== null && isOrchestrationV2WorkActive(status.status); @@ -64,6 +66,7 @@ export function ProviderSubagentBar(props: { Runs on its own + {props.actions} {props.onOpenParent ? ( )} - +
    {item.type === "video" ? ( diff --git a/apps/web/src/components/media/MediaActions.tsx b/apps/web/src/components/media/MediaActions.tsx index f45ba1e7abc78..72c003f717a69 100644 --- a/apps/web/src/components/media/MediaActions.tsx +++ b/apps/web/src/components/media/MediaActions.tsx @@ -113,9 +113,11 @@ export function useMediaActions(source: MediaActionSource) { export function MediaActions({ source, children, + showTooltip = true, }: { source: MediaActionSource; children: ReactElement; + showTooltip?: boolean; }) { const { save, copyImage, canReadMedia, assertCanReadMedia } = useMediaActions(source); const [tooltipOpen, setTooltipOpen] = useState(false); @@ -204,7 +206,7 @@ export function MediaActions({ }; return ( - + Date: Mon, 2 Nov 2026 06:14:36 -0800 Subject: [PATCH 032/163] feat(server): log fast and ultrafast service tiers in analytics (#29348) Co-authored-by: Claude Opus 5.5 --- .../telemetry/ProviderUsageAnalytics.test.ts | 29 ++++++++++++++++++- .../src/telemetry/ProviderUsageAnalytics.ts | 22 +++++++++++++- docs/internals/product-analytics.md | 4 ++- 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts index 4e277af4d11a6..bd0a7c7da64b9 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts @@ -77,7 +77,10 @@ const context = ( modelSelection: { instanceId: ProviderInstanceId.make("codex"), model, - options: [{ id: "reasoningEffort", value: "xhigh" }], + options: [ + { id: "reasoningEffort", value: "xhigh" }, + { id: "serviceTier", value: "priority" }, + ], }, runtimeMode: "full-access", interactionMode: "default", @@ -154,6 +157,7 @@ describe("provider usage reporting", () => { lifecycleObserved: true, model: "gpt-6-sol", effort: "xhigh", + serviceTier: "fast", runtimeMode: "full-access", interactionMode: "default", createdBy: "user", @@ -320,4 +324,27 @@ describe("provider usage reporting", () => { } expect(routed("ollama/acme-internal", "secret-variant")).not.toHaveProperty("effort"); }); + + it("reports closed service tiers from a tier option or a fast mode toggle", () => { + const tier = (option: { id: string; value: string | boolean }) => + providerTurnProperties( + { + driver: "codex", + context: { + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-6-sol", + options: [option], + }, + }, + providerTurn: turn("t", complete(1, 1)), + }, + label, + ).serviceTier; + expect(tier({ id: "serviceTier", value: "ultrafast" })).toBe("ultrafast"); + expect(tier({ id: "serviceTier", value: "default" })).toBe("standard"); + expect(tier({ id: "serviceTier", value: "/home/me/secret" })).toBeUndefined(); + expect(tier({ id: "fastMode", value: true })).toBe("fast"); + expect(tier({ id: "fastMode", value: false })).toBe("standard"); + }); }); diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.ts index 96a00d596554d..ce7f29ba1f8d5 100644 --- a/apps/server/src/telemetry/ProviderUsageAnalytics.ts +++ b/apps/server/src/telemetry/ProviderUsageAnalytics.ts @@ -20,7 +20,10 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; +import { + getModelSelectionBooleanOptionValue, + getModelSelectionStringOptionValue, +} from "@t3tools/shared/model"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as AnalyticsService from "./AnalyticsService.ts"; import { catalogModelLabel } from "./ProviderDimensions.ts"; @@ -106,6 +109,22 @@ function selectedEffort(selection: ModelSelection): string | undefined { return effort !== undefined && REPORTED_EFFORTS.has(effort) ? effort : undefined; } +// Codex sends a tier id (its "fast" config shows up as "priority"); Claude has a fastMode toggle. +const REPORTED_SERVICE_TIERS: ReadonlyMap = new Map([ + ["default", "standard"], + ["flex", "flex"], + ["fast", "fast"], + ["priority", "fast"], + ["ultrafast", "ultrafast"], +]); + +function selectedServiceTier(selection: ModelSelection): string | undefined { + const tier = getModelSelectionStringOptionValue(selection, "serviceTier"); + if (tier !== undefined) return REPORTED_SERVICE_TIERS.get(tier); + const fastMode = getModelSelectionBooleanOptionValue(selection, "fastMode"); + return fastMode === undefined ? undefined : fastMode ? "fast" : "standard"; +} + /** * Confirmed models across counted work. Unknown when any piece of work has no * reported model, unless two distinct models were already seen. @@ -130,6 +149,7 @@ function selectionProperties( return defined({ model: selection === undefined ? undefined : label(selection.model), effort: selection === undefined ? undefined : selectedEffort(selection), + serviceTier: selection === undefined ? undefined : selectedServiceTier(selection), runtimeMode: context?.runtimeMode, interactionMode: context?.interactionMode, ...context?.origin, diff --git a/docs/internals/product-analytics.md b/docs/internals/product-analytics.md index 2c6055d811a74..b6dc3f245390a 100644 --- a/docs/internals/product-analytics.md +++ b/docs/internals/product-analytics.md @@ -84,7 +84,9 @@ is unknown or the ledger goes backwards, and background work that ends between turns lands in the next one. Claude subagents have no turns of their own, so this never overlaps child turns. -`model` and `effort` are what the run selected. `observedModel` and +`model`, `effort`, and `serviceTier` are what the run selected. `serviceTier` +is `standard`, `flex`, `fast`, or `ultrafast`, from Codex's tier option or +Claude's fast mode, and is absent when the selection does not set one. `observedModel` and `mixedModels` appear only when the provider reported the models for the counted work (Codex thread settings and reroutes, Claude root messages, OpenCode steps). `mixedModels: false` without `reportVersion` was never checked. Model labels From ac8dce0cc3abd8a337f2d806b5082a6834b9b81a Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 2 Nov 2026 06:38:34 -0800 Subject: [PATCH 033/163] fix(marketing): show 40k+ GitHub stars (#29362) Co-authored-by: Claude Opus 5.5 --- apps/marketing/src/lib/site.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/marketing/src/lib/site.ts b/apps/marketing/src/lib/site.ts index 5cd1337d141f4..8b42f400512e9 100644 --- a/apps/marketing/src/lib/site.ts +++ b/apps/marketing/src/lib/site.ts @@ -7,6 +7,6 @@ export const ANDROID_PLAY_STORE_URL = "https://play.google.com/store/apps/details?id=com.t3tools.t3code"; export const MARKETING_STATS = { - githubStars: "31k+", + githubStars: "40k+", users: "500,000", } as const; From edc37c96c810d42761ab510c6a3e9d0a741547dc Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 2 Nov 2026 10:06:31 -0600 Subject: [PATCH 034/163] fix(web): center authorized client settings rows (#29382) --- .../components/settings/AuthorizedClientsSettings.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx index c63c163592c6f..61fa056cff67b 100644 --- a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx +++ b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx @@ -876,8 +876,8 @@ export const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow {isDefault ? ( ) : null} -
    -
    +
    +

    {endpoint.label}

    @@ -894,14 +894,14 @@ export const AdvertisedEndpointListRow = memo(function AdvertisedEndpointListRow ) : null} {!isAvailable ? ( - + Setup required ) : null}
    -
    +
    {isDefault ? ( - + Default ) : null} From 5e966bc04aa54782f57f81b08386d0e192f64eca Mon Sep 17 00:00:00 2001 From: Nick Anisimov Date: Mon, 2 Nov 2026 20:33:09 +0400 Subject: [PATCH 035/163] fix(mobile): keep One UI navigation and Compose on one row (#29203) --- .../ScrollComposeButton.android.tsx | 4 ++- .../features/home/AndroidHomeFab.android.tsx | 31 +++++++++---------- .../features/home/AndroidHomeFab.shared.tsx | 1 - .../layout/AdaptiveWorkspaceLayout.tsx | 1 - .../threads/ThreadNavigationSidebar.tsx | 11 ++----- .../AndroidWorkspaceNavigation.android.tsx | 4 +-- .../AndroidWorkspaceSidebar.android.tsx | 7 ++--- .../workspace/WorkspaceRootScreen.android.tsx | 16 +++------- .../workspace/floating-workspace-tabs.test.ts | 31 +++++++++---------- .../workspace/floating-workspace-tabs.ts | 20 +++++------- 10 files changed, 52 insertions(+), 74 deletions(-) diff --git a/apps/mobile/src/components/ScrollComposeButton.android.tsx b/apps/mobile/src/components/ScrollComposeButton.android.tsx index d107d9be5d8a0..13aeb462bdf5f 100644 --- a/apps/mobile/src/components/ScrollComposeButton.android.tsx +++ b/apps/mobile/src/components/ScrollComposeButton.android.tsx @@ -17,12 +17,14 @@ import { resolveScaledTextRole } from "../lib/appearancePreferences"; export function ScrollComposeButton(props: { readonly expanded: boolean; readonly onPress: () => void; + readonly size?: number; readonly className?: string; readonly style?: StyleProp; }) { const { appearance, themeVariables: colors } = useAppearancePreferences(); const typography = resolveScaledTextRole("footnote", appearance.baseFontSize); - const { iconSize, fabSize } = useAndroidControlSizing(); + const { iconSize, fabSize: scaledFabSize } = useAndroidControlSizing(); + const fabSize = props.size ?? scaledFabSize; const nativeSize = Math.max(56, fabSize); const scale = fabSize / nativeSize; const nativeIconSize = Math.round(iconSize / scale); diff --git a/apps/mobile/src/features/home/AndroidHomeFab.android.tsx b/apps/mobile/src/features/home/AndroidHomeFab.android.tsx index 1a54ed4ad46c3..bc1fe6af518a2 100644 --- a/apps/mobile/src/features/home/AndroidHomeFab.android.tsx +++ b/apps/mobile/src/features/home/AndroidHomeFab.android.tsx @@ -6,7 +6,7 @@ import { type NativeSyntheticEvent, } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; -import { NewThreadButton } from "../../components/NewThreadButton"; +import { ScrollComposeButton } from "../../components/ScrollComposeButton.android"; import { androidHomeFabPosition, type AndroidHomeFabLayout as SharedAndroidHomeFabLayout, @@ -15,9 +15,9 @@ import { useWorkspaceState } from "../../state/workspace"; import { FabScrollContext } from "./FabScrollContext"; import { updateFabScroll } from "./fab-scroll"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; -import { useEnabledNavigationTabs } from "../workspace/navigation-tabs"; import { WorkspaceTabsContext, useWorkspaceTabs } from "../workspace/WorkspaceTabsContext"; import { FLOATING_TABS, floatingTabsMetrics } from "../workspace/floating-workspace-tabs"; +import { useEnabledNavigationTabs } from "../workspace/navigation-tabs"; import { useAppearancePreferences, useAndroidFloatingTabs, @@ -32,19 +32,16 @@ export function AndroidHomeFabLayout(props: ComponentProps) => { @@ -69,9 +66,9 @@ export function AndroidHomeFabLayout(props: ComponentProps{props.children}; } diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx index 517d3ddf2981b..137608d6ffd2b 100644 --- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -935,7 +935,6 @@ function AdaptiveWorkspaceLayoutContent( ; diff --git a/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx b/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx index 1fa6a87bf596a..a5849398a843d 100644 --- a/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx +++ b/apps/mobile/src/features/workspace/WorkspaceRootScreen.android.tsx @@ -3,7 +3,7 @@ import { WorkspaceNoTabs } from "./WorkspaceNoTabs"; import { useEnabledNavigationTabs } from "./navigation-tabs"; import { NAVIGATION_TAB_ORDER } from "./navigation-tab-order"; import { WorkspaceExtraTab } from "./WorkspaceExtraTab"; -import { useWindowDimensions, View } from "react-native"; +import { View } from "react-native"; import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context"; import { NativeStackScreenOptions } from "../../native/StackHeader"; import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader"; @@ -15,7 +15,7 @@ import { PullRequestsScreen } from "../pull-requests/PullRequestsScreen"; import { PullRequestToolbar } from "../pull-requests/PullRequestToolbar.android"; import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; import { AndroidWorkspaceNavigation, FloatingWorkspaceTabs } from "./AndroidWorkspaceNavigation"; -import { FLOATING_TABS, floatingTabsMetrics } from "./floating-workspace-tabs"; +import { FLOATING_TABS } from "./floating-workspace-tabs"; import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext"; import { WorkspaceTabPanes } from "./WorkspaceTabPanes"; import type { WorkspaceTab } from "./workspace-tabs-state"; @@ -28,21 +28,13 @@ export function WorkspaceRootScreen() { const workspace = useWorkspaceTabs()!; const enabled = useEnabledNavigationTabs(); const insets = useSafeAreaInsets(); - const { fabClearance, scale, fabSize } = useAndroidControlSizing(); - const window = useWindowDimensions(); - const floating = floatingTabsMetrics(enabled.length + 1, scale, fabSize, window.width); + const { fabClearance, fabSize } = useAndroidControlSizing(); const context = { ...workspace, bottomClearance: layout.usesSplitView ? workspace.bottomClearance : floatingTabsEnabled - ? insets.bottom + - FLOATING_TABS.bottom + - FLOATING_TABS.edge + - Math.max( - floating.height, - workspace.state.selectedTab === "threads" ? floating.fabOffset + fabSize : 0, - ) + ? insets.bottom + FLOATING_TABS.bottom + FLOATING_TABS.edge + fabSize : workspace.state.selectedTab === "threads" ? fabClearance + 16 : 16, diff --git a/apps/mobile/src/features/workspace/floating-workspace-tabs.test.ts b/apps/mobile/src/features/workspace/floating-workspace-tabs.test.ts index dd4aadb11605d..59dc131b1c870 100644 --- a/apps/mobile/src/features/workspace/floating-workspace-tabs.test.ts +++ b/apps/mobile/src/features/workspace/floating-workspace-tabs.test.ts @@ -20,22 +20,21 @@ it.each([ ); it.each([ - [475, 1, 56], - [411, 1, 56], - [475, 1.25, 70], + [475, 1, 56, 4, 56], + [411, 1, 56, 4, 56], + [475, 1.25, 70, 4, 70], + [320, 11 / 16, 48, 4, 48], + [320, 1, 56, 4, 55.2], + [320, 22 / 16, 77, 4, 55.2], + [300, 22 / 16, 77, 4, 51.2], + [411, 22 / 16, 77, 4, 73.4], + [320, 22 / 16, 77, 2, 77], ] as const)( - "fills a %sdp cover row at scale %s with a %sdp compose button", - (width, scale, fabSize) => { - const metrics = floatingTabsMetrics(4, scale, fabSize, width, true); - expect(metrics.sharesRow).toBe(true); - expect(metrics.pill + 2 * 16 + 12 + fabSize).toBe(width); - expect(metrics.height).toBe(fabSize); + "fills a %sdp row at scale %s beside a %sdp compose button", + (width, scale, fabSize, count, height) => { + const metrics = floatingTabsMetrics(count, scale, fabSize, width, true); + expect(metrics.pill + 2 * 16 + 12 + metrics.height).toBeCloseTo(width); + expect(metrics.height).toBeCloseTo(height); + expect(metrics.pill / count).toBeGreaterThanOrEqual(metrics.height - 0.001); }, ); - -it("stacks compose above a full-width pill when a cover row is too narrow", () => { - const metrics = floatingTabsMetrics(4, 1, 56, 300, true); - expect(metrics.sharesRow).toBe(false); - expect(metrics.pill).toBe(268); - expect(metrics.fabOffset).toBe(68); -}); diff --git a/apps/mobile/src/features/workspace/floating-workspace-tabs.ts b/apps/mobile/src/features/workspace/floating-workspace-tabs.ts index bb24d3478fdf2..6612dcace29f0 100644 --- a/apps/mobile/src/features/workspace/floating-workspace-tabs.ts +++ b/apps/mobile/src/features/workspace/floating-workspace-tabs.ts @@ -9,22 +9,18 @@ export function floatingTabsMetrics( fillWidth = false, ) { const unit = Math.max(1, scale); - const height = fabSize; - const beside = 2 * FLOATING_TABS.edge + FLOATING_TABS.gap + fabSize; - const row = beside + count * 60 * unit; - const sharesRow = paneWidth === undefined || paneWidth >= row; - const room = + const spacing = 2 * FLOATING_TABS.edge + FLOATING_TABS.gap; + // Share width evenly when space is tight, retaining Android's 48dp touch target. + const height = paneWidth === undefined - ? count * 60 * unit - : sharesRow - ? paneWidth - beside - : paneWidth - 2 * FLOATING_TABS.edge; + ? fabSize + : Math.max(48, Math.min(fabSize, (paneWidth - spacing) / (count + 1))); + const beside = spacing + height; + const room = paneWidth === undefined ? count * 60 * unit : paneWidth - beside; return { // Reserve the compose slot even while its button is hidden. pill: Math.max(0, fillWidth ? room : Math.min(count * 72 * unit, room)), height, - row, - sharesRow, - fabOffset: sharesRow ? (height - fabSize) / 2 : height + FLOATING_TABS.gap, + row: beside + count * 60 * unit, }; } From d833184115ec823825c2cc6f612443cd3a1c1b2c Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 2 Nov 2026 10:35:10 -0600 Subject: [PATCH 036/163] perf(server): bound runtime recovery reads by thread ownership (#29429) --- .../ProjectionRecovery.test.ts | 146 ++++++++++++++++++ .../src/orchestration-v2/ProjectionStore.ts | 26 ++-- 2 files changed, 160 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts index 4df71fd5a9d63..f1169f1e910b4 100644 --- a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts @@ -22,6 +22,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as SqlClient from "effect/sql/SqlClient"; +import * as Statement from "effect/sql/Statement"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -657,6 +658,151 @@ it.effect("includes shared sessions and provider-owned background rosters in rec }).pipe(Effect.provide(layerTest)), ); +it.effect("bounds runtime provider-thread reads by ownership and preserves recovery liveness", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const sql = yield* SqlClient.SqlClient; + const now = yield* DateTime.now; + const threadId = yield* createThread("ownership"); + const other = yield* createThread("other-owner"); + const ownerNodeId = NodeId.make("node:recovery:owner"); + yield* projections.apply({ + id: EventId.make("event:recovery:owner"), + type: "node.updated", + threadId, + nodeId: ownerNodeId, + driver, + occurredAt: now, + payload: { + id: ownerNodeId, + threadId, + runId: null, + parentNodeId: null, + rootNodeId: ownerNodeId, + kind: "root_turn", + status: "completed", + countsForRun: false, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: now, + completedAt: now, + }, + }); + const cases = [ + { name: "direct", ownership: "direct", status: "active", ordinal: 2, included: true }, + { name: "owner", ownership: "owner", status: "active", ordinal: null, included: true }, + { name: "owner-only", ownership: "owner", status: "active", ordinal: 1, included: true }, + { name: "subagent", ownership: "subagent", status: "active", ordinal: 1, included: true }, + { name: "duplicate", ownership: "all", status: "active", ordinal: 1, included: true }, + { name: "roster", ownership: "direct", status: "idle", ordinal: 3, included: true }, + { name: "run", ownership: "owner", status: "idle", ordinal: 4, included: true }, + { name: "item", ownership: "subagent", status: "idle", ordinal: 5, included: true }, + { name: "waiting-run", ownership: "direct", status: "idle", ordinal: 6, included: true }, + { name: "settled", ownership: "all", status: "idle", ordinal: 7, included: false }, + { name: "unrelated", ownership: "none", status: "active", ordinal: 8, included: false }, + { name: "unrelated-run", ownership: "none", status: "idle", ordinal: 9, included: false }, + ] as const; + for (const entry of cases) { + const id = ProviderThreadId.make(`provider-thread:ownership:${entry.name}`); + yield* projections.apply({ + id: EventId.make(`event:${id}`), + type: "provider-thread.updated", + threadId, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id, + appThreadId: + entry.name === "owner-only" + ? null + : entry.ownership === "direct" || entry.ownership === "all" + ? threadId + : other, + ownerNodeId: + entry.ownership === "owner" || entry.ownership === "all" ? ownerNodeId : null, + driver, + providerInstanceId, + providerSessionId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: entry.status, + firstRunOrdinal: entry.ordinal, + lastRunOrdinal: entry.ordinal, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + pendingBackgroundTasks: + entry.name === "roster" + ? [{ taskId: "shell", description: "background", kind: "command" }] + : [], + }, + }); + if (entry.ownership === "subagent" || entry.ownership === "all") { + for (const suffix of ["a", "b"]) { + yield* sql` + INSERT INTO orchestration_v2_projection_subagents + (subagent_id, thread_id, parent_node_id, provider, provider_thread_id, + origin, status, updated_at, payload_json) + VALUES (${`${id}:${suffix}`}, ${threadId}, ${ownerNodeId}, 'codex', ${id}, + 'provider_native', 'completed', '', '{}') + `; + } + } + if (entry.name === "run" || entry.name === "unrelated-run") { + yield* createRun(threadId, "waiting", { ordinal: entry.ordinal, providerThreadId: id }); + } + } + const waitingProviderThreadId = ProviderThreadId.make("provider-thread:ownership:waiting-run"); + const waitingRunId = yield* createRun(threadId, "completed", { + ordinal: 6, + providerThreadId: waitingProviderThreadId, + }); + yield* sql` + INSERT INTO orchestration_v2_projection_turn_items + (turn_item_id, thread_id, run_id, node_id, provider_thread_id, ordinal, type, + status, updated_at, payload_json) + VALUES ('item:ownership', ${threadId}, ${waitingRunId}, ${ownerNodeId}, + ${ProviderThreadId.make("provider-thread:ownership:item")}, 1, 'assistant_message', 'waiting', '', '{}') + `; + const statements: Array["compile"]>> = []; + const observe: Statement.Transformer = (statement) => { + const compiled = statement.compile(); + if (compiled[0].includes("SELECT provider_thread.payload_json")) statements.push(compiled); + return Effect.succeed(statement); + }; + const projection = yield* projections + .getRuntimeRecoveryProjection(threadId) + .pipe(Effect.provideService(Statement.CurrentTransformer, observe)); + assert.deepEqual( + projection.providerThreads.map((row) => row.id), + cases + .filter((entry) => entry.included) + .toSorted((a, b) => (a.ordinal ?? 0) - (b.ordinal ?? 0) || a.name.localeCompare(b.name)) + .map((entry) => ProviderThreadId.make(`provider-thread:ownership:${entry.name}`)), + ); + assert.equal(statements.length, 1); + const [query, params] = statements[0]!; + const plan = yield* sql.unsafe<{ detail: string }>(`EXPLAIN QUERY PLAN ${query}`, params); + assert.isFalse( + plan.some((row) => /^SCAN provider_thread(?:$| )/.test(row.detail)), + JSON.stringify(plan), + ); + assert.isTrue( + plan.some((row) => row.detail.includes("provider_threads_owner_idx")), + JSON.stringify(plan), + ); + assert.isFalse( + plan.some((row) => /SEARCH (owner|n) USING INDEX .*nodes_thread/.test(row.detail)), + JSON.stringify(plan), + ); + }).pipe(Effect.provide(layerTest)), +); + it.effect("reads the run that owns a background roster, not a queued or resumed one", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 451a917770ec4..90a9582cb647b 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -4586,18 +4586,20 @@ export const layer: Layer.Layer = sql` SELECT provider_thread.payload_json FROM orchestration_v2_projection_provider_threads AS provider_thread - WHERE ( - provider_thread.thread_id = ${threadId} - OR EXISTS ( - SELECT 1 FROM orchestration_v2_projection_nodes AS owner - WHERE owner.node_id = provider_thread.owner_node_id - AND owner.thread_id = ${threadId} - ) - OR EXISTS ( - SELECT 1 FROM orchestration_v2_projection_subagents AS subagent - WHERE subagent.provider_thread_id = provider_thread.provider_thread_id - AND subagent.thread_id = ${threadId} - ) + WHERE provider_thread.provider_thread_id IN ( + SELECT provider_thread_id FROM orchestration_v2_projection_provider_threads + WHERE thread_id = ${threadId} + UNION + -- Start with non-null owners; a thread can have a large settled node history. + SELECT owned.provider_thread_id + FROM orchestration_v2_projection_provider_threads AS owned + INDEXED BY orchestration_v2_projection_provider_threads_owner_idx + CROSS JOIN orchestration_v2_projection_nodes AS owner + ON owner.node_id = owned.owner_node_id + WHERE owned.owner_node_id IS NOT NULL AND owner.thread_id = ${threadId} + UNION + SELECT provider_thread_id FROM orchestration_v2_projection_subagents + WHERE thread_id = ${threadId} AND provider_thread_id IS NOT NULL ) AND ( provider_thread.status = 'active' From 7cf653bca60d186e977c0809ed18be20f1076666 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 2 Nov 2026 10:39:50 -0600 Subject: [PATCH 037/163] perf(server): narrow delegated recovery reads to delivery records (#29435) --- .../DelegatedCompletionDelivery.test.ts | 71 ++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 45 ++++++--- .../orchestration-v2/ProjectionStore.test.ts | 92 +++++++++++++++++++ .../src/orchestration-v2/ProjectionStore.ts | 14 ++- 4 files changed, 204 insertions(+), 18 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 87f6bbd1a6745..900dc1508770e 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -25,6 +25,7 @@ import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Stream from "effect/Stream"; +import * as Tracer from "effect/Tracer"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; import * as ServerConfig from "../config.ts"; @@ -1346,6 +1347,76 @@ const seedRestartCancelledChild = (input: { it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( "subagent follow-ups", (it) => { + it.effect("recovers a reserved delivery without loading conversation history", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:bounded-delivery-recovery"); + const runId = RunId.make("run:bounded-delivery-recovery"); + const taskId = NodeId.make("task:bounded-delivery-recovery"); + yield* seedParentWithTerminalTask({ + threadId, + runId, + taskId, + projectId: ProjectId.make("project:bounded-delivery-recovery"), + rootNodeId: NodeId.make("node:bounded-delivery-recovery"), + deliveryState: "claimed", + deliveryTaskIds: [taskId], + completionWake: "always", + now, + }); + for (const suffix of ["first", "second"]) { + yield* sink.write({ + events: [ + { + id: EventId.make(`event:bounded-delivery-history:${suffix}`), + type: "message.updated", + threadId, + occurredAt: now, + payload: { + id: MessageId.make(`message:bounded-delivery-history:${suffix}`), + threadId, + runId: null, + nodeId: null, + createdBy: "user", + creationSource: "web", + role: "user", + text: "Unrelated historical input", + attachments: [], + streaming: false, + createdAt: now, + updatedAt: now, + }, + }, + ], + }); + } + const statements: string[] = []; + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (time, exit) => { + end(time, exit); + const query = span.attributes.get("db.query.text"); + if (typeof query === "string") statements.push(query); + }; + return span; + }, + }); + yield* orchestrator.recoverDelegatedTasks.pipe(Effect.withTracer(tracer)); + assert.isFalse(statements.some((query) => query.includes("MIN(ordinal)"))); + const messageReads = statements.filter((query) => + query.includes("FROM orchestration_v2_projection_messages"), + ); + assert.isNotEmpty(messageReads); + assert.isTrue(messageReads.every((query) => query.includes("message_id IN"))); + const wake = yield* requests.take; + assert.equal(wake.delegatedCompletion?.parentRunId, runId); + }), + ); it.effect("keeps a checkpoint completion committed between finalize's read and write", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 75df815127f39..0df010b690829 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1346,27 +1346,40 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const offerDelegatedCompletionDelivery = /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ Effect.fnUntraced(function* (threadId: ThreadId, parentRunId: RunId) { - const projection = yield* projectionStore.getThreadRecords( - threadId, - ["runs", "messages", "providerTurns", "providerThreads"], - { messageRoles: ["user"] }, - ); - const parentRun = projection.runs.find((candidate) => candidate.id === parentRunId); + const controls = yield* projectionStore.getThreadRecords(threadId, ["runs"], { + runIds: [parentRunId], + }); + const parentRun = controls.runs[0]; const cohort = parentRun?.delegatedCompletion; const delivery = cohort?.delivery; if ( parentRun === undefined || cohort?.disposition !== "open" || - delivery === null || - delivery === undefined || + delivery == null || delivery.taskIds.length === 0 || - projection.thread.archivedAt !== null || - projection.thread.deletedAt !== null || - (completionDeliveryMessage(projection, delivery) !== undefined && - !isUndeliveredMailboxSteer(projection, delivery.messageId)) - ) { + controls.thread.archivedAt !== null || + controls.thread.deletedAt !== null + ) return; + const messages = yield* projectionStore.getThreadRecords(threadId, ["messages"], { + messageIds: [delivery.messageId], + }); + const message = messages.messages[0]; + if (message !== undefined) { + if (message.delegatedCompletion === undefined || message.runId === null) return; + const runs = yield* projectionStore.getThreadRecords(threadId, ["runs"], { + runIds: [message.runId], + }); + const run = runs.runs[0]; + const turns = yield* projectionStore.getThreadRecords(threadId, ["providerTurns"], { + providerTurnAttemptIds: run?.activeAttemptId == null ? [] : [run.activeAttemptId], + }); + if (!isUndeliveredMailboxSteer({ ...messages, ...runs, ...turns }, delivery.messageId)) + return; } + const projection = yield* projectionStore.getThreadRecords(threadId, ["providerThreads"], { + providerThreadIds: parentRun.providerThreadId === null ? [] : [parentRun.providerThreadId], + }); const providerThread = parentRun.providerThreadId === null ? undefined @@ -12708,7 +12721,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const projection = yield* projectionStore.getThreadRecords( threadId, ["runs", "messages", "subagents"], - { messageRoles: ["user"] }, + { + runIds: [runId, message.delegatedCompletion.parentRunId], + messageIds: [message.id], + subagentRunIds: [message.delegatedCompletion.parentRunId], + }, ); const deliveryRun = projection.runs.find((candidate) => candidate.id === runId); const deliveryMessage = diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index aadd9ecc8be06..4b72c9610c5ed 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -215,6 +215,98 @@ const addRolledBackRecoveryCandidate = Effect.fn("addRolledBackRecoveryCandidate return threadId; }); +it.effect("record reads restrict provider histories to delivery identities", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = yield* addRolledBackRecoveryCandidate("delivery-identities"); + const sql = yield* SqlClient.SqlClient; + const now = yield* DateTime.now; + for (const suffix of ["selected", "history"]) { + const id = ProviderThreadId.make(`provider-thread:${suffix}`); + yield* store.apply({ + id: EventId.make(`event:delivery-identities:${suffix}`), + type: "provider-thread.updated", + threadId, + occurredAt: now, + payload: { + id, + appThreadId: threadId, + driver, + providerInstanceId, + providerSessionId: null, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + status: "active", + firstRunOrdinal: 1, + createdAt: now, + updatedAt: now, + }, + }); + } + for (const [suffix, attempt] of [ + ["selected", "current"], + ["history", "old"], + ["runless", null], + ] as const) { + yield* store.apply({ + id: EventId.make(`event:delivery-turn:${suffix}`), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { + id: ProviderTurnId.make(`turn:${suffix}`), + providerThreadId: ProviderThreadId.make("provider-thread:selected"), + nodeId: NodeId.make("node:delivery"), + runAttemptId: attempt === null ? null : RunAttemptId.make(attempt), + nativeTurnRef: null, + ordinal: suffix === "selected" ? 1 : suffix === "history" ? 2 : 3, + status: "completed", + startedAt: now, + completedAt: now, + }, + }); + } + assert.deepEqual( + (yield* store.getThreadRecords(threadId, ["providerTurns"], { + providerTurnAttemptIds: [RunAttemptId.make("current")], + })).providerTurns.map((turn) => turn.id), + ["turn:selected"], + ); + assert.deepEqual( + (yield* store.getThreadRecords(threadId, ["providerTurns"], { + providerTurnAttemptIds: [], + })).providerTurns, + [], + ); + const selected = yield* store.getThreadRecords(threadId, ["providerThreads"], { + providerThreadIds: [ProviderThreadId.make("provider-thread:selected")], + }); + assert.deepEqual( + selected.providerThreads.map((row) => row.id), + ["provider-thread:selected"], + ); + assert.deepEqual( + (yield* store.getThreadRecords(threadId, ["providerThreads"], { + providerThreadIds: [], + })).providerThreads, + [], + ); + // Unselected history must not be decoded, even if its payload is unreadable. + yield* sql`UPDATE orchestration_v2_projection_provider_threads SET payload_json = '{}' + WHERE provider_thread_id = 'provider-thread:history'`; + assert.lengthOf( + (yield* store.getThreadRecords(threadId, ["providerThreads"], { + providerThreadIds: [ProviderThreadId.make("provider-thread:selected")], + })).providerThreads, + 1, + ); + }).pipe(Effect.provide(layerTest)), +); + it.effect("record reads filter notification sources without dropping matching message bodies", () => Effect.gen(function* () { const store = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 90a9582cb647b..b214349d90f82 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -329,6 +329,8 @@ export interface ProjectionRuntimeResponseContext { } export interface ProjectionRecordFilter { + readonly providerThreadIds?: ReadonlyArray; + readonly providerTurnAttemptIds?: ReadonlyArray; readonly messageRoles?: ReadonlyArray; readonly monitorNotificationsOnly?: boolean; readonly turnItemRunId?: RunId; @@ -3387,13 +3389,14 @@ export const layer: Layer.Layer = OR threads.provider_thread_id IN (SELECT value FROM json_each(${cohortProviderThreadIds}))) ORDER BY sessions.updated_at ASC, sessions.provider_session_id ASC `, - fields !== undefined && !fields.includes("providerThreads") + (fields !== undefined && !fields.includes("providerThreads")) || + (window === undefined && matchesNothing(filter?.providerThreadIds)) ? Effect.succeed([]) : window === undefined ? sql` SELECT payload_json FROM orchestration_v2_projection_provider_threads - WHERE thread_id = ${threadId} + WHERE (thread_id = ${threadId} OR owner_node_id IN ( SELECT node_id FROM orchestration_v2_projection_nodes @@ -3404,7 +3407,8 @@ export const layer: Layer.Layer = FROM orchestration_v2_projection_subagents WHERE thread_id = ${threadId} AND provider_thread_id IS NOT NULL - ) + )) + ${filter?.providerThreadIds === undefined ? sql`` : sql`AND provider_thread_id IN (SELECT value FROM json_each(${encodeIdList(filter.providerThreadIds)}))`} ORDER BY COALESCE(first_run_ordinal, 0), provider_thread_id ASC ` : sql` @@ -3416,13 +3420,15 @@ export const layer: Layer.Layer = AND provider_thread_id = ${latestTodoList?.provider_thread_id ?? null}) ORDER BY COALESCE(first_run_ordinal, 0), provider_thread_id ASC `, - fields !== undefined && !fields.includes("providerTurns") + (fields !== undefined && !fields.includes("providerTurns")) || + (window === undefined && matchesNothing(filter?.providerTurnAttemptIds)) ? Effect.succeed([]) : window === undefined ? sql` SELECT payload_json FROM orchestration_v2_projection_provider_turns WHERE thread_id = ${threadId} + ${filter?.providerTurnAttemptIds === undefined ? sql`` : sql`AND run_attempt_id IN (SELECT value FROM json_each(${encodeIdList(filter.providerTurnAttemptIds)}))`} ORDER BY provider_thread_id ASC, ordinal ASC ` : sql` From c8a601c0dfa5c7626e51e06d727076f6b840a005 Mon Sep 17 00:00:00 2001 From: Dara Adedeji <76637177+SunkenInTime@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:41:43 -0500 Subject: [PATCH 038/163] fix(cursor): /compact compacts with the SDK's summarize (#29398) Co-authored-by: Gabriel Rodrigues Co-authored-by: Cursor Co-authored-by: maria-rcks --- apps/server/package.json | 2 +- .../orchestrator-mcp-server.md | 7 ++- docs/user/cursor.md | 13 ++++- packages/provider-cursor/package.json | 2 +- .../src/server/CursorAgentSdk.ts | 29 ++++++---- .../src/server/adapter.test.ts | 26 ++++----- .../provider-cursor/src/server/adapter.ts | 8 ++- pnpm-lock.yaml | 54 +++++++++---------- pnpm-workspace.yaml | 6 +++ 9 files changed, 90 insertions(+), 57 deletions(-) diff --git a/apps/server/package.json b/apps/server/package.json index 5d6c7e8d46058..e6a572c8818b4 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -34,7 +34,7 @@ }, "dependencies": { "@anthropic-ai/claude-agent-sdk": "^0.3.276", - "@cursor/sdk": "1.0.38", + "@cursor/sdk": "1.2.0", "@effect/platform-node": "catalog:", "@effect/platform-node-shared": "catalog:", "@ff-labs/fff-node": "0.11.0", diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 11e7bd9a8d06e..1a23cf0246fb0 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -99,8 +99,11 @@ server headers or token. ### Cursor Agent SDK V2 Cursor receives the same authenticated HTTP MCP endpoint through the SDK's -`mcpServers` agent and send options. The adapter passes the authorization header -to the SDK but projects only redacted option metadata into protocol diagnostics. +`mcpServers` on `Agent.create` / `Agent.resume` and each `send`. With +`@cursor/sdk` 1.0.39+, send-level servers replace only the create-time inline +set; ambient servers from `settingSources` (`project`, `user`, `team`, `mdm`, +`plugins`) stay available. The adapter passes the authorization header to the +SDK but projects only redacted option metadata into protocol diagnostics. ### Grok ACP V2 diff --git a/docs/user/cursor.md b/docs/user/cursor.md index 6a6b1c8f284b3..4263ceb14fd8d 100644 --- a/docs/user/cursor.md +++ b/docs/user/cursor.md @@ -15,6 +15,17 @@ The adapter currently uses the SDK's local-agent runtime so runs operate in the workspace. Cursor cloud agents need repository and cloud-environment configuration that T3 Code does not expose yet. +Custom Cursor MCP servers and plugins are not configured in T3 Code. They load from the environment +machine's Cursor config when the agent opens: project `.cursor/mcp.json`, user `~/.cursor/mcp.json`, +and installed plugins under `~/.cursor/plugins`. Plugin tools +can appear without a login; OAuth MCP servers still need credentials. Run `agent mcp login ` +with the cwd set to the T3 project root (tokens land in +`~/.cursor/projects//mcp-auth.json`). Cursor desktop Connections auth does not write +that file, and the local SDK cannot complete interactive MCP OAuth itself—auth attempts fail with +messages such as "MCP authentication is not supported in local SDK runs" or that the auth server +does not support dynamic client registration. After you add or change skills, plugins, or MCP +servers, or after a successful CLI login, use **Restart agent session**. + ## Sign in Choose **Sign in**, then open the sign-in page and complete it in your browser. T3 Code @@ -36,7 +47,7 @@ The adapter supports: - creating and resuming local Cursor agent threads; - changing the model and model parameters between turns; - assistant text, reasoning, tool activity, plans, and todo streaming; -- thread-scoped T3 Code MCP tools; +- thread-scoped T3 Code MCP tools alongside ambient Cursor MCP/plugins from disk; - image attachments; - interruption, queued app messages, and orchestrator-owned interrupt/restart steering; - provider conversation snapshots through `Agent.messages.list()`; diff --git a/packages/provider-cursor/package.json b/packages/provider-cursor/package.json index b619c3b61fdb4..90122cbe57e66 100644 --- a/packages/provider-cursor/package.json +++ b/packages/provider-cursor/package.json @@ -49,7 +49,7 @@ "test": "vp test run --config ../../vite.config.ts --dir ." }, "dependencies": { - "@cursor/sdk": "1.0.38", + "@cursor/sdk": "1.2.0", "@napi-rs/keyring": "^1.3.0", "@t3tools/contracts": "workspace:*", "@t3tools/provider-core": "workspace:*", diff --git a/packages/provider-cursor/src/server/CursorAgentSdk.ts b/packages/provider-cursor/src/server/CursorAgentSdk.ts index 791121a7140ec..f48d7baf1b24a 100644 --- a/packages/provider-cursor/src/server/CursorAgentSdk.ts +++ b/packages/provider-cursor/src/server/CursorAgentSdk.ts @@ -89,6 +89,8 @@ export interface CursorAgentSdkSendInput { readonly message: string | SDKUserMessage; readonly options?: Omit; readonly onDelta?: (update: InteractionUpdate) => Effect.Effect; + /** Runs `agent.summarize()` instead, which takes no message or options. */ + readonly summarize?: boolean; } export interface CursorAgentSdkRun { @@ -139,6 +141,8 @@ export interface CursorAgentSdkLoggedAgentOptions { export interface CursorAgentSdkLoggedSendOptions { readonly model?: SendOptions["model"]; readonly mode?: SendOptions["mode"]; + readonly hasMcpServers?: boolean; + readonly mcpServerNames?: ReadonlyArray; readonly local?: { readonly force?: boolean; readonly hasCustomTools?: boolean; @@ -298,9 +302,12 @@ export function loggedCursorSendOptions( if (options === undefined) { return {}; } + const mcpServerNames = + options.mcpServers === undefined ? undefined : Object.keys(options.mcpServers).toSorted(); return { ...(options.model === undefined ? {} : { model: options.model }), ...(options.mode === undefined ? {} : { mode: options.mode }), + ...(mcpServerNames === undefined ? {} : { hasMcpServers: true, mcpServerNames }), ...(options.local === undefined ? {} : { @@ -466,16 +473,18 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu const startRun = () => Effect.tryPromise({ try: () => - agent.send(sendInput.message, { - ...sendInput.options, - onDelta: async ({ update }) => { - if (!callbacksReady) { - pendingUpdates.push(update); - return; - } - await dispatchUpdate(update); - }, - }), + sendInput.summarize === true + ? agent.summarize() + : agent.send(sendInput.message, { + ...sendInput.options, + onDelta: async ({ update }) => { + if (!callbacksReady) { + pendingUpdates.push(update); + return; + } + await dispatchUpdate(update); + }, + }), catch: (cause) => runnerError(cause, "run.start"), }); const run = yield* startRun().pipe( diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index e03c4e07242d4..4c421a352a8ca 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -219,7 +219,7 @@ describe("CursorAdapterV2", () => { Stream.takeUntil((event) => event.type === "turn.terminal"), Stream.runCollect, ); - assert.isFalse(sentWithMcpOverride); + assert.isTrue(sentWithMcpOverride); const rows = events.filter((event) => event.type === "subagent.updated"); assert.equal(rows[0]?.subagent.status, "running"); assert.equal(rows[0]?.subagent.model, model ?? null); @@ -510,11 +510,11 @@ describe("CursorAdapterV2", () => { ), ); - it.effect("fails standalone SDK transport diagnostics and sends compaction as /compress", () => + it.effect("fails standalone SDK transport diagnostics and compacts with SDK summarize", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-errors-" }); - const sentMessages: Array = []; + const summarizeRequests: Array = []; let sendCalls = 0; const instanceId = ProviderInstanceId.make("cursor"); const threadId = ThreadId.make("cursor-transport-error-thread"); @@ -538,9 +538,7 @@ describe("CursorAdapterV2", () => { send: (input) => Effect.sync(() => { sendCalls += 1; - sentMessages.push( - typeof input.message === "string" ? input.message : input.message.text, - ); + summarizeRequests.push(input.summarize === true); const runId = `native-cursor-run-${sendCalls}`; return { agentId: "native-cursor-error", @@ -551,9 +549,10 @@ describe("CursorAdapterV2", () => { status: "finished" as const, model: { id: "composer-2.5" }, durationMs: 1, - ...(sendCalls === 1 - ? { result: "Error: RetriableError: WritableIterable is closed" } - : {}), + result: + sendCalls === 1 + ? "Error: RetriableError: WritableIterable is closed" + : "Summary of the conversation so far", }), cancel: Effect.void, }; @@ -646,11 +645,12 @@ describe("CursorAdapterV2", () => { attachments: [], }, }); - yield* runtime.events.pipe( - Stream.filter((event) => event.type === "turn.terminal"), - Stream.runHead, + const compactionEvents = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, ); - assert.equal(sentMessages[1], "/compress"); + assert.deepEqual(summarizeRequests, [false, true]); + assert.notInclude(JSON.stringify(compactionEvents), "Summary of the conversation so far"); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 924139ec34daa..73f7ac9d9767d 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -2385,15 +2385,18 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( hasDeviceTools, delivered, ); + const compacted = message === "/compress"; const pendingUpdates: Array = []; let context: ActiveCursorTurn | null = null; - // MCP send overrides replace the ambient servers loaded when the agent opens. + // Create-time and send-time mcpServers merge with settingSources (SDK >= 1.0.39). const sdkRun = yield* agent.session .send({ message, + summarize: compacted, options: { model: cursorSdkModelSelection(turnInput.modelSelection), mode: turnInput.runtimePolicy.interactionMode === "plan" ? "plan" : "agent", + ...(mcpServers === undefined ? {} : { mcpServers }), }, onDelta: (update) => { if (context === null) { @@ -2405,7 +2408,6 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }, }) .pipe(Effect.mapError(classifyCursorModelRejection(turnInput.modelSelection))); - const compacted = message === "/compress"; yield* Ref.set(told, { agent: agent.nativeThreadId, orchestration: !compacted && (delivered.orchestration || mcpServers !== undefined), @@ -2469,6 +2471,8 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( if ( context !== null && context.assistant.nextSegment === 0 && + // A summarize run's result is the summary, not an answer. + !compacted && // Text from a resume that made no progress is not the turn's answer. !isResumeFailureAfterTurnEnded(context, result) && result.result !== undefined && diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fa3d823395445..ccc69351000ec 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -833,8 +833,8 @@ importers: specifier: ^0.3.276 version: 0.3.276(@anthropic-ai/sdk@0.93.0(zod@4.6.5))(@modelcontextprotocol/sdk@1.29.0(supports-color@8.1.1)(zod@4.6.5))(zod@4.6.5) '@cursor/sdk': - specifier: 1.0.38 - version: 1.0.38(zod@4.6.5) + specifier: 1.2.0 + version: 1.2.0(zod@4.6.5) '@effect/platform-node': specifier: 4.0.5 version: 4.0.5(bufferutil@4.1.0)(effect@4.0.5)(redis@6.2.1)(utf-8-validate@6.0.6) @@ -1701,8 +1701,8 @@ importers: packages/provider-cursor: dependencies: '@cursor/sdk': - specifier: 1.0.38 - version: 1.0.38(zod@4.6.5) + specifier: 1.2.0 + version: 1.2.0(zod@4.6.5) '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 @@ -3511,38 +3511,38 @@ packages: resolution: {integrity: sha512-bPlN9S9O1A0euCpEWE4qnvB5YDuyYVsUTrxSgmAM1Is0j4tICHoVyOVAXfWMP/kS9ZrjvyIXWV2PmomiAXXqOw==} engines: {node: '>=20.19.0'} - '@cursor/sdk-darwin-arm64@1.0.38': - resolution: {integrity: sha512-pXxj4pjbIoDo6ZjgksSf4VTD4EJz6BGDKvFjDVVUMg0PmLCVbceOnp0pqfRO8SVpdUSE45GFrXuLnSZgLag/xw==} + '@cursor/sdk-darwin-arm64@1.2.0': + resolution: {integrity: sha512-UkZ/RdxKCpOQ85nRgzSq+g0h+gIw36/lCEvQvomhs5EkSFZW3OwbeEzkAU3UYglZ7t3RNHj3mc5C5cdDtHguvw==} cpu: [arm64] os: [darwin] hasBin: true - '@cursor/sdk-darwin-x64@1.0.38': - resolution: {integrity: sha512-rutfTMq1f9WZckPFH8R5bzNzHaZg7I/TijVUkfD3GbqIqqc5OKHzdTMqZf+AFAqRDQccGJn4GLWcnQ9wTwIVNA==} + '@cursor/sdk-darwin-x64@1.2.0': + resolution: {integrity: sha512-mJTFdX+qv9dHAm59tT7uq7ci7+BDvFoNk4gdF2zGp9SLULicY+FdFD64p1qLen1bX5Y2soZaX5mWBy7BfObjcg==} cpu: [x64] os: [darwin] hasBin: true - '@cursor/sdk-linux-arm64@1.0.38': - resolution: {integrity: sha512-CqmUnM8W8W2mKucSrdHO0kn4ems82siWuo7kvVJvXCtPkaziVNC++dro5h9hSh2oVgRbB91sWQ4lzsHVIDpkvA==} + '@cursor/sdk-linux-arm64@1.2.0': + resolution: {integrity: sha512-Rs+cd5snuhxMAHkpqRfEGPB1qAsfqSOYJh5SOHZTOWy2LkRVO62WHwd4x80C2emj+dosTV5WAcuF2kMKKcrDJg==} cpu: [arm64] os: [linux] hasBin: true - '@cursor/sdk-linux-x64@1.0.38': - resolution: {integrity: sha512-RL6OJTAF3oozMG+HNtykySQ5BOP94yJNWP65wZ2yzMLTAW9ao80++OnaWJya1lndLacHLYP+QZT4igm5TT+BWQ==} + '@cursor/sdk-linux-x64@1.2.0': + resolution: {integrity: sha512-ainsGAFtkWTBZrLABp82Hvfv7VB/FxmZHE42qMVotFTRDwOY2iduvhSig910bVxv+kw3S00Srmu/9CxklLwhbw==} cpu: [x64] os: [linux] hasBin: true - '@cursor/sdk-win32-x64@1.0.38': - resolution: {integrity: sha512-IUfuCk/S/qzEB+tfT4yWH6iSMz56Lvakn1zNjdk+oAsZ7RJWtWkZcea6eqMSRB1WLmTeQG0uetXKX330w+xI0A==} + '@cursor/sdk-win32-x64@1.2.0': + resolution: {integrity: sha512-p3rkyta6R/nXIukd3/ifJq32otkkGoUi41T2jxnHbPHMhzE2F8OuJQGBVmORuQLMr+bIGGVZmCxertgs4WgzcQ==} cpu: [x64] os: [win32] hasBin: true - '@cursor/sdk@1.0.38': - resolution: {integrity: sha512-8UwPKaprIXvlVR71yHyNNTyFwZCOzfHW7W+FKjPdDS9Ym9FDZc51Jwsu9lAhxHf7n0US3t0pybkDaNFdldrQ+A==} + '@cursor/sdk@1.2.0': + resolution: {integrity: sha512-Nqm2U0zTWrYEDCv3Rdwsfa1gYZWsg+JnY+I2F8BwWSAr3FNo0TZWwyHWoWngZgriF1w02fJ4gjJWaul9zysvgQ==} engines: {node: '>=22.13'} peerDependencies: zod: ^3.25.0 || ^4.0.0 @@ -13501,22 +13501,22 @@ snapshots: '@csstools/css-tokenizer@4.0.1': {} - '@cursor/sdk-darwin-arm64@1.0.38': + '@cursor/sdk-darwin-arm64@1.2.0': optional: true - '@cursor/sdk-darwin-x64@1.0.38': + '@cursor/sdk-darwin-x64@1.2.0': optional: true - '@cursor/sdk-linux-arm64@1.0.38': + '@cursor/sdk-linux-arm64@1.2.0': optional: true - '@cursor/sdk-linux-x64@1.0.38': + '@cursor/sdk-linux-x64@1.2.0': optional: true - '@cursor/sdk-win32-x64@1.0.38': + '@cursor/sdk-win32-x64@1.2.0': optional: true - '@cursor/sdk@1.0.38(zod@4.6.5)': + '@cursor/sdk@1.2.0(zod@4.6.5)': dependencies: '@bufbuild/protobuf': 1.10.0 '@connectrpc/connect': 1.7.0(@bufbuild/protobuf@1.10.0) @@ -13524,11 +13524,11 @@ snapshots: '@statsig/js-client': 3.31.0 zod: 4.6.5 optionalDependencies: - '@cursor/sdk-darwin-arm64': 1.0.38 - '@cursor/sdk-darwin-x64': 1.0.38 - '@cursor/sdk-linux-arm64': 1.0.38 - '@cursor/sdk-linux-x64': 1.0.38 - '@cursor/sdk-win32-x64': 1.0.38 + '@cursor/sdk-darwin-arm64': 1.2.0 + '@cursor/sdk-darwin-x64': 1.2.0 + '@cursor/sdk-linux-arm64': 1.2.0 + '@cursor/sdk-linux-x64': 1.2.0 + '@cursor/sdk-win32-x64': 1.2.0 '@date-fns/tz@1.5.0': {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index be4d3c29ea763..e2865566986d9 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -227,6 +227,12 @@ minimumReleaseAgeExclude: - "@pierre/highlights@0.2.0" - "@pierre/theming@1.0.2" - agent-device@0.21.32 + - "@cursor/sdk-darwin-arm64@1.2.0" + - "@cursor/sdk-darwin-x64@1.2.0" + - "@cursor/sdk-linux-arm64@1.2.0" + - "@cursor/sdk-linux-x64@1.2.0" + - "@cursor/sdk-win32-x64@1.2.0" + - "@cursor/sdk@1.2.0" overrides: # Pin every patched package, including transitive dependencies, so lockfile-free From ed8833f80371ef04901d09db78b94b9edb2a4dc2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 09:04:40 -0800 Subject: [PATCH 039/163] fix(mobile): pending auto-merge shows in the merge button (#29465) Co-authored-by: Claude Opus 5.5 --- .../PullRequestMergeControls.tsx | 30 ++++++++++++------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx index 8ba68d2a2bfa9..30b682a157201 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx @@ -82,6 +82,8 @@ export function PullRequestMergeControls(props: { ? `${MERGE_METHODS[method].title} stack (${scope.layers.length})` : MERGE_METHODS[method].title : "Merge unavailable"; + const autoMergeArmed = pr.state === "open" && pr.autoMergeEnabled === true; + const armedLabel = `Auto-merge pending${pr.autoMergeMethod ? ` (${pr.autoMergeMethod})` : ""}`; const autoAction = pr.autoMergeEnabled ? "disable-auto-merge" : "enable-auto-merge"; const canAutoMerge = !busy && @@ -167,13 +169,25 @@ export function PullRequestMergeControls(props: { return ( confirm("merge")} menuTitle="Merge options" actions={[ @@ -202,17 +216,13 @@ export function PullRequestMergeControls(props: { }} /> {permissions.connected && + !autoMergeArmed && reason && reason !== MERGE_CONFLICT_REASON && reason !== "Checking stack membership…" && !(checkingStack && reason === "Refresh the stack before merging.") ? ( {reason} ) : null} - {pr.autoMergeEnabled ? ( - - Auto-merge is enabled{pr.autoMergeMethod ? ` · ${pr.autoMergeMethod}` : ""} - - ) : null} {stack.error && stack.supportsStackActions ? ( \n \n );\n}\n", "apps/web/src/tasks/api.ts": "export const stopTask = (id: string) => fetch(`/api/tasks/${id}/stop`, { method: 'POST' });\n"}}}, "prompt": "In the task list, the Stop button on a running background task does nothing: the task keeps showing Running and its worker thread keeps going. Wire it up.", "expect": {"notCalls": ["t3_thread_launch", "create_threads", "delegate_task", "orchestrator_capabilities", "task_cancel", "task_status", "t3_thread_interrupt", "t3_thread_send"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-10-29; regression guard"}, "notes": ""} +{"id": "tt-control-task-queue", "area": "orchestration", "kind": "control", "pattern": "Domain task queue lookup", "experience": "A question about the app's task queue limit is ordinary code work, not a T3 task.", "rule": "Ordinary coding tasks need no T3 tools.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repository: /home/user/app (acme/app). This is the local machine.", "world": {"repo": "acme/app", "branch": "main", "status": "", "files": {"docs/cache.md": "Cache exports must preserve keys.\n", "src/thread-pool.ts": "export const workerCount = 4;\n", "src/task-queue.ts": "export const queueLimit = 10;\n", "src/agent-config.ts": "export const agentLabel = \"Assistant\";\n"}}, "mocks": {"t3_thread_launch": {"threadId": "11111111-1111-4111-8111-111111111111", "projectId": "33333333-3333-4333-8333-333333333333", "modelSelection": {"instanceId": "codex", "model": "gpt-6.1-sol", "options": []}, "runId": "run-acme-thread", "status": "running"}, "t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Acme cache worker", "status": "running"}, "items": [{"position": 1, "type": "assistant_message", "text": "Checking the cache export."}], "nextPosition": 1, "hasMore": false}, "t3_thread_wait": {"threadId": "11111111-1111-4111-8111-111111111111", "runId": "run-acme-thread", "status": "running", "timedOut": true, "next": "Completion wakes this thread, so end your turn. Do not wait on it or poll it."}}}, "prompt": "Explain the configured limit in src/task-queue.ts. This is the application task queue.", "expect": {"notCalls": ["t3_thread_launch", "create_threads", "delegate_task", "Agent", "Workflow", "orchestrator_capabilities", "task_status", "task_cancel"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-10-29; regression guard"}, "notes": "Synthetic Acme scenario; no field transcript copied."} +{"id": "tt-control-agent-config", "area": "orchestration", "kind": "control", "pattern": "Domain agent configuration lookup", "experience": "A question about the app's agent label setting is ordinary code work; it starts no agent.", "rule": "Ordinary coding tasks need no T3 tools.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repository: /home/user/app (acme/app). This is the local machine.", "world": {"repo": "acme/app", "branch": "main", "status": "", "files": {"docs/cache.md": "Cache exports must preserve keys.\n", "src/thread-pool.ts": "export const workerCount = 4;\n", "src/task-queue.ts": "export const queueLimit = 10;\n", "src/agent-config.ts": "export const agentLabel = \"Assistant\";\n"}}, "mocks": {"t3_thread_launch": {"threadId": "11111111-1111-4111-8111-111111111111", "projectId": "33333333-3333-4333-8333-333333333333", "modelSelection": {"instanceId": "codex", "model": "gpt-6.1-sol", "options": []}, "runId": "run-acme-thread", "status": "running"}, "t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Acme cache worker", "status": "running"}, "items": [{"position": 1, "type": "assistant_message", "text": "Checking the cache export."}], "nextPosition": 1, "hasMore": false}, "t3_thread_wait": {"threadId": "11111111-1111-4111-8111-111111111111", "runId": "run-acme-thread", "status": "running", "timedOut": true, "next": "Completion wakes this thread, so end your turn. Do not wait on it or poll it."}}}, "prompt": "Read src/agent-config.ts and tell me the current default agent label in this application.", "expect": {"notCalls": ["t3_thread_launch", "create_threads", "delegate_task", "Agent", "Workflow", "orchestrator_capabilities"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-10-29; regression guard"}, "notes": "Synthetic Acme scenario; no field transcript copied."} +{"id": "tt-background-research-no-agent-word", "area": "orchestration", "kind": "guard", "pattern": "bare 'in the background' ask: delegate_task", "experience": "Asked to look into something in the background without the word 'agent', the agent must start a delegate_task, not a background native Agent or a new thread.", "rule": "Background agent work goes to delegate_task; Claude's Agent runs with run_in_background:false. / t3_thread_launch and create_threads make new top-level threads, only when the user asks for a new thread.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Repository: /home/user/app (acme/app). This is the local machine.", "world": {"repo": "acme/app", "branch": "main", "status": "", "files": {"docs/cache.md": "Cache exports must preserve keys.\n", "src/cache/export.ts": "export function exportCache(entries: Map) {\n return [...entries].filter(([, value]) => value !== '').map(([key, value]) => ({ key, value }));\n}\n"}}}, "prompt": "In the background, find out why src/cache/export.ts drops entries that docs/cache.md says must be kept, and report back when you know. I'll keep going on the release notes here.", "expect": {"calls": [{"tool": "delegate_task", "args": {"task": "~cache"}}], "notCalls": ["t3_thread_launch", "create_threads", "Workflow", "t3_thread_wait"], "callsMustNot": [{"tool": "Agent", "args": {"run_in_background": true}}, {"tool": "delegate_task", "args": {"mode": "wait"}}], "maxCalls": {"task_status": 0}}, "source": {"request": "juliusmarminge (maintainer) request, 2026-10-29; regression guard", "review": "council review round 1: bare background ask without 'agent'"}, "notes": "Synthetic Acme scenario. Pairs with tt-background-agent; checks the rule does not depend on the word 'agent'."} +{"id":"tt-control-background-test-run","area":"orchestration","kind":"control","pattern":"background shell command is not a delegate","experience":"Asked to run the test suite in the background while refactoring, the agent should use an ordinary background shell command, not a delegate, subagent or thread.","rule":"Ordinary coding tasks need no T3 tools.","privacy":"commit-safe","setup":{"role":"top","context":"Repository: /home/user/app (acme/app). This is the local machine.","world":{"repo":"acme/app","branch":"main","status":"","files":{"package.json":"{\"scripts\":{\"test\":\"vitest run\"}}\n","src/export/csv.ts":"export function toCsv(rows: Row[]) {\n return rows.map((r) => [r.id, r.total].join(',')).join('\\n');\n}\n"}}},"prompt":"Kick off the full test suite in the background, and meanwhile rename toCsv to rowsToCsv in src/export/csv.ts.","expect":{"notCalls":["delegate_task","t3_thread_launch","create_threads","Workflow","orchestrator_capabilities"],"callsMustNot":[{"tool":"Agent","args":{"run_in_background":true}}],"calls":[{"tool":"Bash","args":{"command":"~test"}}]},"source":{"request":"juliusmarminge (maintainer) request, 2026-10-29; regression guard","review":"council review round 1: over-correction control for 'background'"},"notes":"Synthetic Acme scenario. 'Background' here means a shell command, not an agent."} diff --git a/evals/mcp-tool-use/run.test.ts b/evals/mcp-tool-use/run.test.ts index 69de4f0c6c4b2..ff65511a9cc7d 100644 --- a/evals/mcp-tool-use/run.test.ts +++ b/evals/mcp-tool-use/run.test.ts @@ -23,6 +23,7 @@ import { shellOutput, shellRequest, summarize, + t3Default, t3SystemAppend, t3SubagentContext, withDevices, @@ -70,6 +71,54 @@ it("accepts any tool listed as an alternative", () => { ]); }); +it("counts the new threads an agent asks for, one brief per thread, over both creation tools", () => { + const expect = { newThreads: ["~reconnect", "~csv", "~admin"] }; + const run = (...calls: Array<{ tool: string; input: unknown; failed?: boolean }>): SampleRun => ({ + calls: calls.map((call, step) => ({ step, ...call })), + text: "", + stopReason: "end_turn", + }); + const batch = (...prompts: Array) => ({ + tool: "create_threads", + input: { threads: prompts.map((prompt) => ({ prompt })) }, + }); + const launch = (message: string, failed = false) => ({ + tool: "t3_thread_launch", + input: { message }, + failed, + }); + const label = 'newThreads ["~reconnect","~csv","~admin"]'; + assert.deepEqual(failed(expect, run(batch("Fix reconnect", "Fix CSV dates", "Fix admin"))), []); + assert.deepEqual( + failed(expect, run(launch("Fix reconnect"), batch("Fix CSV dates", "Fix admin"))), + [], + ); + assert.deepEqual( + failed(expect, run(launch("Fix reconnect", true), batch("Fix reconnect", "csv", "admin"))), + [], + ); + assert.deepEqual(failed(expect, run(batch("reconnect", "csv"), launch("csv and admin"))), []); + assert.deepEqual(failed(expect, run(batch("Fix reconnect, csv and admin"))), [label]); + assert.deepEqual(failed(expect, run(batch("reconnect, csv, admin", "csv", "csv"))), [label]); + assert.deepEqual(failed(expect, run(batch("reconnect", "csv", "admin", "docs"))), [label]); + for (const call of [ + { tool: "t3_thread_launch", input: { prompt: "csv" } }, + { tool: "create_threads", input: { threads: [{ message: "csv" }] } }, + ]) { + assert.deepEqual(failed(expect, run(launch("reconnect"), launch("admin"), call)), [label]); + } + assert.deepEqual( + failed( + expect, + run(launch("reconnect"), launch("admin"), { + tool: "t3_thread_launch", + input: { title: "CSV", message: "Fix reconnect" }, + }), + ), + [label], + ); +}); + it("runs code-mode calls without exposing host capabilities, including after await", async () => { const catalog = [{ name: "mock", description: "mock" }]; const result = await executeCodex( @@ -345,6 +394,57 @@ it("replays earlier capability results with the model under test as the caller", assert.include(String(replayed?.content), '"inheritedModel":"claude-opus-5-5"'); }); +it("gives each launched thread its own id, and reading it back shows that thread's brief", () => { + const base = buildBase(template, { model: "claude-sonnet-5-5", keepUserInstructions: false }); + const sample = makeSample(childCase, base); + const one = t3Default(sample, "t3_thread_launch", { + title: "Reconnect", + message: "Fix reconnect", + }); + const batch = t3Default(sample, "create_threads", { + threads: [ + { title: "CSV", prompt: "Fix CSV dates" }, + { prompt: "Fix admin expiry", target: { providerInstanceId: "muse", model: "muse-wonder" } }, + ], + }); + const created = (batch as { threads: Array<{ providerInstanceId: string; model: string }> }) + .threads; + assert.deepEqual( + created.map((thread) => [thread.providerInstanceId, thread.model]), + [ + ["claudeAgent", "claude-sonnet-5-5"], + ["muse", "muse-wonder"], + ], + ); + const ids = [one, ...(batch as { threads: Array }).threads].map( + (thread) => (thread as { threadId: string }).threadId, + ); + assert.equal(new Set(ids).size, 3); + const read = (threadId: unknown) => + t3Default(sample, "t3_thread_read", { threadId }) as { + thread: { title: string; status: string; createdBy?: string }; + items: Array<{ text: string; createdBy: string; creationSource: string }>; + }; + const idle = t3Default(sample, "create_threads", { threads: [{ title: "Later" }] }) as { + threads: Array<{ threadId: string; status: string; runId?: string }>; + }; + assert.equal(idle.threads[0]?.status, "idle"); + assert.isUndefined(idle.threads[0]?.runId); + assert.equal(read(idle.threads[0]?.threadId).thread.status, "idle"); + assert.deepEqual(read(idle.threads[0]?.threadId).items, []); + assert.equal(read(ids[1]).thread.title, "CSV"); + assert.equal(read(ids[2]).items[0]?.text, "Fix admin expiry"); + assert.equal(read(ids[2]).thread.createdBy, "agent"); + assert.deepEqual( + [read(ids[2]).items[0]?.createdBy, read(ids[2]).items[0]?.creationSource], + ["agent", "mcp"], + ); + assert.equal( + read("11111111-1111-4111-8111-111111111111").thread.title, + "Fix the flaky reconnect test", + ); +}); + it("does not record a deferred tool called before it was loaded", () => { const base = buildBase(template, { model: "claude-sonnet-5-5", keepUserInstructions: false }); const sample = makeSample(childCase, base); diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index 20f9090692d8b..01a3bd9a1de11 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -162,6 +162,11 @@ const McpToolUseExpect = Schema.Struct({ order: Schema.optional(Schema.Array(Schema.String)), minCalls: Schema.optional(Schema.Record(Schema.String, Schema.Number)), maxCalls: Schema.optional(Schema.Record(Schema.String, Schema.Number)), + /** + * One `args`-style value per new top-level thread the agent asks for, by `t3_thread_launch` or a + * `create_threads` entry. Each matches a different thread's request; no other thread is asked for. + */ + newThreads: Schema.optional(Schema.Array(Schema.Unknown)), /** The last step with tool calls includes this tool, then the turn ends. */ endsTurnAfter: Schema.optional(Schema.String), /** Regexes that no shell command may match. */ @@ -732,7 +737,8 @@ const createdPullRequests = ({ tool, input, output }: ShellEntry) => : []; /** * One sample's state. ToolSearch adds loaded schemas to `tools`, like Claude Code. `shell` is the - * history the simulator keeps consistent with; `linked` and `nextTask` do the same for T3 results. + * history the simulator keeps consistent with; `linked`, `nextTask` and `threads` do the same for + * T3 results. */ type Sample = { readonly testCase: McpToolUseCase; @@ -744,6 +750,8 @@ type Sample = { readonly linked: Set; readonly codeStore: Record; nextTask: number; + /** Threads the agent launched in this sample, by id, so reading one shows its own brief. */ + readonly threads: Map; /** T3's device tools, once `withDevices` builds them for a world with devices. */ devices?: DeviceTools; /** T3's results for prior device calls whose case result is "default". */ @@ -788,6 +796,7 @@ export const makeSample = (testCase: McpToolUseCase, base: Base): Sample => { linked: new Set([...urls, ...shell.flatMap(createdPullRequests)]), codeStore: {}, nextTask: Math.max(0, ...taskNumbers) + 1, + threads: new Map(), priorResults: new Map(), }; }; @@ -1000,9 +1009,41 @@ const linkedEntry = (sample: Sample, url: string) => { }; /** A believable T3 result for a tool the case does not mock. */ -const t3Default = (sample: Sample, name: string, input: Readonly>) => { +export const t3Default = ( + sample: Sample, + name: string, + input: Readonly>, +) => { const pr = () => pullRequest(sample.repo, input); + const newThread = (request: unknown, brief: unknown) => { + const n = sample.nextTask++; + const title = + isRecord(request) && typeof request.title === "string" ? request.title : "New thread"; + const text = typeof brief === "string" ? brief.trim() : ""; + sample.threads.set(uuid(n), { title, brief: text }); + return { + threadId: uuid(n), + title, + ...(text ? { runId: `run-${n}`, status: "starting" } : { status: "idle" }), + }; + }; switch (name) { + case "t3_thread_launch": + return newThread(input, input.message); + case "create_threads": + return { + threads: (Array.isArray(input.threads) ? input.threads : []).map((request) => { + const target = isRecord(request) && isRecord(request.target) ? request.target : {}; + return { + ...newThread(request, isRecord(request) ? request.prompt : undefined), + createdBy: "agent", + creationSource: "mcp", + providerInstanceId: + target.providerInstanceId ?? (sample.base.codex ? "codex" : "claudeAgent"), + model: target.model ?? sample.base.model, + }; + }), + }; case "orchestrator_capabilities": return { inheritedProviderInstanceId: "claudeAgent", @@ -1108,6 +1149,20 @@ const t3Default = (sample: Sample, name: string, input: Readonly { return Object.entries(expected).every(([path, value]) => matches(value, at(path))); }; +/** Each new top-level thread request in a run; a failed call created nothing. */ +const newThreadRequests = (calls: ReadonlyArray) => + calls.flatMap((call): ReadonlyArray<{ request: unknown; brief: unknown }> => { + if (call.failed === true || !isRecord(call.input)) return []; + if (call.tool === "t3_thread_launch") + return [{ request: call.input, brief: call.input.message }]; + if (call.tool !== "create_threads" || !Array.isArray(call.input.threads)) return []; + return call.input.threads.map((request: unknown) => ({ + request, + brief: isRecord(request) ? request.prompt : undefined, + })); + }); + +/** Whether every expected value can take a different request it matches. */ +const matchesDistinct = ( + expected: ReadonlyArray, + requests: ReturnType, + taken: ReadonlySet = new Set(), +): boolean => { + const [first, ...rest] = expected; + if (expected.length === 0) return true; + return requests.some( + ({ request, brief }, i) => + !taken.has(i) && + matches(first, typeof first === "string" ? brief : request) && + matchesDistinct(rest, requests, new Set([...taken, i])), + ); +}; + /** delegate_task takes `target.options` as an object or `[{id, value}]`. Grade both as an object. */ const withOptionsObject = (input: unknown) => { if (!isRecord(input) || !isRecord(input.target) || !Array.isArray(input.target.options)) { @@ -1472,6 +1556,13 @@ export const gradeSample = (expect: McpToolUseCase["expect"], run: SampleRun) => add(`minCalls ${t} >= ${n}`, count(t) >= n); for (const [t, n] of Object.entries(expect.maxCalls ?? {})) add(`maxCalls ${t} <= ${n}`, count(t) <= n); + if (expect.newThreads !== undefined) { + const requests = newThreadRequests(calls); + add( + `newThreads ${valueText(expect.newThreads)}`, + requests.length === expect.newThreads.length && matchesDistinct(expect.newThreads, requests), + ); + } if (expect.endsTurnAfter !== undefined) { const lastStep = Math.max(-1, ...calls.map((call) => call.step)); const last = calls.filter((call) => call.step === lastStep).map((call) => call.tool); From 9bcf75335f9b2a8af877e1317c809b72a070b280 Mon Sep 17 00:00:00 2001 From: Gabriel De Andrade <30420087+gabrielelpidio@users.noreply.github.com> Date: Mon, 2 Nov 2026 14:41:50 -0400 Subject: [PATCH 043/163] fix(server): background agent asks go to delegate_task, not a background Agent (#27139) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- apps/server/src/provider/CodexDeveloperInstructions.test.ts | 5 ++++- .../provider-core/src/server/orchestrationInstructions.ts | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/server/src/provider/CodexDeveloperInstructions.test.ts b/apps/server/src/provider/CodexDeveloperInstructions.test.ts index 87473e8da2f11..e8939f2368ada 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.test.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.test.ts @@ -65,7 +65,10 @@ describe("Codex orchestration context", () => { NodeAssert.ok(orchestration.includes("use your native tool when the child uses your provider")); NodeAssert.ok(orchestration.includes("`run_in_background:false`")); - NodeAssert.ok(orchestration.includes("A native type running another provider's model")); + NodeAssert.ok(orchestration.includes("A native type on another provider's model")); + NodeAssert.ok( + orchestration.includes("Background agent: `delegate_task`, never a background `Agent`."), + ); NodeAssert.ok( orchestration.includes("Every new delegate review or re-check is a new `delegate_task`"), ); diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index 70b3fff064f3b..90ed18e9b3398 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -6,7 +6,7 @@ export const T3_CODE_ORCHESTRATION_SECTIONS: ReadonlyArray = [ Ordinary coding tasks need no T3 tools. -- Subagents: use your native tool when the child uses your provider, a model it offers, and no settings beyond yours, and it finishes in this turn (Claude \`Agent\` always with \`run_in_background:false\`; Codex \`spawn_agent\`, then wait). Use \`delegate_task\` for another provider's model, user-asked settings, a separate checkout (\`isolation:"worktree"\`), background work, or \`delegate_task\` by name. A native type running another provider's model counts too. Workflow only when asked. +- Subagents: use your native tool when the child uses your provider, a model it offers, and no settings beyond yours (Claude \`Agent\`, \`run_in_background:false\`; Codex \`spawn_agent\`, then wait). Use \`delegate_task\` for another provider's model, user-asked settings, a separate checkout (\`isolation:"worktree"\`), or \`delegate_task\` by name. A native type on another provider's model counts too. Background agent: \`delegate_task\`, never a background \`Agent\`. Workflow only when asked. - Call \`orchestrator_capabilities\` once per thread, before the first \`delegate_task\`. Again only after an error or a user-named provider change. Settings go in \`target.options\`. Provider or model unavailable: say so. Never switch unasked, or fall back to native tools, Workflow, or CLIs. Never make a child's checkout in the shell or in \`task\`. - Every new delegate review or re-check is a new \`delegate_task\` (brief, findings, objections), never a \`t3_thread_send\`. Fix small review findings yourself; start no delegate for them. When told to proceed without a delegate, or to run fewer, \`task_cancel\` the extras. Start no replacement. - Follow a running delegate's \`next\`. Do not poll it (\`task_status\`, \`sleep\`, watchers, Monitor, ScheduleWakeup). Stop a delegate run you replace or no longer need with \`task_cancel\`, never \`t3_thread_interrupt\` on a \`childThreadId\`. From 84537c4dd976a89b6ec094f43ae3ef7bee12cb1a Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Mon, 2 Nov 2026 14:23:37 -0500 Subject: [PATCH 044/163] feat(server): read source control host tokens from a secret provider (#27756) Signed-off-by: Yordis Prieto Co-authored-by: maria-rcks --- .../src/provider/ProviderInstanceRegistry.ts | 20 +++-- .../server/src/secrets/settingsSecretValue.ts | 10 +-- apps/server/src/serverSettings.test.ts | 28 +++++-- .../sourceControlHostSecrets.test.ts | 23 +++++- .../sourceControl/sourceControlHostSecrets.ts | 11 ++- .../SourceControlAppSignInSettings.tsx | 4 +- .../settings/SourceControlTokenSettings.tsx | 48 ++++++++--- packages/contracts/src/settingsSecretValue.ts | 70 ++++++++++++---- .../src/shared/definition.ts | 3 +- .../src/server/GitHubCredentials.ts | 8 +- .../src/server/GitHubSourceControlProvider.ts | 7 +- .../src/server/gitHubDiscovery.test.ts | 82 ++++++++++++++++++- 12 files changed, 256 insertions(+), 58 deletions(-) diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts index 57a218a0dafe1..cc3ca60fcb829 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.ts @@ -9,6 +9,8 @@ import { type SecretReference, secretReferencesInSettings, type ServerProvider, + type SettingsSecretSlot, + withSettingsSecrets, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -45,7 +47,7 @@ export class ProviderInstanceRegistry extends Context.Service< interface InstanceSecrets { readonly environment: ResolvedProviderInstanceEnvironment; - readonly config: Readonly>; + readonly config: ReadonlyArray; } interface LiveEntry { @@ -110,12 +112,12 @@ const readInstanceSecrets = Effect.fn("ProviderInstanceRegistry.readInstanceSecr } return [{ ...variable, value: secret, sensitive: true }]; }); - const config: Record = {}; - for (const { field } of configFields) { + const config = configFields.flatMap(({ field, key }) => { const secret = values[index++]; - if (secret === undefined) unreadable.push(field); - else config[field] = secret; - } + if (secret !== undefined) return [{ field, key, value: secret }]; + unreadable.push(field); + return []; + }); const secrets: InstanceSecrets = { environment, config }; return { secrets, unreadable }; }); @@ -224,7 +226,7 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* reference)); - const resolved = Object.fromEntries( - pending.map(({ field }, index) => [field, values[index] ?? ""] as const), + return withSettingsSecrets( + settings, + pending.map((slot, index) => ({ ...slot, value: values[index] ?? "" })), ); - return { ...settings, ...resolved }; }); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 281bab5e4227b..cc34e2f818381 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1547,20 +1547,34 @@ it.layer(NodeServices.layer)("server settings", (it) => { provider: SecretProviderId.make("personal"), reference: "op://Private/Bitbucket/token", }; + const gitHubReference = { + provider: SecretProviderId.make("personal"), + reference: "op://Private/GitHub/token", + }; yield* serverSettings.updateSettings({ - sourceControlHosts: { bitbucket: { accessToken: "bb-access" } }, + sourceControlHosts: { + bitbucket: { accessToken: "bb-access" }, + github: { tokens: { "github.com": "ghp_dotcom", "ghe.acme.test": "ghp_ghe" } }, + }, }); assert.isTrue(Option.isSome(yield* stored("bitbucket", "accessToken", null))); + assert.isTrue(Option.isSome(yield* stored("github", "tokens", "github.com"))); const referenced = yield* serverSettings.updateSettings({ - sourceControlHosts: { bitbucket: { accessToken: reference } }, + sourceControlHosts: { + bitbucket: { accessToken: reference }, + github: { tokens: { "github.com": gitHubReference, "ghe.acme.test": "ghp_ghe" } }, + }, }); assert.deepEqual(referenced.sourceControlHosts.bitbucket?.accessToken, reference); assert.isTrue(Option.isNone(yield* stored("bitbucket", "accessToken", null))); - assert.deepEqual( - ServerSettingsModule.redactServerSettingsForClient(referenced).sourceControlHosts - .bitbucket?.accessToken, - reference, - ); + assert.isTrue(Option.isNone(yield* stored("github", "tokens", "github.com"))); + assert.isTrue(Option.isSome(yield* stored("github", "tokens", "ghe.acme.test"))); + const redacted = + ServerSettingsModule.redactServerSettingsForClient(referenced).sourceControlHosts; + assert.deepEqual(redacted.bitbucket?.accessToken, reference); + const tokens = redacted.github?.tokens as Record; + assert.deepEqual(tokens["github.com"], gitHubReference); + assert.notEqual(tokens["ghe.acme.test"], "ghp_ghe"); }).pipe(Effect.provide(layerServerSettingsWithSecrets())), ); diff --git a/apps/server/src/sourceControl/sourceControlHostSecrets.test.ts b/apps/server/src/sourceControl/sourceControlHostSecrets.test.ts index bfbe4a1c8ac94..be1da6f3d610c 100644 --- a/apps/server/src/sourceControl/sourceControlHostSecrets.test.ts +++ b/apps/server/src/sourceControl/sourceControlHostSecrets.test.ts @@ -14,7 +14,14 @@ const source = (reference: string) => ({ reference, }); -const secretsByReference = new Map([["bitbucket#token", "bb_from_provider"]]); +const secretsByReference = new Map([ + ["bitbucket#token", "bb_from_provider"], + ["github#token", "ghp_from_provider"], +]); + +const perHostHosts = { + github: { tokens: { "github.com": source("github#token"), "ghe.acme.test": "ghp_literal" } }, +}; const hosts = { bitbucket: { email: "me@example.test", accessToken: source("bitbucket#token") }, @@ -69,11 +76,25 @@ it.effect("leaves the resolver unused for a kind that holds no reference", () => }), ); +it.effect("replaces a per-host token reference and keeps the literal beside it", () => + Effect.gen(function* () { + const { reads, resolver } = countingResolver(); + const resolved = yield* resolveSourceControlHostSecrets(resolver, perHostHosts, "github"); + assert.deepEqual(resolved, { + github: { tokens: { "github.com": "ghp_from_provider", "ghe.acme.test": "ghp_literal" } }, + }); + assert.deepEqual(reads, ["github#token"]); + }), +); + it("collects the references held in credential fields and skips literal values", () => { assert.deepEqual(collectSourceControlHostSecretReferences(hosts), [ source("missing#token"), source("bitbucket#token"), ]); + assert.deepEqual(collectSourceControlHostSecretReferences(perHostHosts), [ + source("github#token"), + ]); assert.deepEqual( collectSourceControlHostSecretReferences({ bitbucket: { accessToken: "literal" }, diff --git a/apps/server/src/sourceControl/sourceControlHostSecrets.ts b/apps/server/src/sourceControl/sourceControlHostSecrets.ts index cf86ade6b0eee..82de25be4de69 100644 --- a/apps/server/src/sourceControl/sourceControlHostSecrets.ts +++ b/apps/server/src/sourceControl/sourceControlHostSecrets.ts @@ -53,7 +53,16 @@ export function writeSecretFieldValues( ): unknown { if (typeof original === "string") return values[0]?.[1] ?? ""; if (isSecretReference(original)) return original; - return Object.fromEntries(values.map(([serverHost, value]) => [serverHost ?? "", value])); + const sources = + original !== null && typeof original === "object" && !Array.isArray(original) + ? Object.entries(original).flatMap(([serverHost, entry]) => + isSecretReference(entry) ? [[serverHost.trim().toLowerCase(), entry] as const] : [], + ) + : []; + return Object.fromEntries([ + ...sources, + ...values.map(([serverHost, value]) => [serverHost ?? "", value] as const), + ]); } type SourceControlHostsSettings = Readonly>>>; diff --git a/apps/web/src/components/settings/SourceControlAppSignInSettings.tsx b/apps/web/src/components/settings/SourceControlAppSignInSettings.tsx index 5662954ef7cd6..df73fa3b24b45 100644 --- a/apps/web/src/components/settings/SourceControlAppSignInSettings.tsx +++ b/apps/web/src/components/settings/SourceControlAppSignInSettings.tsx @@ -101,7 +101,9 @@ export function SourceControlAppSignInSettings({ readHostCredentialSettings(settings, definition.kind), ); const signedIn = (signIns[host] ?? "").length > 0; - const tokenOverrides = (tokens[host] ?? "").length > 0; + const token = tokens[host]; + // A token read from a secret provider overrides the sign-in like a saved one. + const tokenOverrides = typeof token === "string" ? token.length > 0 : token !== undefined; const canSignIn = useAtomValue( sourceControlEnvironment.startSignIn.permissionAtom(environmentId), ); diff --git a/apps/web/src/components/settings/SourceControlTokenSettings.tsx b/apps/web/src/components/settings/SourceControlTokenSettings.tsx index 912de7ad91701..5a78b5f28287d 100644 --- a/apps/web/src/components/settings/SourceControlTokenSettings.tsx +++ b/apps/web/src/components/settings/SourceControlTokenSettings.tsx @@ -1,4 +1,9 @@ -import type { EnvironmentId } from "@t3tools/contracts"; +import { + isSecretReference, + type EnvironmentId, + type SecretReference, + type SettingsSecretValue, +} from "@t3tools/contracts"; import { ExternalLinkIcon } from "lucide-react"; import { useState } from "react"; @@ -12,8 +17,11 @@ import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button, InlineButton } from "../ui/button"; import { Input } from "../ui/input"; -import { SecretInput } from "./SecretInput"; import { Label } from "../ui/label"; +import { SecretSourceInput, useSecretSources } from "./SecretSourceInput"; + +const hasToken = (token: SettingsSecretValue | undefined) => + typeof token === "string" ? token.length > 0 : token !== undefined; export function SourceControlTokenSettings({ environmentId, @@ -34,15 +42,24 @@ export function SourceControlTokenSettings({ }); const defaultHost = definition.publicHost ?? ""; const [host, setHost] = useState(defaultHost); - const [draft, setDraft] = useState(""); + const secretSources = useSecretSources(environmentId); + const [pending, setPending] = useState<{ + readonly key: string; + readonly draft: string | SecretReference; + } | null>(null); const [saving, setSaving] = useState(false); const normalizedHost = host.trim().toLowerCase(); - const isSaved = (tokens[normalizedHost] ?? "").length > 0; + const savedToken = tokens[normalizedHost]; + const isSaved = hasToken(savedToken); const savedHosts = Object.entries(tokens) - .filter(([, value]) => value.length > 0) + .filter(([, value]) => hasToken(value)) .map(([saved]) => saved); + const sourceKey = JSON.stringify([normalizedHost, savedToken ?? ""]); + const draft = + pending?.key === sourceKey ? pending.draft : isSecretReference(savedToken) ? savedToken : ""; + const submission = typeof draft === "string" ? draft.trim() : draft; - const save = async (target: string, token: string) => { + const save = async (target: string, token: SettingsSecretValue) => { setSaving(true); const result = await updateSettings({ environmentId, @@ -55,7 +72,7 @@ export function SourceControlTokenSettings({ }); setSaving(false); if (result._tag === "Success") { - setDraft(""); + setPending(null); onSaved(); } }; @@ -65,7 +82,7 @@ export function SourceControlTokenSettings({ className="grid gap-3" onSubmit={(event) => { event.preventDefault(); - if (normalizedHost && draft.trim()) void save(normalizedHost, draft.trim()); + if (normalizedHost && submission !== "") void save(normalizedHost, submission); }} > {/* Locked while saving: a successful save clears the draft, which would drop edits made mid-request. */} @@ -106,12 +123,15 @@ export function SourceControlTokenSettings({
    - setDraft(event.target.value)} + sources={secretSources} + onChange={(event) => setPending({ key: sourceKey, draft: event.target.value })} + onSecretChange={(secret) => setPending({ key: sourceKey, draft: secret ?? "" })} />
    @@ -132,7 +152,11 @@ export function SourceControlTokenSettings({ Remove ) : null} -
    diff --git a/packages/contracts/src/settingsSecretValue.ts b/packages/contracts/src/settingsSecretValue.ts index 101c40998b6f0..97558c82d574f 100644 --- a/packages/contracts/src/settingsSecretValue.ts +++ b/packages/contracts/src/settingsSecretValue.ts @@ -26,26 +26,68 @@ export function acceptsSecretReference(schema: Schema.Top): boolean { return Schema.resolveAnnotationsKey(schema)?.settingsSecretReference === true; } -/** Fields of a settings struct typed `SettingsSecretValue`; any other schema has none. */ -function secretReferenceSettingsFields(schema: Schema.Top): ReadonlyArray { +const declaresSecretReference = (ast: SchemaAST.AST) => + ast.context?.annotations?.settingsSecretReference === true; + +interface SecretReferenceField { + readonly field: string; + readonly keyed: boolean; +} + +/** + * Fields of a settings struct typed `SettingsSecretValue`, or a record of it such as one value + * per host; any other schema has none. + */ +function secretReferenceSettingsFields(schema: Schema.Top): ReadonlyArray { if (!SchemaAST.isObjects(schema.ast)) return []; - return schema.ast.propertySignatures.flatMap((property) => - property.type.context?.annotations?.settingsSecretReference === true && - typeof property.name === "string" - ? [property.name] - : [], - ); + return schema.ast.propertySignatures.flatMap(({ name, type }) => { + if (typeof name !== "string") return []; + if (declaresSecretReference(type)) return [{ field: name, keyed: false }]; + return SchemaAST.isObjects(type) && + type.indexSignatures.some((signature) => declaresSecretReference(signature.type)) + ? [{ field: name, keyed: true }] + : []; + }); } -/** Each declared reference field of `settings` that holds a reference, in field order. */ +/** Where a reference sits: a field, or one key of a record field. */ +export interface SettingsSecretSlot { + readonly field: string; + readonly key: string | undefined; +} + +interface SettingsSecretReference extends SettingsSecretSlot { + readonly reference: SecretReference; +} + +/** Each declared reference slot of `settings` that holds a reference, in field order. */ export function secretReferencesInSettings( schema: Schema.Top, settings: unknown, -): ReadonlyArray<{ readonly field: string; readonly reference: SecretReference }> { +): ReadonlyArray { if (settings === null || typeof settings !== "object") return []; const values = settings as Readonly>; - return secretReferenceSettingsFields(schema).flatMap((field) => { - const value = values[field]; - return isSecretReference(value) ? [{ field, reference: value }] : []; - }); + return secretReferenceSettingsFields(schema).flatMap( + ({ field, keyed }) => { + const value = values[field]; + if (!keyed) + return isSecretReference(value) ? [{ field, key: undefined, reference: value }] : []; + if (value === null || typeof value !== "object") return []; + return Object.entries(value).flatMap(([key, entry]) => + isSecretReference(entry) ? [{ field, key, reference: entry }] : [], + ); + }, + ); +} + +/** `settings` with each slot set to its value, keeping the other keys of a record field. */ +export function withSettingsSecrets>>( + settings: Settings, + slots: ReadonlyArray, +): Settings { + const next: Record = { ...settings }; + for (const { field, key, value } of slots) { + next[field] = key === undefined ? value : { ...(next[field] as object), [key]: value }; + } + return next as Settings; } diff --git a/packages/source-control-core/src/shared/definition.ts b/packages/source-control-core/src/shared/definition.ts index 30e88377590f8..ed12267c25a09 100644 --- a/packages/source-control-core/src/shared/definition.ts +++ b/packages/source-control-core/src/shared/definition.ts @@ -3,6 +3,7 @@ import { type PullRequestReviewVerdict, type RepositoryIdentity, secretSetting, + SettingsSecretValue, SourceControlProviderKind, type SourceControlProviderInfo, TrimmedNonEmptyString, @@ -214,7 +215,7 @@ export const hostCredentialSettingsFields = { Schema.withDecodingDefault(Effect.succeed({})), Schema.annotateKey({ providerSettingsForm: { hidden: true } }), ), - tokens: Schema.Record(SourceControlHostName, TrimmedString).pipe( + tokens: Schema.Record(SourceControlHostName, SettingsSecretValue).pipe( Schema.withDecodingDefault(Effect.succeed({})), secretSetting, Schema.annotateKey({ providerSettingsForm: { hidden: true } }), diff --git a/packages/source-control-github/src/server/GitHubCredentials.ts b/packages/source-control-github/src/server/GitHubCredentials.ts index 41641790aac52..607e6ca00d1b1 100644 --- a/packages/source-control-github/src/server/GitHubCredentials.ts +++ b/packages/source-control-github/src/server/GitHubCredentials.ts @@ -16,7 +16,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition"; -import type { ServerSettings } from "@t3tools/contracts"; +import { settingsSecretLiteral, type ServerSettings } from "@t3tools/contracts"; import * as GitHubClient from "../shared/definition.ts"; @@ -194,8 +194,10 @@ export const make = Effect.gen(function* () { ); const savedToken = (host: string) => - sourceControlHost.settings.get.pipe( - Effect.map((settings) => readSettings(settings).tokens[host]?.trim() || null), + sourceControlHost.settings.getWithSecrets(GitHubClient.definition.kind).pipe( + Effect.map( + (settings) => settingsSecretLiteral(readSettings(settings).tokens[host]).trim() || null, + ), Effect.orElseSucceed(() => null), ); diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts index bc0438cf41b60..8583797a9688b 100644 --- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts +++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts @@ -1,4 +1,4 @@ -import { SourceControlProviderKind } from "@t3tools/contracts"; +import { settingsSecretLiteral, SourceControlProviderKind } from "@t3tools/contracts"; import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -225,7 +225,7 @@ export const makeDiscovery = Effect.gen(function* () { probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) { const settings = readSourceControlHostSettings( GitHubClient.settings, - yield* sourceControlHost.settings.get.pipe( + yield* sourceControlHost.settings.getWithSecrets(GitHubClient.definition.kind).pipe( Effect.map((current) => current.sourceControlHosts[GitHubClient.definition.kind]), Effect.orElseSucceed(() => undefined), ), @@ -237,7 +237,8 @@ export const makeDiscovery = Effect.gen(function* () { }, spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) }, }); - const savedToken = (settings.tokens["github.com"] ?? "").trim() !== ""; + const token = settings.tokens["github.com"]; + const savedToken = settingsSecretLiteral(token).trim() !== ""; const signedIn = appSignIn.enabled && !savedToken && (settings.signIns["github.com"] ?? "").trim() !== ""; const variable = environmentTokenVariable(environment); diff --git a/packages/source-control-github/src/server/gitHubDiscovery.test.ts b/packages/source-control-github/src/server/gitHubDiscovery.test.ts index cd8a838b23723..b108d71f75584 100644 --- a/packages/source-control-github/src/server/gitHubDiscovery.test.ts +++ b/packages/source-control-github/src/server/gitHubDiscovery.test.ts @@ -1,10 +1,14 @@ -import { SourceControlProviderKind } from "@t3tools/contracts"; +import { ServerSettings, SourceControlProviderKind } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; import * as GitHubCredentials from "./GitHubCredentials.ts"; import * as GitHubAppSignIn from "./GitHubAppSignIn.ts"; @@ -79,3 +83,79 @@ it.effect("asks for no credential when the identity resolver left the base URL e assert.deepStrictEqual(hosts, []); }), ); + +const decodeSettings = Schema.decodeSync(ServerSettings); +const referencedTokenSettings = decodeSettings({ + sourceControlHosts: { + github: { tokens: { "github.com": { provider: "vault", reference: "op://v/gh" } } }, + }, +}); + +it.effect.each([ + { name: "readable", token: "resolved-token", source: "the token saved in Settings" }, + { name: "unreadable", token: "", source: "GH_TOKEN from the server environment" }, +])("checks the $name GitHub token reference against the API", (scenario) => + Effect.gen(function* () { + const paths: Array = []; + const discovery = yield* GitHubSourceControlProvider.makeDiscovery.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(GitHubRest.GitHubRest)({ + rest: (input) => { + paths.push(input.path); + return Effect.succeed({ + status: 200, + headers: {}, + body: JSON.stringify({ login: "octocat" }), + truncated: false, + invalidUtf8: false, + }); + }, + }), + Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({ enabled: false }), + Layer.effect( + SourceControlHost.SourceControlHost, + Effect.gen(function* () { + const host = yield* SourceControlHost.SourceControlHost; + return { + ...host, + settings: { + ...host.settings, + getWithSecrets: () => + Effect.succeed( + decodeSettings({ + sourceControlHosts: { + github: { tokens: { "github.com": scenario.token } }, + }, + }), + ), + }, + }; + }), + ).pipe( + Layer.provide( + TestSourceControlHost.layer({ + settings: referencedTokenSettings, + process: { + run: () => + Effect.succeed( + TestSourceControlHost.processOutput("", { + exitCode: ChildProcessSpawner.ExitCode(1), + }), + ), + }, + }), + ), + ), + ), + ), + Effect.provideService(HostProcess.Environment, { GH_TOKEN: "environment-token" }), + ); + if (discovery.type !== "managed-cli") return assert.fail("expected a managed CLI"); + const item = yield* discovery.probe("/repo"); + assert.deepStrictEqual(paths, ["user"]); + assert.strictEqual(item.auth.status, "authenticated"); + assert.deepStrictEqual(item.auth.account, Option.some("octocat")); + assert.include(Option.getOrThrow(item.auth.detail), scenario.source); + }), +); From a497f7b9a3efab4d0c41c9eabaeea775d751e6e7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 11:43:38 -0800 Subject: [PATCH 045/163] fix(web): confirm before removing a provider instance's saved settings (#29480) Co-authored-by: Claude Opus 5.5 --- ...SettingsPanel.environment.browser.test.tsx | 94 +++++++++++++++++++ .../settings/ProviderSettingsPanel.tsx | 40 +++++++- 2 files changed, 130 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx index 79322dc5ff6ee..3e6cbb5fbf79b 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.environment.browser.test.tsx @@ -36,6 +36,7 @@ const state = vi.hoisted(() => ({ updateModelPreferences: vi.fn(), toggleFavorite: vi.fn(), mutateProviderInstance: vi.fn(), + confirm: vi.fn<() => Promise>(), })); vi.mock(import("../../state/server"), async (original) => { @@ -80,6 +81,14 @@ vi.mock(import("../../state/use-atom-command"), async (original) => ({ "accept-url-auth": state.acceptUrlAuth, })[command.label ?? ""] ?? vi.fn()) as never, })); +vi.mock(import("~/localApi"), async (original) => { + const api = { dialogs: { confirm: state.confirm } }; + return { + ...(await original()), + readLocalApi: (() => api) as never, + ensureLocalApi: (() => api) as never, + }; +}); vi.mock(import("../../state/query"), async (original) => ({ ...(await original()), useEnvironmentQuery: ((query: unknown) => ({ @@ -231,6 +240,7 @@ async function setup() { state.updateModelPreferences.mockReset(); state.toggleFavorite.mockReset(); state.mutateProviderInstance.mockReset().mockResolvedValue(AsyncResult.success({})); + state.confirm.mockReset().mockResolvedValue(false); state.refresh.mockReset().mockResolvedValue(AsyncResult.success(undefined)); state.updateProvider.mockReset().mockResolvedValue(AsyncResult.success(undefined)); state.uninstall.mockReset().mockResolvedValue(AsyncResult.success({})); @@ -359,6 +369,90 @@ describe("EnvironmentProviderSettings routing", () => { }); }); +describe("EnvironmentProviderSettings instance removal", () => { + it("resets a configured default instance only once the user confirms", async () => { + await setup(); + state.settings = { + ...DEFAULT_UNIFIED_SETTINGS, + providerInstances: { + [codexId]: { + driver: ProviderDriverKind.make("codex"), + enabled: true, + config: { binaryPath: "/opt/codex/bin/codex" }, + }, + }, + }; + await setProviders([provider()]); + await using _screen = await render(panel({ targetInstanceId: codexId })); + const reset = page.getByRole("button", { name: "Reset Codex provider settings to default" }); + await userEvent.click(reset); + + expect(state.mutateProviderInstance).not.toHaveBeenCalled(); + expect(state.confirm).toHaveBeenCalledOnce(); + + state.confirm.mockResolvedValue(true); + await userEvent.click(reset); + await vi.waitFor(() => + expect(state.mutateProviderInstance).toHaveBeenCalledWith({ + operation: "remove", + instanceId: codexId, + }), + ); + }); + + it("warns that resetting an enabled default-off provider turns it off", async () => { + await setup(); + const antigravityId = ProviderInstanceId.make("antigravity"); + const antigravity = ProviderDriverKind.make("antigravity"); + state.settings = { + ...DEFAULT_UNIFIED_SETTINGS, + providerInstances: { + [antigravityId]: { + driver: antigravity, + enabled: true, + config: { binaryPath: "/opt/antigravity/bin/agy" }, + }, + }, + }; + await setProviders([{ ...provider(), instanceId: antigravityId, driver: antigravity }]); + await using _screen = await render(panel({ targetInstanceId: antigravityId })); + await userEvent.click(page.getByRole("button", { name: /^Reset .* provider settings/ })); + + expect(state.confirm).toHaveBeenCalledWith( + expect.stringContaining("It will also be turned off."), + { + variant: "destructive", + }, + ); + expect(state.mutateProviderInstance).not.toHaveBeenCalled(); + }); + + it("deletes a custom instance only once the user confirms", async () => { + await setup(); + state.settings = { + ...DEFAULT_UNIFIED_SETTINGS, + providerInstances: { + [customId]: { driver: ProviderDriverKind.make("codex"), enabled: true }, + }, + }; + await using _screen = await render(panel({ targetInstanceId: customId })); + const remove = page.getByRole("button", { name: `Delete instance ${customId}` }); + await userEvent.click(remove); + + expect(state.mutateProviderInstance).not.toHaveBeenCalled(); + expect(state.confirm).toHaveBeenCalledOnce(); + + state.confirm.mockResolvedValue(true); + await userEvent.click(remove); + await vi.waitFor(() => + expect(state.mutateProviderInstance).toHaveBeenCalledWith({ + operation: "remove", + instanceId: customId, + }), + ); + }); +}); + describe("EnvironmentProviderSettings health check interval", () => { it("commits interval drafts and allows retrying rejected edits", async () => { await setup(); diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx index 5585a062dd652..fca8b88925e96 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx @@ -11,6 +11,7 @@ import { connectionStatusTitle } from "@t3tools/client-runtime/connection"; import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; import { isAtomCommandInterrupted, + settlePromise, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { @@ -47,6 +48,7 @@ import { useToggleEnvironmentModelFavorite, } from "../../hooks/useSettings"; import { useStableCallback } from "../../hooks/useStableCallback"; +import { ensureLocalApi } from "../../localApi"; import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { cn } from "../../lib/utils"; import { resolveAppModelSelectionState } from "../../modelSelection"; @@ -127,6 +129,25 @@ import { resolveSelectedProviderEnvironmentId, } from "./ProviderSettingsPanel.logic"; +function providerInstanceName(instance: ProviderInstanceConfig): string { + return ( + instance.displayName?.trim() || + providerClients.get(instance.driver)?.label || + String(instance.driver) + ); +} + +async function confirmProviderInstanceRemoval( + question: string, + consequence = "", +): Promise { + const message = `${question}\nIts saved settings, including any custom binary path, will be removed.${consequence}`; + const confirmed = await settlePromise(() => + ensureLocalApi().dialogs.confirm(message, { variant: "destructive" }), + ); + return confirmed._tag === "Success" && confirmed.value; +} + function modelListChanges(current: ReadonlyArray, next: ReadonlyArray) { const currentSet = new Set(current); const nextSet = new Set(next.map((model) => model.trim()).filter(Boolean)); @@ -830,6 +851,10 @@ export function EnvironmentProviderSettings({ const deleteInstance = useStableCallback( async (instanceId: ProviderInstanceId, instance: ProviderInstanceConfig) => { + const confirmed = await confirmProviderInstanceRemoval( + `Remove the ${providerInstanceName(instance)} provider instance?`, + ); + if (!confirmed) return; const updateResult = await persistProviderInstance({ operation: "remove", instanceId, @@ -866,10 +891,17 @@ export function EnvironmentProviderSettings({ ); const resetDefaultInstance = useStableCallback(async (driverKind: ProviderDriverKind) => { - const result = await persistProviderInstance({ - operation: "remove", - instanceId: defaultInstanceIdForDriver(driverKind), - }); + const instanceId = defaultInstanceIdForDriver(driverKind); + const instance = settings.providerInstances?.[instanceId] ?? { driver: driverKind }; + const turnsOff = + resolveProviderInstanceEnabled(instance) && + !resolveProviderInstanceEnabled({ driver: driverKind }); + const confirmed = await confirmProviderInstanceRemoval( + `Reset the ${providerInstanceName(instance)} provider to its defaults?`, + turnsOff ? " It will also be turned off." : "", + ); + if (!confirmed) return; + const result = await persistProviderInstance({ operation: "remove", instanceId }); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); toastManager.add({ From 3ddd3989e03e44c0106c6e3e44033a2f5b8b50ae Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 11:44:20 -0800 Subject: [PATCH 046/163] fix(server): settled threads no longer re-send relay clears on every PR update (#29369) Co-authored-by: Claude Opus 5.5 --- .../src/relay/AgentAwarenessRelay.test.ts | 107 ++++++++++++++++++ apps/server/src/relay/AgentAwarenessRelay.ts | 38 ++++--- 2 files changed, 129 insertions(+), 16 deletions(-) diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 4bbaa85fc3b16..2a259114b0926 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -482,6 +482,113 @@ describe("AgentAwarenessRelay", () => { }), ); + it.effect("publishes a cleared thread's tombstone once while it stays cleared", () => + Effect.gen(function* () { + const { relay, currentShell, publications } = yield* makeTestRelay(); + yield* relay.publishThread(THREAD_ID); + const completed = shell({ status: "completed" }); + yield* Ref.set(currentShell, completed); + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + yield* Ref.set(currentShell, { + ...completed, + settledOverride: "settled", + settledAt: yield* DateTime.now, + lastVisitedAt: null, + }); + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + assert.deepEqual( + publications.map((publication) => publication.state?.phase ?? null), + ["running", "completed", null], + ); + + for (let i = 0; i < 3; i++) { + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + } + assert.deepEqual( + publications.map((publication) => publication.state?.phase ?? null), + ["running", "completed", null], + ); + }), + ); + + it.effect("does not alert an old completion after publishing its thread's tombstone", () => + Effect.gen(function* () { + const oldCompleted = shell({ + status: "completed", + latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T11:59:00.000Z"), + }); + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe(NOW))); + const { relay, currentShell, publications } = yield* makeTestRelay(); + yield* Ref.set(currentShell, { + ...oldCompleted, + settledOverride: "settled", + settledAt: DateTime.makeUnsafe(NOW), + lastVisitedAt: null, + }); + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + assert.deepEqual( + publications.map((publication) => publication.state), + [null], + ); + + yield* Ref.set(currentShell, oldCompleted); + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + assert.deepEqual( + publications.map((publication) => publication.state), + [null], + ); + }), + ); + + it.effect("alerts a completion settled during its hold after an earlier tombstone", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe(NOW))); + const { relay, currentShell, publications } = yield* makeTestRelay(); + const settledAt = DateTime.makeUnsafe(NOW); + yield* Ref.set(currentShell, { + ...shell({ status: "completed" }), + settledOverride: "settled", + settledAt, + lastVisitedAt: null, + }); + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + + const completed = shell({ + status: "completed", + latestRunCompletedAt: DateTime.makeUnsafe("2026-09-04T12:00:06.000Z"), + }); + yield* Ref.set(currentShell, completed); + yield* relay.publishThread(THREAD_ID); + yield* Ref.set(currentShell, { + ...completed, + settledOverride: "settled", + settledAt, + lastVisitedAt: null, + }); + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + assert.deepEqual( + publications.map((publication) => publication.state?.phase ?? null), + [null, "completed", null], + ); + }), + ); + it.effect("drops a held completion when a queued continuation hides the thread", () => Effect.gen(function* () { const { relay, currentShell, publications } = yield* makeTestRelay(); diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index 66e5a3def7c07..076afc92d733a 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -165,6 +165,17 @@ function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): s return JSON.stringify(meaningfulState); } +const CLEARED_PUBLISH_IDENTITY = agentAwarenessPublishIdentity(null); + +// A published tombstone stays recorded so repeats are skipped, but it is not live state. +function hasLivePublishedState( + publishedStateByThread: ReadonlyMap, + threadId: ThreadId, +): boolean { + const identity = publishedStateByThread.get(threadId); + return identity !== undefined && identity !== CLEARED_PUBLISH_IDENTITY; +} + function resolveAgentActivityPublishingStartupState(input: { readonly relayConfigured: boolean; readonly publishEnabled: boolean; @@ -517,7 +528,7 @@ export const make = Effect.gen(function* () { if ( threadShell !== null && !isListedThreadLineage(threadShell.lineage) && - !(yield* Ref.get(publishedStateByThreadRef)).has(threadId) + !hasLivePublishedState(yield* Ref.get(publishedStateByThreadRef), threadId) ) { // Subagents and side chats have no relay rows to clear; per-event tombstones would needlessly redeliver user aggregates. return; @@ -538,11 +549,15 @@ export const make = Effect.gen(function* () { const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef); if ( (snapshot.state?.phase === "completed" || snapshot.state?.phase === "failed") && - !publishedStateByThread.has(threadId) + !hasLivePublishedState(publishedStateByThread, threadId) ) { if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return; } - if (publishedStateByThread.get(threadId) === publishIdentity) { + if ( + publishedStateByThread.get(threadId) === publishIdentity && + // A held completion settled after an earlier clear still has to alert. + !(snapshot.state === null && heldCompletions.has(threadId)) + ) { // Clear moot deadlines so later transient nulls cannot skip their deferral window. publishConfirmDeadlines.delete(threadId); heldCompletions.delete(threadId); @@ -557,10 +572,7 @@ export const make = Effect.gen(function* () { // Confirm tombstones over live state to avoid removing active cards. // Confirm completion: a run can end moments before its continuation starts, and the relay // alerts on every move into completed. - const requiresConfirmation = - (snapshot.state === null && - publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) || - snapshot.state?.phase === "completed"; + const requiresConfirmation = snapshot.state === null || snapshot.state?.phase === "completed"; if (requiresConfirmation) { if (snapshot.state?.phase === "completed") heldCompletions.add(threadId); const nowMs = (yield* DateTime.now).epochMilliseconds; @@ -640,15 +652,9 @@ export const make = Effect.gen(function* () { }).pipe(withRelayClientTracing); publishConfirmDeadlines.delete(threadId); heldCompletions.delete(threadId); - yield* Ref.update(publishedStateByThreadRef, (publishedStates) => { - const nextPublishedStates = new Map(publishedStates); - if (snapshot.state === null) { - nextPublishedStates.delete(threadId); - } else { - nextPublishedStates.set(threadId, publishIdentity); - } - return nextPublishedStates; - }); + yield* Ref.update(publishedStateByThreadRef, (publishedStates) => + new Map(publishedStates).set(threadId, publishIdentity), + ); }); const processThreadPublish = Effect.fnUntraced(function* (threadId: ThreadId) { From a821f039c159174b08aab8d1f39b5c8e588d416e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 11:45:45 -0800 Subject: [PATCH 047/163] fix(client-runtime): connection diagnosis no longer blames the host while this device's sign-in loads (#29352) Co-authored-by: Claude Opus 5.5 --- docs/user/t3-connect-troubleshooting.md | 6 ++- .../src/connection/diagnosis.test.ts | 26 ++++++++++++ .../src/connection/diagnosis.ts | 41 ++++++++++++++++--- 3 files changed, 67 insertions(+), 6 deletions(-) diff --git a/docs/user/t3-connect-troubleshooting.md b/docs/user/t3-connect-troubleshooting.md index 27af390b81ef8..4abe8bcc5d163 100644 --- a/docs/user/t3-connect-troubleshooting.md +++ b/docs/user/t3-connect-troubleshooting.md @@ -99,7 +99,8 @@ Fix: ## Sign-in, account, or link problems -T3 Connect does not have an active link between your account and the host. +This device's T3 Connect sign-in is not ready yet, or T3 Connect does not have +an active link between your account and the host. - **The host is linked to a different account.** Sign in to the same T3 Connect account on this device and on the host. On the host, run `t3 connect logout`, @@ -111,6 +112,9 @@ T3 Connect does not have an active link between your account and the host. `t3 service restart` on the host, or restart `t3 serve`. - **This device's sign-in expired, or the host no longer accepts this device.** Sign out of T3 Connect and sign in again. +- **This device is still loading its T3 Connect sign-in.** Wait a moment; + T3 Code retries on its own. If it keeps waiting, reload or restart T3 Code on + this device. - **Your account reached its tunnel limit.** Remove an environment you do not use from your T3 account's T3 Connect page, or [link a paid T3 Chat account](./remote-access.md#more-machines-with-t3-chat) diff --git a/packages/client-runtime/src/connection/diagnosis.test.ts b/packages/client-runtime/src/connection/diagnosis.test.ts index 5d396888eb593..93cc54bd044d0 100644 --- a/packages/client-runtime/src/connection/diagnosis.test.ts +++ b/packages/client-runtime/src/connection/diagnosis.test.ts @@ -8,6 +8,8 @@ import { presentConnectionDiagnosis } from "./diagnosis.ts"; import { mapManagedRelayError, mapRemoteEnvironmentError } from "./errors.ts"; import { AVAILABLE_CONNECTION_STATE, + ConnectionBlockedError, + ConnectionTransientError, type ConnectionAttemptError, type SupervisorConnectionState, } from "./model.ts"; @@ -128,6 +130,30 @@ describe("presentConnectionDiagnosis", () => { expect(origin?.hops.map((hop) => hop.hop)).toEqual(["device", "relay", "tunnel", "server"]); }); + it("blames this device, not the host, while its own T3 Connect sign-in loads", () => { + const failure = new ConnectionTransientError({ + reason: "session-pending", + detail: "Waiting for the T3 Connect sign-in to load.", + }); + const diagnosis = diagnose(backoff(failure)); + expect(diagnosis?.headline).not.toContain("did not answer"); + expect(diagnosis?.hops.find((hop) => hop.result === "failed")?.hop).toBe("device"); + expect(diagnosis?.steps.join(" ")).not.toContain("Mac mini"); + expect(diagnosis?.moreInfoUrl).toContain("sign-in-account-or-link-problems"); + // A host with a LAN route as well uses the direct route, still authorized through T3 Connect. + expect(diagnose(backoff(failure), "direct")?.moreInfoUrl).toContain( + "sign-in-account-or-link-problems", + ); + }); + + it("does not report hops as working when the failure names none", () => { + const failure = new ConnectionBlockedError({ + reason: "authentication", + detail: "Your cloud sign-in changed. Sign in again to authorize the environment.", + }); + expect(results(backoff(failure))).not.toContainEqual(expect.stringMatching(/:ok$/)); + }); + it("keeps the relay health status out of a failure that has its own cause", () => { const failure = mapRemoteEnvironmentError( new RemoteEnvironmentAuthFetchError({ message: "Failed to fetch", cause: new TypeError() }), diff --git a/packages/client-runtime/src/connection/diagnosis.ts b/packages/client-runtime/src/connection/diagnosis.ts index a3de100766a7c..4272943e0daa9 100644 --- a/packages/client-runtime/src/connection/diagnosis.ts +++ b/packages/client-runtime/src/connection/diagnosis.ts @@ -26,7 +26,7 @@ export interface ConnectionDiagnosis { readonly hops: ReadonlyArray; readonly steps: ReadonlyArray; readonly facts: ReadonlyArray; - /** The troubleshooting guide section for this failure. Null for direct routes. */ + /** The troubleshooting guide section for this failure. Null for direct routes, except a pending T3 Connect sign-in. */ readonly moreInfoUrl: string | null; } @@ -46,7 +46,15 @@ export interface ConnectionDiagnosisInput { interface Located { readonly hop: ConnectionHop; - readonly cause: ConnectionFailureCause | "offline" | "outdated" | "released" | null; + readonly cause: + | ConnectionFailureCause + | "offline" + | "outdated" + | "released" + | "session_pending" + | null; + /** The failure named no hop, so the hops before this one were never probed. */ + readonly guessed?: true; } const NOT_ANSWERING: ReadonlySet = new Set([ @@ -62,6 +70,9 @@ function locate(input: ConnectionDiagnosisInput): Located | null { if (failure?._tag === "ConnectionBlockedError" && failure.serverUpdateRequired) { return { hop: "server", cause: "outdated" }; } + if (failure?.reason === "session-pending") { + return { hop: "device", cause: "session_pending" }; + } if (failure?.hop !== undefined) { return { hop: failure.hop, cause: failure.failureCause ?? null }; } @@ -71,7 +82,11 @@ function locate(input: ConnectionDiagnosisInput): Located | null { failure.reason === "timeout" || failure.reason === "transport"; const via = failure.via ?? input.via; - return { hop: unreachable && via === "relay" ? "tunnel" : "server", cause: null }; + return { + hop: unreachable && via === "relay" ? "tunnel" : "server", + cause: null, + guessed: true, + }; } const status = input.relayStatus; if (status?.status !== "offline") return null; @@ -84,6 +99,8 @@ function headline(host: string, located: Located, failure: ConnectionAttemptErro switch (located.cause) { case "offline": return "This device is offline"; + case "session_pending": + return "This device is still loading its T3 Connect sign-in"; case "outdated": return `${host} runs an older T3 Code`; case "clock_skew": @@ -141,6 +158,11 @@ function steps(host: string, located: Located, failure: ConnectionAttemptError | switch (located.cause) { case "offline": return ["Connect this device to the internet. T3 Code reconnects on its own."]; + case "session_pending": + return [ + "Wait a moment. T3 Code retries on its own.", + "If it keeps waiting, reload or restart T3 Code on this device.", + ]; case "outdated": return [`Update T3 Code on ${host}.`]; case "clock_skew": @@ -220,6 +242,7 @@ function helpSection( return "the-host-runs-an-older-t3-code"; case "clock_skew": return "the-clock-is-off"; + case "session_pending": case "not_linked": case "tunnel_not_enabled": return "sign-in-account-or-link-problems"; @@ -300,7 +323,12 @@ export function presentConnectionDiagnosis( const hops = order.map((hop, index): ConnectionDiagnosisHop => ({ hop, label: hopLabel(hop, host), - result: index < failedIndex ? "ok" : index === failedIndex ? "failed" : "unchecked", + result: + index === failedIndex + ? "failed" + : index < failedIndex && located.guessed !== true + ? "ok" + : "unchecked", })); // The relay health check only explains the state when no attempt has failed yet. @@ -329,7 +357,10 @@ export function presentConnectionDiagnosis( hops, steps: steps(host, located, failure), facts, - moreInfoUrl: relayPath ? t3ConnectTroubleshootingUrl(helpSection(located, failure)) : null, + moreInfoUrl: + relayPath || located.cause === "session_pending" + ? t3ConnectTroubleshootingUrl(helpSection(located, failure)) + : null, }; } From 6f41364805e31a1f8d59c18c7cc451630cd9265d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 11:47:24 -0800 Subject: [PATCH 048/163] fix(opencode): Claude usage limits through OpenCode keep their reset time (#29301) Co-authored-by: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 45 +++++++++++++++++++ .../src/server/v2/adapter.ts | 12 ++++- 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index b4c319e8e9a96..bb52bb92daea3 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -563,6 +563,22 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { status: 429, }, }, + { + name: "a Claude limit without a reset timestamp", + failureClass: "usage_limit", + error: { + type: "provider.unknown", + message: "You've hit your session limit · resets 5:20pm (Europe/Berlin)", + }, + }, + { + name: "an unrelated provider.unknown failure", + failureClass: "provider_error", + error: { + type: "provider.unknown", + message: "Request failed. Resets at 2026-11-02T20:00:00Z.", + }, + }, ] as const)("classifies $name as $failureClass", ({ error, failureClass }) => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ @@ -583,6 +599,35 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + // regression: #29289 Claude weekly limits through claude-agent lost their usage-limit reset + it.effect( + "classifies a Claude weekly limit as a usage limit that resets at its reported time", + () => + Effect.gen(function* () { + const message = + "You've hit your weekly limit · resets 9pm (Europe/Paris) Resets at 2026-11-02T20:00:00.000Z."; + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.failed", { + sessionID: SESSION, + error: { type: "provider.unknown", message }, + }), + ]); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.startTurn(turnInput(thread)); + const ended = yield* Fiber.join(terminal); + assert.equal(ended?.status, "failed"); + assert.deepEqual(ended?.failure, { + class: "usage_limit", + code: "provider.unknown", + message, + retryable: null, + resetAt: "2026-11-02T20:00:00.000Z", + }); + }).pipe(Effect.scoped), + ); + it.effect("ends the turn when its terminal event is one this build cannot decode", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index f49de61b24690..ae74eb2908e86 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -524,6 +524,12 @@ const wakeTurnId = (sessionId: string, attemptId: string) => `${sessionId}:wake: const isWakeTurn = (turn: OrchestrationV2ProviderTurn) => turn.nativeTurnRef?.nativeId?.includes(":wake:") === true; +// OpenCode's claude-agent reports a spent Claude plan as provider.unknown with Claude's own text. +const claudeUsageLimit = (message: string | undefined) => + message !== undefined && /^You've hit your [^\n·]*\blimit\b/.test(message) + ? { resetAt: /\bResets at (\d{4}-\d\d-\d\dT[\d:.]+Z)\.?\s*$/.exec(message)?.[1] ?? null } + : undefined; + const INTERRUPT_TIMEOUT = "10 seconds"; const INSTRUCTIONS_KEY = "t3-code"; const RECONNECT_ATTEMPTS = 5; @@ -2152,14 +2158,18 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const { type, message, status, response } = event.data.error; // OpenCode types an empty balance as provider.quota too, but it answers // that with HTTP 402 and it never resets. Usage windows and budgets are 429. + const claudeLimit = claudeUsageLimit(message); const usageLimit = - (type === "provider.quota" && status !== 402) || type === "provider.rate-limit"; + (type === "provider.quota" && status !== 402) || + type === "provider.rate-limit" || + claudeLimit !== undefined; return yield* endExecution(state, turn, { status: "failed", failure: makeProviderFailure({ message: readableProviderErrorMessage(message, status, response?.body), code: type, class: usageLimit ? "usage_limit" : "provider_error", + resetAt: claudeLimit?.resetAt ?? null, }), }); } From bdf5806dfcf31e6fd3ce4d8d028e262f4fe6d7e3 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 2 Nov 2026 14:26:27 -0600 Subject: [PATCH 049/163] fix(desktop): prepare macOS x64 bytecode under Rosetta (#29484) --- .github/workflows/release-desktop.yml | 8 ++++ docs/operations/development.md | 5 +- scripts/lib/server-compile-cache.test.ts | 61 ++++++++++++++++++++++++ scripts/prepare-server-compile-cache.cjs | 10 +++- 4 files changed, 81 insertions(+), 3 deletions(-) diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 5a16a9b4c170f..3af4e6abeafe9 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -203,6 +203,14 @@ jobs: native/hyprland-snap-shot/target/${{ inputs.rust_target }}/release/t3-hyprland-snap-shot key: linux-capture-helpers-${{ inputs.rust_target }}-${{ hashFiles('native/kde-snap-shot/Cargo.lock', 'native/kde-snap-shot/Cargo.toml', 'native/kde-snap-shot/src/**', 'native/hyprland-snap-shot/Cargo.lock', 'native/hyprland-snap-shot/Cargo.toml', 'native/hyprland-snap-shot/src/**', 'native/hyprland-snap-shot/protocols/**') }} + - name: Ensure Rosetta for macOS x64 bytecode generation + if: inputs.platform == 'mac' && inputs.arch == 'x64' + shell: bash + run: | + if [[ "$(uname -m)" == "arm64" ]] && ! /usr/bin/arch -x86_64 /usr/bin/true; then + sudo /usr/sbin/softwareupdate --install-rosetta --agree-to-license + fi + - name: Setup Rust if: steps.resource_monitor_cache.outputs.cache-hit != 'true' || (inputs.platform == 'linux' && steps.capture_helper_cache.outputs.cache-hit != 'true') uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable diff --git a/docs/operations/development.md b/docs/operations/development.md index ea7f10a6ba2dd..131b279fab683 100644 --- a/docs/operations/development.md +++ b/docs/operations/development.md @@ -265,8 +265,9 @@ options. Native macOS and Windows desktop artifact builds generate server bytecode with the packaged Electron executable, after ASAR creation and before signing. Linux builds skip generation until -native packaging and relocated AppImage reuse have been validated. Cross-platform and -cross-architecture builds also skip generation explicitly. CLI, SEA and WSL runtimes keep their +native packaging and relocated AppImage reuse have been validated. macOS x64 builds on ARM64 +hosts run the packaged x64 Electron under Rosetta to generate the cache. Other cross-platform and +cross-architecture builds skip generation explicitly. CLI, SEA and WSL runtimes keep their existing behavior; only desktop backend imports covered by generation receive prepared bytecode. Worker-only modules compile normally. diff --git a/scripts/lib/server-compile-cache.test.ts b/scripts/lib/server-compile-cache.test.ts index bb9294c54219c..9853d4aed85fb 100644 --- a/scripts/lib/server-compile-cache.test.ts +++ b/scripts/lib/server-compile-cache.test.ts @@ -25,6 +25,67 @@ it.each(["x64", "arm64"])("skips prepared bytecode generation on Linux %s", asyn expect(result.stdout).toContain("Skipping unsupported target linux"); }); +it("prepares macOS x64 cache on an ARM64 build host", async () => { + const { spawnSync } = await import("node:child_process"); + const root = NodeFS.realpathSync( + NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-rosetta-cache-")), + ); + try { + const resources = NodePath.join(root, "Fixture.app", "Contents", "Resources"); + const archive = NodePath.join(resources, "app.asar"); + const dist = NodePath.join(archive, "apps/server/dist"); + const helper = NodePath.join(archive, "apps/desktop/dist-electron/serverCompileCache.cjs"); + NodeFS.mkdirSync(dist, { recursive: true }); + NodeFS.mkdirSync(NodePath.dirname(helper), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(dist, "binCli-fixture.mjs"), "export const answer = 42;"); + NodeFS.writeFileSync( + helper, + `module.exports = require(${JSON.stringify(NodeURL.fileURLToPath(new URL("./server-compile-cache.ts", import.meta.url)))});`, + ); + const hook = NodeURL.fileURLToPath( + new URL("../prepare-server-compile-cache.cjs", import.meta.url), + ); + // The fixture uses Node for generation; the hook still sees an ARM64 macOS build host. + const result = spawnSync( + process.execPath, + [ + "-e", + ` + const childProcess = require("node:child_process"); + const spawn = childProcess.spawnSync; + childProcess.spawnSync = (executable, args, options) => { + require("node:assert/strict").equal(executable, ${JSON.stringify(NodePath.join(root, "Fixture.app", "Contents", "MacOS", "Fixture"))}); + return spawn(process.execPath, args, options); + }; + Object.defineProperty(process, "platform", { value: "darwin" }); + Object.defineProperty(process, "arch", { value: "arm64" }); + require(${JSON.stringify(hook)})({ + appOutDir: ${JSON.stringify(root)}, electronPlatformName: "darwin", arch: 1, + packager: { appInfo: { productFilename: "Fixture" } } + }).catch(error => { console.error(error); process.exitCode = 1; }); + `, + ], + { encoding: "utf8" }, + ); + expect(result.status, result.stderr).toBe(0); + const manifest = JSON.parse( + NodeFS.readFileSync(NodePath.join(resources, "server-compile-cache/manifest.json"), "utf8"), + ); + expect(manifest.entries).toEqual([ + { + module: "app.asar/apps/server/dist/binCli-fixture.mjs", + file: expect.stringMatching(/^[a-f0-9]{8}$/), + }, + ]); + expect( + NodeFS.statSync(NodePath.join(resources, "server-compile-cache", manifest.entries[0].file)) + .size, + ).toBeGreaterThan(0); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } +}); + it("seeds relocated cache entries without allowing writes into shipped resources", () => { const root = NodeFS.realpathSync( NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-prepared-test-")), diff --git a/scripts/prepare-server-compile-cache.cjs b/scripts/prepare-server-compile-cache.cjs index 1c4b886d115ac..673d9cc29f2a2 100644 --- a/scripts/prepare-server-compile-cache.cjs +++ b/scripts/prepare-server-compile-cache.cjs @@ -12,7 +12,15 @@ module.exports = async ({ appOutDir, electronPlatformName, arch, packager }) => return; } const targetArch = ["ia32", "x64", "armv7l", "arm64", "universal"][arch]; - if (electronPlatformName !== process.platform || targetArch !== process.arch) { + const runsWithRosetta = + electronPlatformName === "darwin" && + process.platform === "darwin" && + process.arch === "arm64" && + targetArch === "x64"; + if ( + electronPlatformName !== process.platform || + (targetArch !== process.arch && !runsWithRosetta) + ) { console.log( `[server-compile-cache] Skipping unexecutable target ${electronPlatformName}/${targetArch}`, ); From cc59f99e735300120a6fc74d9a0b9df7c98fa81c Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Mon, 2 Nov 2026 14:26:35 -0600 Subject: [PATCH 050/163] fix(server): keep PR watches active after host failures (#29450) ## Problem PR watches stopped after eight failed host reads, so a prolonged network outage prevented later CI and review updates from reaching the thread. ## Change Keep watches active after provider failures reported as `failed`. Read detail and activity concurrently without allowing an activity failure to cancel or hide a permanent detail failure. Repeated known permanent failures still stop the watch and notify the agent; rate limits still pause reads. Non-rate-limited GitHub HTTP 403 responses and GraphQL `FORBIDDEN` responses now use a distinct `forbidden` reason so access refusals are counted instead of retried indefinitely. GraphQL error types survive the client mapping, after the existing requested-reviewer fallback. The provider's `failed` category also includes unclassified host and decode errors. Those continue retrying at the existing two-minute cadence until the watch ends or is stopped. A fixed outage deadline would recreate the recovery failure for longer outages. ## Scope and approval This is a focused fix for an obvious bug in existing PR watch recovery, covered by the small bug-fix exception in CONTRIBUTING.md. The changes cover watcher recovery, a GitHub failure classification needed to preserve permanent-error handling, and their regression tests. The new server-side `forbidden` reason does not change RPC contracts or add settings. ## Verification `vp run check:changed` passed, including 154 tests across five files. Regression coverage includes a 30-minute outage followed by one CI-success notification, mixed activity/detail failures, resetting a prior failure count, and repeated forbidden reads stopping the watch. Provider tests distinguish HTTP 403 and exclusively permanent GraphQL refusals from retryable HTTP 503 and mixed or untyped GraphQL errors. The mixed-failure and GraphQL classification cases failed before their fixes. Seven focused requested-reviewer fallback/refusal tests also pass. Model: GPT 6.1 Sol. Harness: Codex. --- .../PullRequestWatchReactor.ts | 40 ++-- .../src/orchestration-v2/runtimeLayer.test.ts | 201 +++++++++++++----- .../src/server/PullRequestProvider.ts | 1 + .../server/GitHubPullRequestProvider.test.ts | 38 ++++ .../src/server/GitHubPullRequestProvider.ts | 9 + .../src/server/GitHubRequestPolicy.ts | 1 + .../src/server/gitHubGraphQlClient.test.ts | 4 +- .../src/server/gitHubGraphQlClient.ts | 3 + 8 files changed, 228 insertions(+), 69 deletions(-) diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 62a2cb09220c6..ab141dcbc1437 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -50,13 +50,13 @@ const FINGERPRINT_REREAD_MS = 30 * 60_000; const isProviderError = Schema.is(PullRequestProviderError); -const isRateLimited = (cause: Cause.Cause) => +const providerFailureReason = (cause: Cause.Cause) => Option.match(Cause.findErrorOption(cause), { - onNone: () => false, + onNone: () => null, onSome: (error) => - error._tag === "PullRequestOperationError" && - isProviderError(error.cause) && - error.cause.reason === "rate-limited", + error._tag === "PullRequestOperationError" && isProviderError(error.cause) + ? error.cause.reason + : null, }); const logFailure = @@ -444,7 +444,7 @@ export const make = Effect.gen(function* () { (cause): Effect.Effect => Cause.hasInterruptsOnly(cause) ? Effect.interrupt - : isRateLimited(cause) + : providerFailureReason(cause) === "rate-limited" ? Effect.succeed("paused") : Effect.logDebug("pull request watch fingerprint failed", { pullRequest: group.key, @@ -472,21 +472,33 @@ export const make = Effect.gen(function* () { const reference = referenceOf(group); // Invalidate cached reads before using the newer fingerprint; clients receive no notification. if (fingerprint !== null) yield* pullRequests.invalidate({ reference }); - const read = yield* Effect.exit( - Effect.all( - [ - pullRequests.detail({ ...reference, allowStale: false }), + const [detailRead, activityRead] = yield* Effect.all( + [ + Effect.exit(pullRequests.detail({ ...reference, allowStale: false })), + Effect.exit( plan.activity ? pullRequests.activity(reference).pipe(Effect.asSome) : Effect.succeed(Option.none()), - ], - { concurrency: 2 }, - ), + ), + ], + { concurrency: 2 }, ); + // Activity failures must not cancel or hide a permanent detail failure. + const read = Exit.isFailure(detailRead) + ? Exit.failCause(detailRead.cause) + : Exit.isFailure(activityRead) + ? Exit.failCause(activityRead.cause) + : Exit.succeed([detailRead.value, activityRead.value] as const); if (Exit.isFailure(read)) { if (Cause.hasInterruptsOnly(read.cause)) return yield* Effect.failCause(read.cause); lastReads.delete(group.key); - if (isRateLimited(read.cause)) return; + const reason = providerFailureReason(read.cause); + if (reason === "rate-limited") return; + // Transport and host failures can outlast the failure limit; keep the watch for recovery. + if (reason === "failed") { + readFailures.delete(group.key); + return yield* Effect.failCause(read.cause); + } const failures = (readFailures.get(group.key) ?? 0) + 1; readFailures.set(group.key, failures); if (failures >= READ_FAILURE_LIMIT && (yield* eachTarget(group, giveUp))) { diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 2bb9f5ed63165..769ced28d2f15 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1,3 +1,4 @@ +import { PullRequestProviderError } from "@t3tools/source-control-core/server/PullRequestProvider"; import { SourceControlProviderKind } from "@t3tools/contracts"; import { limitRecoveryCommand } from "./UsageLimitRecoveryWorker.ts"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; @@ -3172,63 +3173,155 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); - it.effect("ends a watch it cannot read, and tells the agent", () => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const threadId = ThreadId.make("runtime-pull-request-watch-unreadable"); - const projectId = ProjectId.make("pr-watch-unreadable-project"); - yield* seedProject({ - projectId, - title: "Watch unreadable", - workspaceRoot: "/workspace/watch-unreadable", - defaultModelSelection: null, - createdAt: "2026-10-01T00:00:00.000Z", - }); - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("pr-watch-unreadable-create"), - threadId, - projectId, - title: "Watch unreadable", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - }); - yield* orchestrator.dispatch({ - type: "thread.pull-request.watch", - commandId: CommandId.make("pr-watch-unreadable-start"), - threadId, - host: "github.com", - repository: "pingdotgg/t3code", - number: 8, - watching: true, - link: { url: "https://github.com/pingdotgg/t3code/pull/8", source: "agent" }, - }); - const reactor = yield* PullRequestWatchReactor.make.pipe( - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - Layer.mock(PullRequestService.PullRequestService)({ - detail: () => Effect.die("host unreachable"), - activity: () => Effect.die("host unreachable"), + it.effect.each([ + { reason: "failed", activityFails: false }, + { reason: "not-found", activityFails: false }, + { reason: "failed", activityFails: true }, + { reason: "not-found", activityFails: true }, + { reason: "forbidden", activityFails: true }, + ] as const)( + "handles repeated host read failures: $reason (activity fails: $activityFails)", + ({ reason, activityFails }) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make( + `runtime-pull-request-watch-unreadable-${reason}-${activityFails}`, + ); + const projectId = ProjectId.make(`pr-watch-unreadable-project-${reason}-${activityFails}`); + yield* seedProject({ + projectId, + title: "Watch unreadable", + workspaceRoot: "/workspace/watch-unreadable", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`pr-watch-unreadable-create-${reason}-${activityFails}`), + threadId, + projectId, + title: "Watch unreadable", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`pr-watch-unreadable-start-${reason}-${activityFails}`), + threadId, + host: "github.com", + repository: "pingdotgg/t3code", + number: 8, + watching: true, + link: { url: "https://github.com/pingdotgg/t3code/pull/8", source: "agent" }, + }); + let disconnected = false; + let passed = false; + let genericFailure = false; + const activityFailures = yield* Queue.unbounded(); + const readFailure = (operation: string, failure: "failed" | "not-found" | "forbidden") => + new PullRequestOperationError({ + operation, + detail: "host read failed", + cause: new PullRequestProviderError({ + provider: SourceControlProviderKind.make("github"), + operation, + reason: failure, + detail: "host read failed", }), + }); + const reactor = yield* PullRequestWatchReactor.make.pipe( + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + Layer.mock(PullRequestService.PullRequestService)({ + watchFingerprint: () => Effect.succeed(null), + detail: () => + genericFailure + ? Effect.die("host read failed") + : disconnected + ? (activityFails ? Queue.take(activityFailures) : Effect.void).pipe( + Effect.andThen(Effect.fail(readFailure("detail", reason))), + ) + : Effect.succeed({ + ...watchedPullRequestDetail({ + projectId, + number: 8, + at: "2026-10-02T12:00:00.000Z", + }), + headSha: "abc1234def", + checks: [ + { + name: "test", + status: passed ? ("success" as const) : ("pending" as const), + description: null, + url: null, + required: true, + }, + ], + }), + activity: () => + disconnected && activityFails + ? Queue.offer(activityFailures, undefined).pipe( + Effect.andThen(Effect.fail(readFailure("activity", "failed"))), + ) + : Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + }), + ), ), - ), - ); - for (let pass = 0; pass < 15; pass += 1) yield* reactor.sweep; + ); + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const sweep = reactor.sweep.pipe(Effect.andThen(worker.drain())); + const summaries = Effect.map( + orchestrator.getThreadRecords(threadId, ["messages"]), + ({ messages }) => messages.flatMap((message) => message.notification?.summary ?? []), + ); + yield* sweep; + assert.deepEqual(yield* summaries, []); + disconnected = true; + for (let pass = 0; pass < 15; pass += 1) { + genericFailure = reason === "failed" && (pass === 0 || (pass >= 2 && pass <= 8)); + yield* TestClock.adjust("2 minutes"); + yield* sweep; + } - const thread = yield* orchestrator.getThreadShell(threadId); - assert.isUndefined(thread?.pullRequests?.[0]?.watch); - const { messages } = yield* orchestrator.getThreadRecords(threadId, ["messages"]); - assert.deepEqual( - messages.flatMap((message) => message.notification?.summary ?? []), - ["#8: stopped watching, could not read it"], - ); - }), + const thread = yield* orchestrator.getThreadShell(threadId); + if (reason !== "failed") { + assert.isUndefined(thread?.pullRequests?.[0]?.watch); + assert.deepEqual(yield* summaries, ["#8: stopped watching, could not read it"]); + return; + } + assert.isDefined(thread?.pullRequests?.[0]?.watch); + assert.deepEqual(yield* summaries, []); + disconnected = false; + genericFailure = false; + passed = true; + yield* sweep; + assert.deepEqual(yield* summaries, ["#8: checks passed"]); + yield* TestClock.adjust("10 minutes"); + yield* sweep; + assert.deepEqual(yield* summaries, ["#8: checks passed"]); + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`pr-watch-unreadable-stop-${reason}-${activityFails}`), + threadId, + host: "github.com", + repository: "pingdotgg/t3code", + number: 8, + watching: false, + }); + yield* worker.drain(); + }), ); it.effect("wakes once for a state it reported, across a restart and a new watch", () => diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index a175c365d080e..3156efdd7d80f 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -47,6 +47,7 @@ export class PullRequestProviderError extends Schema.TaggedError + Effect.gen(function* () { + const provider = yield* make.pipe( + Effect.provide( + Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({ + revalidateChecks: (_input, read) => read, + getPullRequestDetail: () => + Effect.fail( + new GitHubRequestPolicy.GitHubApiResponseError({ + host: "github.com", + operation: "detail", + status, + githubErrorTypes, + }), + ), + }), + ), + ); + const error = yield* provider + .getChangeRequest({ + cwd: "/w", + repository: "acme/web", + host: "github.com", + number: 7, + }) + .pipe(Effect.flip); + expect(error.reason).toBe(reason); + }), +); + it.effect("advertises standalone branch deletion for source repository writers", () => Effect.gen(function* () { let action: string | undefined; diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index a99aa87c9652d..b998d2be735a6 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -120,6 +120,15 @@ function gitHubProviderFailure( }; case "SourceControlRateLimitPausedError": return { reason: "rate-limited", retryAt: error.retryAt }; + case "GitHubApiResponseError": + return { + reason: + error.status === 403 || + (error.githubErrorTypes?.includes("FORBIDDEN") && + error.githubErrorTypes.every((type) => type === "FORBIDDEN" || type === "NOT_FOUND")) + ? "forbidden" + : "failed", + }; case "GitHubApiNotFoundError": return error.credential === undefined || error.credential === "app" ? { reason: "not-found" } diff --git a/packages/source-control-github/src/server/GitHubRequestPolicy.ts b/packages/source-control-github/src/server/GitHubRequestPolicy.ts index 158a0982d96f2..0d48932db327b 100644 --- a/packages/source-control-github/src/server/GitHubRequestPolicy.ts +++ b/packages/source-control-github/src/server/GitHubRequestPolicy.ts @@ -85,6 +85,7 @@ export class GitHubApiResponseError extends Schema.TaggedError { errors: [ { type: "NOT_FOUND", message: "Could not resolve" }, { type: "FORBIDDEN", message: "Resource not accessible" }, + { message: "Unknown error" }, ], }), ); @@ -310,7 +311,8 @@ describe("call", () => { expect(error).toMatchObject({ _tag: "GitHubApiResponseError", status: 200, - githubErrors: ["Could not resolve", "Resource not accessible"], + githubErrors: ["Could not resolve", "Resource not accessible", "Unknown error"], + githubErrorTypes: ["NOT_FOUND", "FORBIDDEN", null], }); }).pipe(Effect.provide(layer)); }, diff --git a/packages/source-control-github/src/server/gitHubGraphQlClient.ts b/packages/source-control-github/src/server/gitHubGraphQlClient.ts index 7030abb1742e2..484e808b0cd49 100644 --- a/packages/source-control-github/src/server/gitHubGraphQlClient.ts +++ b/packages/source-control-github/src/server/gitHubGraphQlClient.ts @@ -248,6 +248,9 @@ const fromClientError = ( ...context, status: reason.status ?? 200, githubErrors: reason.errors.map((graphQlError) => graphQlError.message), + githubErrorTypes: reason.errors.map((graphQlError) => + typeof graphQlError["type"] === "string" ? graphQlError["type"] : null, + ), }); }; From af00cf73e1b952586b51f77976f913a35154f30c Mon Sep 17 00:00:00 2001 From: Serhiy Khvala <88881670+serhiyhvala@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:46:12 +0200 Subject: [PATCH 051/163] fix(cursor): show Cursor usage after signing in with Cursor (#29419) Co-authored-by: maria-rcks --- apps/server/src/usage/UsageService.test.ts | 228 +++++++++++++++++- docs/user/usage.md | 18 +- .../src/server/CursorUsageAccounts.ts | 82 ++++++- .../src/server/accountCache.ts | 5 +- .../src/server/accountUsage.test.ts | 50 ++++ .../src/server/accountUsage.ts | 42 +++- packages/provider-cursor/src/server/apiKey.ts | 24 ++ .../src/server/credentialStore.ts | 20 ++ packages/provider-cursor/src/server/driver.ts | 3 +- .../src/server/usageLimits.test.ts | 50 +++- .../provider-cursor/src/server/usageLimits.ts | 22 +- 11 files changed, 492 insertions(+), 52 deletions(-) create mode 100644 packages/provider-cursor/src/server/apiKey.ts diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 8c09383d56c18..218072652cc58 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -30,6 +30,7 @@ import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Context from "effect/Context"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Scheduler from "effect/Scheduler"; import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; @@ -149,6 +150,7 @@ const layerService = (input: { readonly environment?: NodeJS.ProcessEnv; readonly platform?: NodeJS.Platform; readonly hostname?: string; + readonly secretStore?: Partial; }) => layerCursorUsageAccounts( CursorAccountReader.layer.pipe(Layer.provide(CursorKeychain.layer)), @@ -158,7 +160,12 @@ const layerService = (input: { Layer.provideMerge(ProviderHostLive.layer), Layer.provideMerge(CodexUsageHistory.layer.pipe(Layer.provideMerge(Sqlite.layerMemory))), Layer.provideMerge(Layer.mock(BackgroundPolicy.BackgroundPolicy)({})), - Layer.provideMerge(Layer.mock(ServerSecretStore.ServerSecretStore)({})), + Layer.provideMerge( + Layer.mock(ServerSecretStore.ServerSecretStore)({ + get: () => Effect.succeedNone, + ...input.secretStore, + }), + ), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), NodePath.join(input.home, input.prefix)), ), @@ -239,10 +246,12 @@ function makeFakeCursor() { error: null as string | null, gate: undefined as Deferred.Deferred | undefined, calls: [] as { readonly sinceMs: number; readonly untilMs: number }[], + credentials: [] as unknown[], }; - const read = (_credential: unknown, sinceMs: number, untilMs: number) => + const read = (credential: unknown, sinceMs: number, untilMs: number) => Effect.gen(function* () { state.calls.push({ sinceMs, untilMs }); + state.credentials.push(credential); if (state.gate !== undefined) yield* Deferred.await(state.gate); const { accountKey, error } = state; if (error !== null) return { accountKey, records: [], missing: false, error }; @@ -286,6 +295,10 @@ function cursorSource(summary: { readonly sources: readonly UsageSource[] }) { return summary.sources.find((source) => source.fingerprint.provider === "cursor"); } +function cursorSources(summary: { readonly sources: readonly UsageSource[] }) { + return summary.sources.filter((source) => source.fingerprint.provider === "cursor"); +} + const seedCodexHistory = (input: { id: string; nativeTurnId?: string; @@ -1512,11 +1525,6 @@ describe("UsageService", () => { environment: { AGENT_CLI_CREDENTIAL_STORE: "memory" }, authPath: ["config", "cursor", "auth.json"], }, - { - platform: "linux" as const, - environment: { CURSOR_API_KEY: "different-account" }, - authPath: ["config", "cursor", "auth.json"], - }, ].entries()) { const authPath = NodePath.join(home, ...testCase.authPath); yield* Effect.promise(async () => { @@ -1546,6 +1554,212 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); + it.live("reads the Cursor account of an API key or T3 sign-in instead of a CLI login", () => + Effect.gen(function* () { + const { settings, home } = yield* setup; + const signIn = new TextEncoder().encode( + encodeUnknownJsonString({ + version: 1, + backendUrl: "https://api2.cursor.sh", + apiKey: "signed-in-key", + createdAtMs: 0, + }), + ); + for (const [index, testCase] of [ + { environment: { CURSOR_API_KEY: "environment-key" }, stored: Option.none() }, + { environment: {}, stored: Option.some(signIn) }, + ].entries()) { + const cursor = makeFakeCursor(); + const summary = yield* Effect.gen(function* () { + const service = yield* makeWithCursor(cursor.read); + return yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); + }).pipe( + Effect.provide( + layerService({ + prefix: `usage-service-cursor-api-key-${index}`, + home, + settings, + platform: "darwin", + environment: testCase.environment, + secretStore: { get: () => Effect.succeed(testCase.stored) }, + }), + ), + ); + assert.deepStrictEqual(cursor.state.credentials, [ + { kind: "apiKey", apiKey: index === 0 ? "environment-key" : "signed-in-key" }, + ]); + assert.strictEqual(cursorSource(summary)?.status, "ok"); + } + }).pipe(Effect.scoped), + ); + + it.live("does not show a previous Cursor account's history after the API key changes", () => + Effect.gen(function* () { + const { settings, home } = yield* setup; + yield* TestClock.setTime(CURSOR_NOW); + let apiKey = "first-account-key"; + const signIn = () => + Option.some( + new TextEncoder().encode( + encodeUnknownJsonString({ + version: 1, + backendUrl: "https://api2.cursor.sh", + apiKey, + createdAtMs: 0, + }), + ), + ); + const cursor = makeFakeCursor(); + cursor.state.events = [{ timestampMs: CURSOR_NOW - 3 * HOUR_MS, outputTokens: 7 }]; + yield* Effect.gen(function* () { + const service = yield* makeWithCursor(cursor.read); + const first = yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); + assert.isTrue(first.buckets.some((bucket) => bucket.provider === "cursor")); + + apiKey = "second-account-key"; + cursor.state.error = "Cursor account usage could not be read."; + const second = yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); + assert.isFalse(second.buckets.some((bucket) => bucket.provider === "cursor")); + }).pipe( + Effect.provide( + layerService({ + prefix: "usage-service-cursor-key-change", + home, + settings, + platform: "darwin", + environment: {}, + secretStore: { get: () => Effect.sync(signIn) }, + }), + ), + ); + }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + ); + + it.live("keeps a new Cursor key's refresh visible beside a failing key", () => + Effect.gen(function* () { + const { settings, home } = yield* setup; + const cursor = makeFakeCursor(); + const started = yield* Deferred.make(); + const gate = yield* Deferred.make(); + yield* Effect.gen(function* () { + const context = yield* Layer.build( + layerCursorUsageAccounts( + Layer.succeed(CursorAccountReader.CursorAccountReader, { + read: (credential, sinceMs, untilMs) => + (credential as { apiKey?: string }).apiKey === "failing-key" + ? Effect.succeed({ + accountKey: null, + records: [], + missing: false, + error: "Cursor account usage could not be read.", + }) + : Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(gate)), + Effect.andThen(cursor.read(credential, sinceMs, untilMs)), + ), + }), + ), + ); + const accounts = Context.get(context, CursorUsageAccounts.CursorUsageAccounts); + const scan = (awaitRefresh: boolean) => + accounts.scan({ + instances: [ + { + instanceId: ProviderInstanceId.make("cursor"), + environment: { CURSOR_API_KEY: "failing-key" }, + }, + { + instanceId: ProviderInstanceId.make("cursor-work"), + environment: { CURSOR_API_KEY: "new-key" }, + }, + ], + keychainUsageEnabled: false, + windowStartMs: 0, + retentionCutoffMs: 0, + awaitRefresh, + }); + const first = yield* Effect.forkChild(scan(true)); + yield* Deferred.await(started); + const sources = yield* scan(false); + assert.isTrue(sources.some((source) => source.refreshing === true)); + yield* Deferred.succeed(gate, undefined); + yield* Fiber.join(first); + }).pipe( + Effect.provide( + layerService({ + prefix: "usage-service-cursor-new-key", + home, + settings, + platform: "linux", + environment: {}, + }), + ), + ); + }).pipe(Effect.scoped), + ); + + it.live("reports one Cursor source when two API keys belong to the same account", () => + Effect.gen(function* () { + const { settings, home } = yield* setup; + yield* TestClock.setTime(CURSOR_NOW); + const cursor = makeFakeCursor(); + cursor.state.events = [{ timestampMs: CURSOR_NOW - 3 * HOUR_MS, outputTokens: 7 }]; + let revoked = false; + yield* Effect.gen(function* () { + const service = yield* makeWithCursor((credential, sinceMs, untilMs) => + revoked && (credential as { apiKey?: string }).apiKey === "second-key" + ? Effect.succeed({ + accountKey: null, + records: [], + missing: false, + error: "Cursor account usage could not be read.", + }) + : cursor.read(credential, sinceMs, untilMs), + ); + const first = yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); + assert.strictEqual(cursor.state.credentials.length, 2); + assert.deepStrictEqual( + cursorSources(first).map((source) => source.distinctSessions), + [1], + ); + + // The revoked key keeps its stale cache, which must not replace the working key's history. + revoked = true; + cursor.state.events.push({ timestampMs: CURSOR_NOW + 60 * 1000, outputTokens: 5 }); + yield* TestClock.adjust(Duration.minutes(2)); + const second = yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); + assert.deepStrictEqual( + cursorSources(second).map((source) => source.status), + ["ok"], + ); + assert.strictEqual(totalOutputTokens(second), 12); + }).pipe( + Effect.provide( + layerService({ + prefix: "usage-service-cursor-shared-account", + home, + settings: { + ...settings, + providerInstances: { + ...settings.providerInstances, + [ProviderInstanceId.make("cursor")]: { + driver: ProviderDriverKind.make("cursor"), + environment: [{ name: "CURSOR_API_KEY", value: "first-key", sensitive: true }], + }, + [ProviderInstanceId.make("cursor-work")]: { + driver: ProviderDriverKind.make("cursor"), + environment: [{ name: "CURSOR_API_KEY", value: "second-key", sensitive: true }], + }, + }, + }, + platform: "darwin", + environment: {}, + }), + ), + ); + }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + ); + it.live( "includes OpenCode history but does not substitute desktop usage for an unavailable Cursor account", () => diff --git a/docs/user/usage.md b/docs/user/usage.md index 71eb1e0fe8773..d25bdba81f00a 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -24,12 +24,13 @@ OpenCode reads its SQLite database and older JSON history. Antigravity reads loc databases, including T3-managed profiles. Set `OPENCODE_DATA_DIR` or `ANTIGRAVITY_DATA_DIR` on the server to read a different data directory; comma-separated paths read multiple directories. -Cursor reads account usage from Cursor's dashboard API using the CLI login saved on the server. +Cursor reads account usage from Cursor's API for the account you signed in with in T3 or set as +`CURSOR_API_KEY`, or otherwise the CLI login saved on the server. This includes headless T3 sessions and desktop usage across machines; the same account counts -once across connected environments. Without an accessible CLI login, T3 shows a +once across connected environments. Without any of these, T3 shows a notice instead of incomplete local totals. T3 does not estimate missing tokens from conversation text. -On macOS, choose **Enable Cursor usage** on Usage to allow T3 to read your existing CLI login -from Keychain. You can turn it off in **Settings → Providers → Usage providers**. macOS may ask +On macOS without a T3 sign-in, choose **Enable Cursor usage** on Usage to allow T3 to read your +existing CLI login from Keychain. You can turn it off in **Settings → Providers → Usage providers**. macOS may ask you to allow access on the server Mac. Usage includes each configured account's history, including disabled accounts. Custom homes follow @@ -159,10 +160,11 @@ belong to the remote server. Limits need an OpenCode Go API key, or an OpenCode in OpenCode with an API key. A Console browser sign-in alone does not report them. You can also add your Go API key as `OPENCODE_API_KEY` in the OpenCode instance's **Environment variables**, then refresh provider status. Cursor reports -its monthly allowance, including separate Auto and API usage, using the CLI login or -`CURSOR_AUTH_TOKEN`. On macOS, this includes the default Keychain login after you enable Cursor -usage. Keychain login is used for limits only with Cursor's default API endpoint. If you configure -a custom Cursor endpoint, use an explicit token or file-based CLI login for limits. +its monthly allowance, including separate Auto and API usage, for `CURSOR_AUTH_TOKEN` when it is set, +otherwise for the account you signed in with in T3 or set as `CURSOR_API_KEY`, otherwise for the CLI +login. On macOS, this includes the default Keychain login after you enable Cursor usage. Sign-in, API key, +and Keychain login report limits only with Cursor's default API endpoint. If you configure a custom +Cursor endpoint, use an explicit token or file-based CLI login for limits. Grok reports the remaining subscription allowance and reset time for its current billing period after signing in with `grok login`. Explicit `XAI_API_KEY` connections and custom authentication diff --git a/packages/provider-cursor/src/server/CursorUsageAccounts.ts b/packages/provider-cursor/src/server/CursorUsageAccounts.ts index 07fa215f2eeb2..59adc4c6d92f6 100644 --- a/packages/provider-cursor/src/server/CursorUsageAccounts.ts +++ b/packages/provider-cursor/src/server/CursorUsageAccounts.ts @@ -1,11 +1,14 @@ +import type { ProviderInstanceId } from "@t3tools/contracts"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import type { ProviderUsageScan } from "@t3tools/provider-core/server/usage"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as Crypto from "effect/Crypto"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Hex from "effect/encoding/Hex"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -25,6 +28,7 @@ import { type CursorCredentialSource, } from "./accountCache.ts"; import * as CursorAccountReader from "./CursorAccountReader.ts"; +import { readStoredCursorApiKey } from "./credentialStore.ts"; const CURSOR_ACCOUNT_READ_ERROR = "Cursor account usage could not be read."; @@ -36,6 +40,10 @@ export class CursorUsageAccounts extends Context.Service< CursorUsageAccounts, { readonly scan: (input: { + readonly instances: ReadonlyArray<{ + readonly instanceId: ProviderInstanceId; + readonly environment: NodeJS.ProcessEnv; + }>; readonly keychainUsageEnabled: boolean; readonly windowStartMs: number; readonly retentionCutoffMs: number; @@ -52,6 +60,7 @@ const make = Effect.gen(function* () { const accountReader = yield* CursorAccountReader.CursorAccountReader; const hostEnvironment = yield* HostProcess.Environment; const platform = yield* HostProcess.Platform; + const crypto = yield* Crypto.Crypto; const cachePath = path.join(host.paths.stateDir, CURSOR_ACCOUNT_CACHE_FILE_NAME); const caches = new Map(); @@ -187,12 +196,30 @@ const make = Effect.gen(function* () { awaitRefresh: boolean, ) { // A Keychain login outlives an uninstalled Cursor, so it also needs Cursor's local directory. - const localLogin = typeof credential === "string" ? credential : path.dirname(authPath); - if (!(yield* fileSystem.exists(localLogin).pipe(Effect.orElseSucceed(() => true)))) { + const localLogin = + typeof credential === "string" + ? credential + : credential.kind === "keychain" + ? path.dirname(authPath) + : null; + if ( + localLogin !== null && + !(yield* fileSystem.exists(localLogin).pipe(Effect.orElseSucceed(() => true))) + ) { return null; } yield* ensureLoaded; - const credentialKey = typeof credential === "string" ? credential : "keychain"; + const credentialKey = + typeof credential === "string" + ? credential + : credential.kind === "apiKey" + ? // A fingerprint, so a replaced key never reads the previous account's cache. + `api-key:${Hex.encode( + yield* crypto + .digest("SHA-256", new TextEncoder().encode(credential.apiKey)) + .pipe(Effect.orDie), + )}` + : "keychain"; const nowMs = yield* Clock.currentTimeMillis; const recentFailure = failures.get(credentialKey); let refreshing = false; @@ -238,7 +265,13 @@ const make = Effect.gen(function* () { }); const scan: CursorUsageAccounts["Service"]["scan"] = Effect.fn("CursorUsageAccounts.scan")( - function* ({ keychainUsageEnabled, windowStartMs, retentionCutoffMs, awaitRefresh }) { + function* ({ + instances, + keychainUsageEnabled, + windowStartMs, + retentionCutoffMs, + awaitRefresh, + }) { const home = yield* HostProcess.HomeDirectory; const userHome = (platform === "win32" ? hostEnvironment["USERPROFILE"] : hostEnvironment["HOME"]) || home; @@ -255,11 +288,46 @@ const make = Effect.gen(function* () { platform === "darwin" ? path.join(userHome, ".cursor", "auth.json") : path.join(cursorHome, platform === "win32" ? "Cursor" : "cursor", "auth.json"); + // T3's Cursor sign-in and CURSOR_API_KEY name the account the agent uses, so they win. + const apiKeys = yield* Effect.forEach(instances, ({ instanceId, environment }) => + environment.CURSOR_API_KEY?.trim() + ? Effect.succeed(environment.CURSOR_API_KEY.trim()) + : readStoredCursorApiKey(instanceId).pipe( + Effect.provideService(ProviderHost.ProviderHost, host), + Effect.orElseSucceed(() => undefined), + ), + ); + const uniqueApiKeys = [...new Set(apiKeys.filter((apiKey) => apiKey !== undefined))]; + if (uniqueApiKeys.length > 0) { + const sources: ReadonlyArray = yield* Effect.forEach( + uniqueApiKeys, + (apiKey) => + accountSource( + { kind: "apiKey", apiKey }, + authPath, + windowStartMs, + retentionCutoffMs, + awaitRefresh, + ), + ); + // Keys for one account share its source, and a repeated source would count sessions twice. + // A failed key can hold older records, so a current read wins, then a refresh the client + // must follow up on. + const rank = (source: ProviderUsageScan) => + source.status === "ok" ? 2 : source.refreshing ? 1 : 0; + const byAccount = new Map(); + for (const source of sources) { + if (source === null) continue; + const kept = byAccount.get(source.dir); + if (kept === undefined || rank(source) > rank(kept)) { + byAccount.set(source.dir, source); + } + } + return [...byAccount.values()]; + } const credentialStore = hostEnvironment["AGENT_CLI_CREDENTIAL_STORE"]; const loginUnavailable = - Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) || - Boolean(hostEnvironment["CURSOR_API_KEY"]?.trim()) || - credentialStore === "memory"; + Boolean(hostEnvironment["CURSOR_AUTH_TOKEN"]?.trim()) || credentialStore === "memory"; const useKeychain = platform === "darwin" && credentialStore !== "file"; if (useKeychain && !loginUnavailable && !keychainUsageEnabled) { return [ diff --git a/packages/provider-cursor/src/server/accountCache.ts b/packages/provider-cursor/src/server/accountCache.ts index bcbb1ca402b17..b2ff2fbd6b3a2 100644 --- a/packages/provider-cursor/src/server/accountCache.ts +++ b/packages/provider-cursor/src/server/accountCache.ts @@ -2,7 +2,10 @@ import { cursorRateModel } from "./accountUsage.ts"; import type { UsageRecord } from "@t3tools/provider-core/server/usage"; -export type CursorCredentialSource = string | { readonly kind: "keychain" }; +export type CursorCredentialSource = + | string + | { readonly kind: "keychain" } + | { readonly kind: "apiKey"; readonly apiKey: string }; export const CURSOR_ACCOUNT_TTL_MS = 60 * 1000; diff --git a/packages/provider-cursor/src/server/accountUsage.test.ts b/packages/provider-cursor/src/server/accountUsage.test.ts index 642189484bf18..211c24e0902bc 100644 --- a/packages/provider-cursor/src/server/accountUsage.test.ts +++ b/packages/provider-cursor/src/server/accountUsage.test.ts @@ -2,12 +2,14 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientError from "effect/http/HttpClientError"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as Path from "effect/Path"; +import * as TestClock from "effect/testing/TestClock"; import * as CursorKeychain from "./CursorKeychain.ts"; import { readCursorAccountUsage } from "./accountUsage.ts"; @@ -284,6 +286,54 @@ describe("Cursor account history", () => { }); describe("readCursorAccountUsage", () => { + it.effect("reads an API key's account history through Cursor's API", () => + Effect.gen(function* () { + const accessToken = `header.${Buffer.from(JSON.stringify({ sub: "auth|demo" })).toString("base64url")}.signature`; + const requests: Array = []; + const result = yield* readAccountUsage( + { kind: "apiKey", apiKey: "api-key" }, + 0, + 1781000000000, + ({ url, headers }) => { + requests.push([url, headers.get("authorization")]); + return url.endsWith("/auth/exchange_user_api_key") + ? Response.json({ accessToken }) + : Response.json({ + totalUsageEventsCount: 1, + usageEventsDisplay: [ + { timestamp: "1780000000000", model: "gpt-5", tokenUsage: { outputTokens: 4 } }, + ], + }); + }, + ); + assert.isNull(result.error); + assert.deepStrictEqual(requests, [ + ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"], + [ + "https://api2.cursor.sh/aiserver.v1.DashboardService/GetFilteredUsageEvents", + `Bearer ${accessToken}`, + ], + ]); + assert.strictEqual(result.records[0]?.totals.outputTokens, 4); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("stops waiting for an API key exchange that never answers", () => + Effect.gen(function* () { + const read = yield* Effect.forkChild( + readAccountUsage( + { kind: "apiKey", apiKey: "api-key" }, + 0, + 1781000000000, + () => new Promise(() => {}), + ), + ); + yield* TestClock.adjust("10 seconds"); + const result = yield* Fiber.join(read); + assert.strictEqual(result.error, "Cursor account usage could not be read."); + }).pipe(Effect.provide(NodeServices.layer)), + ); + it.effect("asks for Keychain approval when the prompt goes unanswered", () => Effect.gen(function* () { const result = yield* readAccountUsage( diff --git a/packages/provider-cursor/src/server/accountUsage.ts b/packages/provider-cursor/src/server/accountUsage.ts index 65f1470b94c94..21959a4f4de98 100644 --- a/packages/provider-cursor/src/server/accountUsage.ts +++ b/packages/provider-cursor/src/server/accountUsage.ts @@ -13,6 +13,8 @@ import * as PlatformError from "effect/PlatformError"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; +import type { CursorCredentialSource } from "./accountCache.ts"; +import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts"; import * as CursorKeychain from "./CursorKeychain.ts"; function object(value: unknown): Record { @@ -90,7 +92,7 @@ const DASHBOARD_USAGE_URL = "https://cursor.com/api/dashboard/get-filtered-usage const NO_REDIRECT: RequestInit = { redirect: "error" }; export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(function* ( - credentialSource: string | { readonly kind: "keychain" }, + credentialSource: CursorCredentialSource, sinceMs: number, endDate: number, keychainToken: Effect.Effect< @@ -120,7 +122,14 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi Effect.flatMap(decodeJson), Effect.map((credentials) => object(credentials).accessToken), ) - : keychainToken, + : credentialSource.kind === "apiKey" + ? exchangeCursorApiKey(credentialSource.apiKey).pipe( + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.mapError( + () => new CursorAccountUsageInvalidError({ reason: "Invalid API key" }), + ), + ) + : keychainToken, ); if (Result.isFailure(credential)) { const cause = credential.failure; @@ -136,9 +145,11 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi ? null : typeof credentialSource === "string" ? "Cursor credentials could not be read." - : CursorKeychain.isCursorKeychainTimeoutError(cause) - ? "Allow Keychain access on the Mac running T3 Code, then refresh." - : "Cursor Keychain credentials could not be read.", + : credentialSource.kind === "apiKey" + ? "Cursor account usage could not be read." + : CursorKeychain.isCursorKeychainTimeoutError(cause) + ? "Allow Keychain access on the Mac running T3 Code, then refresh." + : "Cursor Keychain credentials could not be read.", }; } const accessToken = credential.success; @@ -168,6 +179,21 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi accountKey = yield* accountHash(subject); if (!Number.isFinite(sinceMs) || !Number.isFinite(endDate) || sinceMs < 0 || sinceMs > endDate) return yield* invalid("Invalid date window"); + // The web dashboard rejects API-key tokens; Cursor's RPC API accepts them. + const pageRequest = + typeof credentialSource !== "string" && credentialSource.kind === "apiKey" + ? HttpClientRequest.post( + `${DEFAULT_CURSOR_API_ENDPOINT}/aiserver.v1.DashboardService/GetFilteredUsageEvents`, + ).pipe( + HttpClientRequest.bearerToken(accessToken), + HttpClientRequest.setHeader("connect-protocol-version", "1"), + ) + : HttpClientRequest.post(DASHBOARD_USAGE_URL).pipe( + HttpClientRequest.setHeaders({ + Origin: "https://cursor.com", + Cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${accessToken}`)}`, + }), + ); const records: UsageRecord[] = []; const occurrences = new Map(); const pages: unknown[][] = []; @@ -183,11 +209,7 @@ export const readCursorAccountUsage = Effect.fn("readCursorAccountUsage")(functi } const response = yield* httpClient .execute( - HttpClientRequest.post(DASHBOARD_USAGE_URL).pipe( - HttpClientRequest.setHeaders({ - Origin: "https://cursor.com", - Cookie: `WorkosCursorSessionToken=${encodeURIComponent(`${userId}::${accessToken}`)}`, - }), + pageRequest.pipe( HttpClientRequest.bodyText( pageRequestBody(page, pageSize, sinceMs, endDate), "application/json", diff --git a/packages/provider-cursor/src/server/apiKey.ts b/packages/provider-cursor/src/server/apiKey.ts new file mode 100644 index 0000000000000..06c93e1f3bc55 --- /dev/null +++ b/packages/provider-cursor/src/server/apiKey.ts @@ -0,0 +1,24 @@ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; + +export const DEFAULT_CURSOR_API_ENDPOINT = "https://api2.cursor.sh"; + +const ApiKeyExchange = Schema.Struct({ accessToken: Schema.NonEmptyString }); + +/** Trades a user API key for the access token Cursor's RPCs accept, as `@cursor/sdk` does. */ +export const exchangeCursorApiKey = Effect.fn("exchangeCursorApiKey")(function* (apiKey: string) { + const client = yield* HttpClient.HttpClient; + const response = yield* client.execute( + HttpClientRequest.post(`${DEFAULT_CURSOR_API_ENDPOINT}/auth/exchange_user_api_key`).pipe( + HttpClientRequest.bearerToken(apiKey), + HttpClientRequest.bodyJsonUnsafe({}), + ), + ); + const { accessToken } = yield* HttpClientResponse.schemaBodyJson(ApiKeyExchange)( + yield* HttpClientResponse.filterStatusOk(response), + ); + return accessToken; +}, Effect.timeout("10 seconds")); diff --git a/packages/provider-cursor/src/server/credentialStore.ts b/packages/provider-cursor/src/server/credentialStore.ts index d0638132f1b6f..d995a49f0d215 100644 --- a/packages/provider-cursor/src/server/credentialStore.ts +++ b/packages/provider-cursor/src/server/credentialStore.ts @@ -1,5 +1,6 @@ import type { SdkCredentialStore } from "@cursor/sdk"; import { ProviderSetupError, type ProviderInstanceId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; @@ -90,3 +91,22 @@ export const makeCursorCredentialStore = Effect.fn("makeCursorCredentialStore")( }; return { store, binding: credentials.binding }; }); + +/** The unexpired API key from this instance's T3 sign-in, read without loading the SDK. */ +export const readStoredCursorApiKey = Effect.fn("readStoredCursorApiKey")(function* ( + instanceId: ProviderInstanceId, +) { + const stored = yield* (yield* (yield* ProviderHost.ProviderHost).credentials( + "cursor", + instanceId, + )).get; + if (Option.isNone(stored)) return undefined; + const credentials = yield* decodeCredentials(new TextDecoder().decode(stored.value)).pipe( + Effect.option, + ); + if (Option.isNone(credentials)) return undefined; + const { apiKey, apiKeyExpiresAtMs } = credentials.value; + return apiKeyExpiresAtMs === undefined || apiKeyExpiresAtMs > (yield* Clock.currentTimeMillis) + ? apiKey + : undefined; +}); diff --git a/packages/provider-cursor/src/server/driver.ts b/packages/provider-cursor/src/server/driver.ts index 51c079a51cb84..f797e871d3bd6 100644 --- a/packages/provider-cursor/src/server/driver.ts +++ b/packages/provider-cursor/src/server/driver.ts @@ -74,10 +74,11 @@ export const CursorDriver: ProviderDriver< usage: { kind: "scan", provider: "cursor", - scan: ({ settings, windowStartMs, retentionCutoffMs, awaitRefresh }) => + scan: ({ instances, settings, windowStartMs, retentionCutoffMs, awaitRefresh }) => CursorUsageAccounts.CursorUsageAccounts.pipe( Effect.flatMap((accounts) => accounts.scan({ + instances, keychainUsageEnabled: settings.cursorKeychainUsageEnabled, windowStartMs, retentionCutoffMs, diff --git a/packages/provider-cursor/src/server/usageLimits.test.ts b/packages/provider-cursor/src/server/usageLimits.test.ts index 1b4cadf88ae3f..617616d14bc25 100644 --- a/packages/provider-cursor/src/server/usageLimits.test.ts +++ b/packages/provider-cursor/src/server/usageLimits.test.ts @@ -182,17 +182,46 @@ describe("Cursor usage limits", () => { }), ); - it.effect("does not use a stored login for an explicit API key", () => + it.effect("reads an API key's own account instead of a stored login", () => Effect.gen(function* () { - const limits = yield* withNodeServices( - readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "different-account" }).pipe( - Effect.provideService( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die("must not request usage")), + for (const platform of ["linux", "darwin"] as const) { + const requests: Array = []; + const limits = yield* withNodeServices( + readCursorUsageLimits({ apiEndpoint: "" }, { CURSOR_API_KEY: "api-key" }, true).pipe( + Effect.provideService(HostProcess.Platform, platform), + Effect.provideService( + FileSystem.FileSystem, + FileSystem.makeNoop({ + readFileString: () => Effect.die("must not read a stored login"), + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => { + requests.push([request.url, request.headers.authorization]); + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json( + request.url.endsWith("/auth/exchange_user_api_key") + ? { accessToken: "api-key-access-token" } + : { planUsage: { totalPercentUsed: 37 } }, + ), + ), + ); + }), + ), ), - ), - ); - expect(limits.unavailable?.reason).toBe("unsupported"); + ); + expect(requests).toEqual([ + ["https://api2.cursor.sh/auth/exchange_user_api_key", "Bearer api-key"], + [ + "https://api2.cursor.sh/aiserver.v1.DashboardService/GetCurrentPeriodUsage", + "Bearer api-key-access-token", + ], + ]); + expect(limits.windows[0]?.usedPercent).toBe(37); + } }), ); @@ -246,13 +275,14 @@ describe("Cursor usage limits", () => { }), ); - it.effect("does not read Keychain or send its token to a custom endpoint", () => + it.effect("does not send a Keychain login or API key to a custom endpoint", () => Effect.gen(function* () { for (const [apiEndpoint, environment] of [ ["http://localhost:3000", {}], ["", { CURSOR_API_ENDPOINT: "http://localhost:3000" }], ["https://cursor-proxy.example", {}], ["", { CURSOR_API_ENDPOINT: "https://cursor-proxy.example" }], + ["https://cursor-proxy.example", { CURSOR_API_KEY: "api-key" }], ] as const) { const limits = yield* withNodeServices( readCursorUsageLimits({ apiEndpoint }, environment, true).pipe( diff --git a/packages/provider-cursor/src/server/usageLimits.ts b/packages/provider-cursor/src/server/usageLimits.ts index 049e646d2c492..87fcecef4e97f 100644 --- a/packages/provider-cursor/src/server/usageLimits.ts +++ b/packages/provider-cursor/src/server/usageLimits.ts @@ -16,10 +16,10 @@ import { makeUnavailableUsageLimits, makeUsageLimits, } from "@t3tools/provider-core/server/usageLimits"; +import { DEFAULT_CURSOR_API_ENDPOINT, exchangeCursorApiKey } from "./apiKey.ts"; import * as CursorKeychain from "./CursorKeychain.ts"; const CursorCredentials = Schema.Struct({ accessToken: Schema.optional(Schema.String) }); -const DEFAULT_CURSOR_API_ENDPOINT = "https://api2.cursor.sh"; const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(CursorCredentials)); const CursorUsageResponse = Schema.Struct({ billingCycleEnd: Schema.optional(Schema.Union([Schema.String, Schema.Number])), @@ -77,19 +77,25 @@ export const readCursorUsageLimits = Effect.fn("readCursorUsageLimits")(function DEFAULT_CURSOR_API_ENDPOINT ).replace(/\/$/, ""); let token = environment.CURSOR_AUTH_TOKEN?.trim(); - // An explicit API key can name a different account from the stored login. - if (!token && environment.CURSOR_API_KEY?.trim()) { - return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); - } + const apiKey = environment.CURSOR_API_KEY?.trim(); const credentialStore = environment.AGENT_CLI_CREDENTIAL_STORE; - if (!token && credentialStore === "memory") { + // An API key can name a different account from the stored login, so read the key's own. + if (!token && apiKey) { + if (endpoint !== DEFAULT_CURSOR_API_ENDPOINT) { + return makeUnavailableUsageLimits({ + checkedAt, + reason: "unsupported", + message: "Cursor usage for an API key requires the default Cursor endpoint.", + }); + } + token = yield* exchangeCursorApiKey(apiKey); + } else if (!token && credentialStore === "memory") { return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported", message: "Cursor usage requires a CLI login or CURSOR_AUTH_TOKEN.", }); - } - if (!token && platform === "darwin" && credentialStore !== "file") { + } else if (!token && platform === "darwin" && credentialStore !== "file") { if (!allowKeychain) { return makeUnavailableUsageLimits({ checkedAt, From cbd3e149a130f1d99d2d067c77b9889d64e28755 Mon Sep 17 00:00:00 2001 From: maria Date: Mon, 2 Nov 2026 20:46:25 +0000 Subject: [PATCH 052/163] perf(server): skip redundant claude session naming (#28910) --- .../src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts | 8 ++++++++ .../src/orchestration-v2/Adapters/ClaudeAdapterV2.ts | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index a7b1f7e2e03f8..42d24d0076d6e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -2601,6 +2601,7 @@ describe("ClaudeAdapterV2 MCP credential channel", () => { ...ClaudeAdapterV2.makeClaudeQueryOptions({ modelSelection: CLAUDE_TEST_MODEL_SELECTION, nativeThreadId: "native-thread-claude-mcp-channel", + title: "Existing T3 title", resume: false, cwd: null, environment: { PATH: "/usr/bin" }, @@ -2655,7 +2656,12 @@ describe("ClaudeAdapterV2 MCP credential channel", () => { subtype: "mcp_set_servers", servers: { "t3-code": t3McpServer }, }); + assert.deepInclude( + cli.controlRequests.find((request) => Reflect.get(request, "subtype") === "initialize"), + { title: "Existing T3 title" }, + ); const spawned = JSON.stringify(cli.spawns); + assert.notInclude(spawned, "--title"); assert.notInclude(spawned, "--mcp-config"); assert.notInclude(spawned, "dummy-mcp-credential"); }), @@ -2745,6 +2751,7 @@ describe("ClaudeAdapterV2 native session identity", () => { assert.equal(openedQueries.length, 1); assert.equal(openedQueries[0]?.options.resume, "native-session-identity"); assert.equal(openedQueries[0]?.options.sessionId, undefined); + assert.equal(openedQueries[0]?.options.title, "Claude attachment test"); }), ); @@ -2753,6 +2760,7 @@ describe("ClaudeAdapterV2 native session identity", () => { const openedQueries = yield* openTurnWithOrdinal(4, false); assert.equal(openedQueries[0]?.options.sessionId, "native-session-identity"); assert.equal(openedQueries[0]?.options.resume, undefined); + assert.equal(openedQueries[0]?.options.title, "Claude attachment test"); }), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index bc90fcb2189b4..4d5238b74b709 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1468,6 +1468,7 @@ const subagentDeviceInstructions: HookCallback = () => export function makeClaudeQueryOptions(input: { readonly modelSelection: ModelSelection; readonly nativeThreadId: string; + readonly title?: string; readonly resume: boolean; readonly resumeSessionAt?: string; readonly cwd: string | null; @@ -1548,6 +1549,8 @@ export function makeClaudeQueryOptions(input: { const deviceInstructions = input.mcpServers !== undefined && input.deviceToolsAvailable === true; const options: ClaudeAgentSdkQueryOptions = { model: compiledSelection.apiModelId, + // T3 names threads; a supplied title skips Claude's redundant naming request. + ...(input.title === undefined ? {} : { title: input.title }), tools: claudeAgentSdkQueryToolsForSdk(selectedTools), permissionMode: (launchArgPermissionMode as PermissionMode | null | undefined) ?? @@ -10349,6 +10352,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const queryOptions = makeClaudeQueryOptions({ modelSelection: turnInput.modelSelection, nativeThreadId, + title: turnInput.appThread.title, resume: shouldResume, ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }), cwd: turnInput.runtimePolicy.cwd, From a9ac1e8e54bd1a411e8bfff8124871adeb4129a2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 13:18:05 -0800 Subject: [PATCH 053/163] fix(mobile): keep the conversation steady during layout changes (#29545) --- .../layout/AdaptiveWorkspaceLayout.tsx | 47 +++-- .../features/threads/ComposerPopoverHost.tsx | 5 +- .../features/threads/PendingUserInputCard.tsx | 81 ++++----- .../features/threads/ThreadDetailScreen.tsx | 114 ++++++++---- .../src/features/threads/ThreadFeed.tsx | 167 ++++++++++++++++-- apps/mobile/src/lib/filePreview.test.ts | 4 + .../src/state/use-thread-composer-state.ts | 2 + 7 files changed, 306 insertions(+), 114 deletions(-) diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx index 137608d6ffd2b..09e7f8a8c449c 100644 --- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -825,10 +825,22 @@ function AdaptiveWorkspaceLayoutContent( 0, viewportWidth - renderedRailWidth.value - - renderedSidebarWidth.value - + (workspacePage ? 0 : renderedSidebarWidth.value) - renderedInspectorWidth.value, ), ); + // Android can resize the native row before React removes its split panes on a fold. + const androidSplit = Platform.OS === "android" && layout.usesSplitView; + const androidContentSlotStyle = useAnimatedStyle(() => ({ + width: androidSplit ? renderedContentWidth.value : ("100%" as const), + })); + // While the sidebar animates, clip the settled navigator instead of reflowing its text every frame. + const androidNavigatorLimit = useAnimatedStyle(() => ({ + maxWidth: + androidSplit && contentTargetWidth !== null && renderedContentWidth.value < contentTargetWidth + ? contentTargetWidth + : ("100%" as const), + })); const handleSelectThread = (thread: EnvironmentThreadShell) => { handleSelectThreadRoute({ @@ -899,11 +911,11 @@ function AdaptiveWorkspaceLayoutContent( > {shouldRenderNavigationRail ? ( - + ) : null} {shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? ( ) : null} - - {/* Android holds the content still, so its floating controls keep its width. */} - - + + {shouldRenderNavigationRail && navigationRailWidth > 0 ? ( - // The rail reserves its slot above and draws over the panes, so it can widen over - // the list in place. It takes the whole workspace only while it is open. + // Its trailing inset clips the old rail as soon as Android fits the workspace to a cover display. ; readonly children: ReactNode; }) { @@ -33,8 +34,8 @@ export function ComposerPopoverHost(props: { ref={hostRef} collapsable={false} pointerEvents="box-none" - className="absolute inset-0" - onLayout={() => setLayoutVersion((version) => version + 1)} + className={props.inFlow ? undefined : "absolute inset-0"} + onLayout={props.hidden ? undefined : () => setLayoutVersion((version) => version + 1)} > {props.children} {props.hidden ? null : content} diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsx index 523d8027519ca..3a2127ea2931c 100644 --- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx +++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx @@ -10,17 +10,12 @@ import { import { useRef } from "react"; import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native"; import Animated, { - Easing, - FadeInUp, - FadeOutDown, useAnimatedStyle, useSharedValue, type DerivedValue, type SharedValue, } from "react-native-reanimated"; -import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout"; - import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { ControlPill } from "../../components/ui/ControlPill"; @@ -43,8 +38,8 @@ export interface PendingUserInputCardProps { readonly collapsed: boolean; readonly onToggleCollapsed: () => void; readonly onStopThread?: () => void; - readonly cardProgress?: SharedValue; - readonly cardCoverage?: SharedValue; + readonly cardProgress: SharedValue; + readonly cardCoverage: SharedValue; readonly onInputFocusChange?: (focused: boolean) => void; readonly drafts: Record; readonly answers: Record> | null; @@ -63,9 +58,6 @@ export interface PendingUserInputCardProps { readonly onDismiss: () => Promise; } -/** Android cannot hit-test overlays beyond their parent's bounds; render its expanded card in-flow. */ -const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios"; - function proseDirectionStyle(text: string, setDirection: TextDirection | undefined) { const direction = textDirection(text); return { @@ -111,14 +103,11 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) { .join(" "), ); - const cardCoverage = props.cardCoverage; + const { cardCoverage, cardProgress, maxHeight } = props; const barHeightRef = useRef(0); const cardHeightRef = useRef(0); const cardHeight = useSharedValue(0); const notifyCoverage = () => { - if (!cardCoverage) { - return; - } // The card resizes with the keyboard every frame, so easing each sample would leave the // feed inset and floating controls trailing it. cardCoverage.set(Math.max(0, cardHeightRef.current - barHeightRef.current)); @@ -132,22 +121,25 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) { cardHeight.set(event.nativeEvent.layout.height); notifyCoverage(); }; - const cardProgress = props.cardProgress; - const maxHeight = props.maxHeight; const cardAnimatedStyle = useAnimatedStyle(() => { - const progress = cardProgress === undefined ? 1 : cardProgress.value; + const progress = cardProgress.value; + const travel = Platform.OS === "android" ? cardCoverage.value : cardHeight.value; return { maxHeight: maxHeight.value, - transform: [{ translateY: (1 - progress) * cardHeight.value }], + opacity: + Platform.OS === "android" + ? Math.min(1, (progress * cardHeight.value) / Math.max(1, cardHeight.value - travel)) + : 1, + transform: [{ translateY: (1 - progress) * travel }], }; }); - const cardMaxHeightStyle = useAnimatedStyle(() => ({ maxHeight: maxHeight.value })); + // Android hit-tests inside the parent; its height is also the space the card takes below the feed. + const androidBoundsStyle = useAnimatedStyle(() => ({ + paddingTop: cardCoverage.value * cardProgress.value, + })); const overlayHeightStyle = useAnimatedStyle(() => ({ height: maxHeight.value })); - // Keep the iOS card mounted so expansion starts on the UI thread without waiting for React layout. - const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed; - const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY; - const bar = showBar ? ( + const bar = ( ) : null} - ) : null; - const card = renderCard ? ( + ); + const card = ( ) : null} - ) : null; + ); return ( - + {bar} - {EXPANDED_CARD_IS_OVERLAY ? ( - - {card} - - ) : ( - card - )} - + + {card} + + ); } diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index afceb0b78b69a..5a427ca803369 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -292,6 +292,7 @@ export interface ThreadDetailScreenProps { text: string, hasAttachmentsOrContext: boolean, ) => Promise, + onWillEnqueue?: () => void, ) => Promise; readonly onReconnectEnvironment: () => void; readonly canSwitchThreadProvider: boolean; @@ -512,6 +513,8 @@ function ThreadDetailBody( }, COMPOSER_HEIGHT_SETTLE_MS); }; const [anchorMessageId, setAnchorMessageId] = useState(null); + const [sendingWithKeyboard, setSendingWithKeyboard] = useState(false); + if (sendingWithKeyboard && !isKeyboardVisible) setSendingWithKeyboard(false); const feedRef = useRef(null); const [endFollowEnabled, setEndFollowEnabled] = useState(true); // Keep the bottom padding fixed while the keyboard animates. Changing it at @@ -908,6 +911,7 @@ function ThreadDetailBody( readonly collapsed: boolean; } | null>(null); const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null; + const questionInFlow = Platform.OS === "android" && activeUserInputRequestId !== null; const composerSlotHidden = activeUserInputRequestId !== null || props.creationState?.kind === "failed"; const pendingMessageEditBlocked = @@ -1011,7 +1015,7 @@ function ThreadDetailBody( const usageLimitsOpen = usageLimitsReport !== null && activeUserInputRequestId === null; const [usageLimitsLayout, setUsageLimitsLayout] = useState({ overlay: 0, panel: 0 }); const handleComposerOverlayLayout = (event: LayoutChangeEvent) => { - onComposerLayout(event); + if (!questionInFlow) onComposerLayout(event); if (!usageLimitsOpen) return; const overlay = event.nativeEvent.layout.height; setUsageLimitsLayout((current) => @@ -1072,12 +1076,9 @@ function ThreadDetailBody( } overlayRepinTimerRef.current = setTimeout(() => { overlayRepinTimerRef.current = null; - if (!endFollowEnabledRef.current) { - return; - } - void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => { - freeze.set(false); - }); + const list = listRef.current; + if (!endFollowEnabledRef.current || !list || list.getState().isAtEnd) return; + void list.scrollToEnd({ animated: Platform.OS === "ios" && !reduceMotion }); }, delayMs); }; // LegendList does not re-anchor short followed conversations when floating @@ -1101,20 +1102,24 @@ function ThreadDetailBody( ), [floatingCoverageTarget], ); - // Android measures its expanded card in-flow; only iOS needs extra overlay coverage. const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null; + const questionStatusSpace = useAnimatedStyle(() => ({ height: floatingControlCoverage.value })); const combinedContentInsetEndAdjustment = useSharedValue( Math.max(0, estimatedOverlayHeight - nativeInsetOvercount), ); useAnimatedReaction( () => - contentInsetEndAdjustment.value + - floatingControlCoverage.value + - (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0), + questionInFlow + ? 0 + : contentInsetEndAdjustment.value + + floatingControlCoverage.value + + (userInputCoverageApplies + ? userInputInsetProgress.value * userInputCardCoverage.value + : 0), (value) => { combinedContentInsetEndAdjustment.set(value); }, - [userInputCoverageApplies], + [questionInFlow, userInputCoverageApplies], ); const composerPopoverLift = useDerivedValue(() => withTiming( @@ -1152,11 +1157,11 @@ function ThreadDetailBody( } if (userInputCollapsed) { setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: false }); - scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50); + if (!questionInFlow) scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50); } else { Keyboard.dismiss(); setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: true }); - scheduleOverlayRepin(60); + if (!questionInFlow) scheduleOverlayRepin(60); } }; const showContent = props.showContent ?? true; @@ -1264,7 +1269,18 @@ function ThreadDetailBody( ); } : undefined; - const messageId = await props.onSendMessage(followUp, declineBeforeDispatch); + let dismissingKeyboard = false; + const messageId = await props.onSendMessage(followUp, declineBeforeDispatch, () => { + if ( + scope.aborted || + Platform.OS !== "ios" || + !hasUserMessage || + !KeyboardController.isVisible() + ) + return; + setSendingWithKeyboard(true); + dismissingKeyboard = true; + }); if (messageId === null || scope.aborted) { return messageId; } @@ -1281,19 +1297,18 @@ function ThreadDetailBody( }); feedRef.current?.resetEndFollow(); setAnchorMessageId(nextAnchorMessageId); - composerEditorRef.current?.blur(); - // The send enqueued the message optimistically, so it is in the feed or - // the queue by the next frame, once the new anchor has rendered. - if (nextAnchorMessageId === messageId && contentPresentationKind === "ready") { + if (!dismissingKeyboard) composerEditorRef.current?.blur(); + const followSubmission = + contentPresentationKind === "ready" && + (dismissingKeyboard || nextAnchorMessageId === messageId); + if (dismissingKeyboard || followSubmission) { + // Commit the optimistic row before UIKit chooses the closing scroll offset. requestAnimationFrame(() => { if (scope.aborted) return; - // Wait for the keyboard to finish dismissing: scrollMessageToEnd freezes - // keyboard-driven inset updates, and a close event swallowed by that - // freeze leaves a phantom bottom inset. + // Scrolling freezes the keyboard inset, so wait until dismissal has removed it. void KeyboardController.dismiss() .then(() => { - // A scroll during the dismissal turns end-follow off; leave the reader where they are. - if (scope.aborted || !endFollowEnabledRef.current) return; + if (!followSubmission || scope.aborted || !endFollowEnabledRef.current) return; return scrollMessageToEnd({ animated: !reduceMotion, closeKeyboard: false }); }) .catch(() => { @@ -1451,10 +1466,14 @@ function ThreadDetailBody( ref={feedRef} contentInsetEndAdjustment={combinedContentInsetEndAdjustment} keyboardOffset={composerKeyboardOffset} + sendingWithKeyboard={sendingWithKeyboard} + fitShortFeedToViewport={questionInFlow && !isKeyboardVisible} contentTopInset={0} contentBottomInset={ - estimatedOverlayHeight + - (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0) + questionInFlow + ? 0 + : estimatedOverlayHeight + + (showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0) } contentMaxWidth={contentMaxWidth} historyControls={props.historyControls} @@ -1488,24 +1507,45 @@ function ThreadDetailBody( -
    diff --git a/apps/web/src/components/chat/timelineMinimapItems.test.ts b/apps/web/src/components/chat/timelineMinimapItems.test.ts index a72813d8f755b..776cd39096a8a 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.test.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.test.ts @@ -15,7 +15,6 @@ describe("deriveTimelineMinimapItems", () => { id: "image-only", createdAt: at, showAssistantMeta: false, - showAssistantTimestamp: false, showAssistantCopyButton: false, assistantCopyStreaming: false, message: { From bad610bec9c39ec5a43fe6598087dcefccc28893 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 15:20:06 -0800 Subject: [PATCH 061/163] perf(server): idle compaction reads only the latest run, live work and newest usage (#29648) Co-authored-by: Claude Opus 5.5 --- .../orchestration-v2/IdleCompactionService.ts | 17 +- .../orchestration-v2/ProjectionStore.test.ts | 164 ++++++++++++++++++ .../src/orchestration-v2/ProjectionStore.ts | 48 ++++- 3 files changed, 222 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/IdleCompactionService.ts b/apps/server/src/orchestration-v2/IdleCompactionService.ts index ce47b0f697700..3b3b788b183a5 100644 --- a/apps/server/src/orchestration-v2/IdleCompactionService.ts +++ b/apps/server/src/orchestration-v2/IdleCompactionService.ts @@ -50,6 +50,8 @@ export const make = Effect.gen(function* () { ) ) return; + const activeProviderThreadIds = + thread.activeProviderThreadId === null ? [] : [thread.activeProviderThreadId]; const records = yield* projections.getThreadRecords( threadId, [ @@ -61,7 +63,20 @@ export const make = Effect.gen(function* () { "turnItems", "contextTransfers", ], - { messageRunIds: [runId], turnItemStatuses: ["pending", "running", "waiting"] }, + { + messageRunIds: [runId], + turnItemStatuses: ["pending", "running", "waiting"], + // The latest run, active runs that hold background work, and rolled-back runs whose + // items it ignores. + runStatuses: ["preparing", "starting", "running", "rolled_back"], + includeLatestRun: true, + // Without an active provider thread there is no session to compact. + providerThreadIds: activeProviderThreadIds, + providerTurnThreadIds: activeProviderThreadIds, + latestProviderTurnUsageOnly: true, + runtimeRequestStatuses: ["pending"], + contextTransferStatuses: ["pending"], + }, ); if ( resolveIdleCompaction(current, records.thread.providerInstanceId) !== diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 4b72c9610c5ed..d447547549760 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -4,6 +4,7 @@ import { EventId, CommandId, CheckpointId, + ContextTransferId, CheckpointRef, CheckpointScopeId, MessageId, @@ -307,6 +308,169 @@ it.effect("record reads restrict provider histories to delivery identities", () }).pipe(Effect.provide(layerTest)), ); +it.effect("idle compaction filters keep the latest run, live work and the newest usage", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + // Its rolled-back run 1 still has a running item, which background work must ignore. + const threadId = yield* addRolledBackRecoveryCandidate("idle-compaction"); + const now = yield* DateTime.now; + const minutes = (count: number) => DateTime.add(now, { minutes: count }); + const selected = ProviderThreadId.make("provider-thread:idle-selected"); + const nodeId = NodeId.make("node:idle-compaction"); + for (const [ordinal, status] of [ + [2, "completed"], + [3, "completed"], + [4, "failed"], + ] as const) { + const runId = RunId.make(`run:idle-compaction:${ordinal}`); + yield* store.apply({ + id: EventId.make(`event:idle-compaction:run-${ordinal}`), + type: "run.created", + threadId, + runId, + nodeId, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id: runId, + threadId, + ordinal, + providerInstanceId, + modelSelection, + providerThreadId: selected, + userMessageId: MessageId.make(`message:idle-compaction:${ordinal}`), + rootNodeId: nodeId, + activeAttemptId: null, + status, + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, + }, + }); + } + for (const [id, providerThreadId, ordinal, usageAt] of [ + ["turn:idle-old", selected, 1, minutes(1)], + ["turn:idle-newest", selected, 2, minutes(3)], + ["turn:idle-later-ordinal", selected, 3, minutes(2)], + ["turn:idle-no-usage", selected, 4, null], + [ + "turn:idle-other-thread", + ProviderThreadId.make("provider-thread:idle-other"), + 1, + minutes(9), + ], + ] as const) { + yield* store.apply({ + id: EventId.make(`event:${id}`), + type: "provider-turn.updated", + threadId, + nodeId, + driver, + occurredAt: now, + payload: { + id: ProviderTurnId.make(id), + providerThreadId, + nodeId, + runAttemptId: null, + nativeTurnRef: null, + ordinal, + status: "completed", + startedAt: now, + completedAt: now, + ...(usageAt === null + ? {} + : { tokenUsage: { usedTokens: 150_000, updatedAt: DateTime.formatIso(usageAt) } }), + }, + }); + } + for (const status of ["pending", "resolved"] as const) { + yield* store.apply({ + id: EventId.make(`event:idle-compaction:request-${status}`), + type: "runtime-request.updated", + threadId, + nodeId, + occurredAt: now, + payload: { + id: RuntimeRequestId.make(`request:idle-compaction:${status}`), + nodeId, + providerTurnId: null, + nativeRequestRef: null, + kind: "user_input", + status, + responseCapability: { type: "message" }, + createdAt: now, + resolvedAt: status === "pending" ? null : now, + }, + }); + } + for (const status of ["pending", "consumed"] as const) { + yield* store.apply({ + id: EventId.make(`event:idle-compaction:transfer-${status}`), + type: "context-transfer.created", + threadId, + occurredAt: now, + payload: { + id: ContextTransferId.make(`transfer:idle-compaction:${status}`), + type: "merge_back", + sourceThreadId: ThreadId.make("thread:idle-compaction:side"), + targetThreadId: threadId, + sourcePoint: { threadId: ThreadId.make("thread:idle-compaction:side") }, + basePoint: null, + sourceProviderInstanceId: providerInstanceId, + targetProviderInstanceId: providerInstanceId, + targetRunId: null, + status, + resolution: null, + createdBy: "user", + error: null, + createdAt: now, + updatedAt: now, + consumedAt: status === "pending" ? null : now, + }, + }); + } + + const records = yield* store.getThreadRecords( + threadId, + ["runs", "providerTurns", "runtimeRequests", "contextTransfers"], + { + runStatuses: ["preparing", "starting", "running", "rolled_back"], + includeLatestRun: true, + providerTurnThreadIds: [selected], + latestProviderTurnUsageOnly: true, + runtimeRequestStatuses: ["pending"], + contextTransferStatuses: ["pending"], + }, + ); + // The failed latest run stays, so a completed earlier run is not mistaken for the latest. + assert.deepEqual( + records.runs.map((run) => run.id), + ["run:idle-compaction:rolled-back", "run:idle-compaction:4"], + ); + assert.deepEqual( + records.providerTurns.map((turn) => turn.id), + ["turn:idle-newest"], + ); + assert.deepEqual( + records.runtimeRequests.map((request) => request.id), + ["request:idle-compaction:pending"], + ); + assert.deepEqual( + records.contextTransfers.map((transfer) => transfer.id), + ["transfer:idle-compaction:pending"], + ); + const empty = yield* store.getThreadRecords(threadId, ["runs", "providerTurns"], { + runStatuses: [], + providerTurnThreadIds: [], + latestProviderTurnUsageOnly: true, + }); + assert.deepEqual([empty.runs, empty.providerTurns], [[], []]); + }).pipe(Effect.provide(layerTest)), +); + it.effect("record reads filter notification sources without dropping matching message bodies", () => Effect.gen(function* () { const store = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 1fd0944aa2583..66fc1d985e92a 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -25,6 +25,7 @@ import type { OrchestrationV2PendingRuntimeRequestSummary, PlanId, OrchestrationV2ConversationMessage, + OrchestrationV2ContextTransfer, OrchestrationV2DomainEvent, OrchestrationV2OlderSettledCount, OrchestrationV2OlderSettledCursor, @@ -32,6 +33,7 @@ import type { OrchestrationV2ProviderThread, OrchestrationV2ProviderTurn, OrchestrationV2Run, + OrchestrationV2RuntimeRequest, OrchestrationV2Subagent, OrchestrationV2ThreadShellSnapshot, OrchestrationV2ShellThreadStatus, @@ -339,6 +341,14 @@ export interface ProjectionRecordFilter { readonly turnItemRunIds?: ReadonlyArray; readonly turnItemNodeIds?: ReadonlyArray; readonly runIds?: ReadonlyArray; + readonly runStatuses?: ReadonlyArray; + /** Keeps the thread's highest-ordinal run even when `runStatuses` excludes it. */ + readonly includeLatestRun?: true; + readonly providerTurnThreadIds?: ReadonlyArray; + /** Only the provider turn whose token usage was updated last. */ + readonly latestProviderTurnUsageOnly?: true; + readonly runtimeRequestStatuses?: ReadonlyArray; + readonly contextTransferStatuses?: ReadonlyArray; readonly subagentIds?: ReadonlyArray; readonly subagentRunIds?: ReadonlyArray; readonly nodeIds?: ReadonlyArray; @@ -3244,7 +3254,9 @@ export const layer: Layer.Layer = ] = yield* Effect.all([ decodeThreadPayload(threadRow.payload_json), (fields !== undefined && !fields.includes("runs")) || - (window === undefined && matchesNothing(filter?.runIds)) + (window === undefined && + (matchesNothing(filter?.runIds) || + (matchesNothing(filter?.runStatuses) && filter?.includeLatestRun !== true))) ? Effect.succeed([]) : window === undefined ? sql` @@ -3252,6 +3264,17 @@ export const layer: Layer.Layer = FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId} ${filter?.runIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.runIds)}))`} + ${ + filter?.runStatuses === undefined + ? sql`` + : sql`AND (status IN (SELECT value FROM json_each(${encodeIdList(filter.runStatuses)})) + OR (${filter.includeLatestRun === true ? 1 : 0} = 1 AND run_id = ( + SELECT run_id FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} + ORDER BY ordinal DESC + LIMIT 1 + )))` + } ORDER BY ordinal ASC ` : sql` @@ -3421,7 +3444,8 @@ export const layer: Layer.Layer = ORDER BY COALESCE(first_run_ordinal, 0), provider_thread_id ASC `, (fields !== undefined && !fields.includes("providerTurns")) || - (window === undefined && matchesNothing(filter?.providerTurnAttemptIds)) + (window === undefined && + matchesNothing(filter?.providerTurnAttemptIds, filter?.providerTurnThreadIds)) ? Effect.succeed([]) : window === undefined ? sql` @@ -3429,7 +3453,15 @@ export const layer: Layer.Layer = FROM orchestration_v2_projection_provider_turns WHERE thread_id = ${threadId} ${filter?.providerTurnAttemptIds === undefined ? sql`` : sql`AND run_attempt_id IN (SELECT value FROM json_each(${encodeIdList(filter.providerTurnAttemptIds)}))`} - ORDER BY provider_thread_id ASC, ordinal ASC + ${filter?.providerTurnThreadIds === undefined ? sql`` : sql`AND provider_thread_id IN (SELECT value FROM json_each(${encodeIdList(filter.providerTurnThreadIds)}))`} + ${ + filter?.latestProviderTurnUsageOnly === true + ? sql`AND json_extract(payload_json, '$.tokenUsage') IS NOT NULL + ORDER BY julianday(json_extract(payload_json, '$.tokenUsage.updatedAt')) DESC, + provider_thread_id ASC, ordinal ASC + LIMIT 1` + : sql`ORDER BY provider_thread_id ASC, ordinal ASC` + } ` : sql` SELECT payload_json FROM orchestration_v2_projection_provider_turns @@ -3439,13 +3471,15 @@ export const layer: Layer.Layer = OR node_id IN (SELECT value FROM json_each(${cohortNodeIds}))) ORDER BY provider_thread_id ASC, ordinal ASC `, - fields !== undefined && !fields.includes("runtimeRequests") + (fields !== undefined && !fields.includes("runtimeRequests")) || + (window === undefined && matchesNothing(filter?.runtimeRequestStatuses)) ? Effect.succeed([]) : window === undefined ? sql` SELECT payload_json FROM orchestration_v2_projection_runtime_requests WHERE thread_id = ${threadId} + ${filter?.runtimeRequestStatuses === undefined ? sql`` : sql`AND status IN (SELECT value FROM json_each(${encodeIdList(filter.runtimeRequestStatuses)}))`} ORDER BY created_at ASC, runtime_request_id ASC ` : sql` @@ -3560,13 +3594,15 @@ export const layer: Layer.Layer = ) ORDER BY rowid ASC `, - fields !== undefined && !fields.includes("contextTransfers") + (fields !== undefined && !fields.includes("contextTransfers")) || + (window === undefined && matchesNothing(filter?.contextTransferStatuses)) ? Effect.succeed([]) : window === undefined ? sql` SELECT payload_json FROM orchestration_v2_projection_context_transfers - WHERE source_thread_id = ${threadId} OR target_thread_id = ${threadId} + WHERE (source_thread_id = ${threadId} OR target_thread_id = ${threadId}) + ${filter?.contextTransferStatuses === undefined ? sql`` : sql`AND status IN (SELECT value FROM json_each(${encodeIdList(filter.contextTransferStatuses)}))`} ORDER BY rowid ASC ` : sql` From 71646e031a6dc9db1309b3b9dff597f872cf2fd3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 2 Nov 2026 15:20:11 -0800 Subject: [PATCH 062/163] perf(server): cancelling a task reads only the tasks and runs it uses (#29652) Co-authored-by: Claude Opus 5.5 --- .../src/mcp/OrchestratorMcpService.test.ts | 71 +++++++++++++++++-- apps/server/src/mcp/OrchestratorMcpService.ts | 56 +++++++++------ .../src/orchestration-v2/Orchestrator.ts | 10 +++ .../orchestration-v2/ProjectionStore.test.ts | 15 +++- .../src/orchestration-v2/ProjectionStore.ts | 15 ++++ .../ProviderTurnControlService.test.ts | 1 + .../ThreadManagementService.ts | 8 +++ .../src/relay/AgentAwarenessRelay.test.ts | 1 + 8 files changed, 147 insertions(+), 30 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 47a6bda166ce1..d463b066b7e40 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -65,6 +65,7 @@ import type { McpInvocationScope } from "./McpInvocationContext.ts"; import { idleThreadProjection, liveThreadShell } from "./McpToolAccess.testkit.ts"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import { resolveRuntimeMode } from "./delegatedTaskModes.ts"; +import type { ProjectionRecordFilter } from "../orchestration-v2/ProjectionStore.ts"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; const decodeTarget = Schema.decodeUnknownEffect(OrchestratorMcpTarget); @@ -453,6 +454,7 @@ describe("OrchestratorMcpService", () => { getThreadRecords: (threadId) => Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), + listAppOwnedChildThreadIds: () => Effect.succeed([]), dispatch: (command) => Ref.update(dispatched, (commands) => [...commands, command]).pipe( Effect.as({} as never), @@ -544,6 +546,7 @@ describe("OrchestratorMcpService", () => { ? Effect.map(Ref.get(status), parentProjection) : Effect.succeed(childProjection), getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), + listAppOwnedChildThreadIds: () => Effect.succeed([]), delegatedTaskResultPending: () => Effect.succeed(false), stopDelegatedTasks: () => Effect.void, // The orchestrator's subagent.stop repair is covered in ThreadStop.test.ts. @@ -642,6 +645,7 @@ describe("OrchestratorMcpService", () => { getThreadRecords: (threadId) => Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), + listAppOwnedChildThreadIds: () => Effect.succeed([]), dispatch: (command) => Ref.update(dispatched, (commands) => [...commands, command]).pipe( Effect.andThen(Effect.fail(new Error("simulated stop failure") as never)), @@ -723,6 +727,7 @@ describe("OrchestratorMcpService", () => { getThreadRecords: (threadId) => Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), + listAppOwnedChildThreadIds: () => Effect.succeed([]), dispatch: (command) => Ref.update(dispatched, (commands) => [...commands, command]).pipe( Effect.andThen( @@ -810,6 +815,7 @@ describe("OrchestratorMcpService", () => { getThreadRecords: (threadId) => Effect.succeed(threadId === parentThreadId ? parentProjection : childProjection), getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), + listAppOwnedChildThreadIds: () => Effect.succeed([]), dispatch: (command) => Ref.update(dispatched, (commands) => [...commands, command]).pipe( Effect.andThen( @@ -865,16 +871,25 @@ describe("OrchestratorMcpService", () => { const taskId = NodeId.make("node:mcp-cancel-grandchild-task"); const dispatched = yield* Ref.make>([]); const stoppedBelow = yield* Ref.make(false); - const appOwnedTask = (id: string, threadId: ThreadId, childId: ThreadId) => ({ + const subagentReads = yield* Ref.make>([]); + const appOwnedTask = ( + id: string, + threadId: ThreadId, + childId: ThreadId, + settled?: "settled", + ) => ({ id: NodeId.make(id), threadId, origin: "app_owned", childThreadId: childId, driver: "codex", model: "gpt-5.6-terra", - result: null, - completionDelivery: { state: "pending" }, + status: settled === undefined ? "running" : "completed", + result: settled === undefined ? null : "Done.", + completionDelivery: { state: settled === undefined ? "pending" : "delivered" }, }); + // Older tasks the parent and child dispatched and that have long settled. + const settledThreadId = ThreadId.make("thread:mcp-cancel-grandchild-settled"); const projections = new Map([ [ parentThreadId, @@ -886,7 +901,15 @@ describe("OrchestratorMcpService", () => { }, runs: [], contextTransfers: [], - subagents: [appOwnedTask(taskId, parentThreadId, childThreadId)], + subagents: [ + appOwnedTask( + "node:mcp-cancel-grandchild-old", + parentThreadId, + settledThreadId, + "settled", + ), + appOwnedTask(taskId, parentThreadId, childThreadId), + ], }, ], [ @@ -897,12 +920,30 @@ describe("OrchestratorMcpService", () => { contextTransfers: [], messages: [], subagents: [ + appOwnedTask( + "node:mcp-cancel-grandchild-done", + childThreadId, + settledThreadId, + "settled", + ), appOwnedTask("node:mcp-cancel-grandchild-below", childThreadId, grandchildThreadId), ], providerThreads: [], runtimeRequests: [], }, ], + [ + settledThreadId, + { + thread: { id: settledThreadId }, + runs: [], + contextTransfers: [], + messages: [], + subagents: [], + providerThreads: [], + runtimeRequests: [], + }, + ], [ grandchildThreadId, { @@ -919,7 +960,21 @@ describe("OrchestratorMcpService", () => { const layerDependencies = Layer.mergeAll( NodeServices.layer, Layer.mock(ThreadManagementService.ThreadManagementService)({ - getThreadRecords: (threadId) => Effect.succeed(projections.get(threadId)!), + getThreadRecords: (threadId, fields, filter) => + ((fields as ReadonlyArray).includes("subagents") + ? Ref.update(subagentReads, (reads) => [...reads, filter]) + : Effect.void + ).pipe(Effect.as(projections.get(threadId)!)), + listAppOwnedChildThreadIds: (threadId) => + Effect.succeed( + projections + .get(threadId)! + .subagents.flatMap((task) => + task.origin === "app_owned" && task.childThreadId !== null + ? [task.childThreadId] + : [], + ), + ), getThreadShell: (threadId) => Effect.succeed( threadId === grandchildThreadId && child.raisedDuringStop !== true @@ -982,6 +1037,12 @@ describe("OrchestratorMcpService", () => { const error = yield* service .cancelTask(scope, { taskId, clientRequestId: "cancel-grandchild-above-modes" }) .pipe(Effect.flip); + // No read decodes every task a thread has dispatched. + for (const filter of yield* Ref.get(subagentReads)) { + assert.isTrue( + filter?.subagentIds !== undefined || filter?.omitSettledSubagents !== undefined, + ); + } return { code: error.code, dispatched: yield* Ref.get(dispatched), diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 910a1531aedb8..0d59dfd4940ca 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -92,6 +92,10 @@ import { DispatchModeLimit, type DispatchModeRefusal, } from "../orchestration-v2/DispatchModeLimit.ts"; +import type { + ProjectionRecordField, + ProjectionRecordFilter, +} from "../orchestration-v2/ProjectionStore.ts"; import { runOutcome } from "../orchestration-v2/RestartBackgroundNote.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; @@ -1047,21 +1051,13 @@ const make = Effect.gen(function* () { ), ); - const loadProjection = (threadId: ThreadId, includeUserMessages = true) => + const loadThreadRecords = ( + threadId: ThreadId, + fields: ReadonlyArray, + filter?: ProjectionRecordFilter, + ) => threadManagement - .getThreadRecords( - threadId, - [ - "runs", - "messages", - "providerThreads", - "providerTurns", - "runtimeRequests", - "contextTransfers", - "turnItems", - ], - { turnItemTypes: [], messageRoles: includeUserMessages ? ["user"] : [] }, - ) + .getThreadRecords(threadId, fields, filter) .pipe( Effect.mapError((error) => failure( @@ -1071,6 +1067,21 @@ const make = Effect.gen(function* () { ), ); + const loadProjection = (threadId: ThreadId, includeUserMessages = true) => + loadThreadRecords( + threadId, + [ + "runs", + "messages", + "providerThreads", + "providerTurns", + "runtimeRequests", + "contextTransfers", + "turnItems", + ], + { turnItemTypes: [], messageRoles: includeUserMessages ? ["user"] : [] }, + ); + // A dispatcher thread holds thousands of tasks, each with its full prompt; read only the ones named. const loadTasks = (threadId: ThreadId, taskIds: ReadonlyArray) => threadManagement.getThreadRecords(threadId, ["subagents"], { subagentIds: taskIds }).pipe( @@ -1491,7 +1502,8 @@ const make = Effect.gen(function* () { "runtimeRequests", "nodes", ], - { messageRoles: ["user"], omitSettledLeafNodes: true }, + // Progress reads only active or undelivered tasks under the child. + { messageRoles: ["user"], omitSettledLeafNodes: true, omitSettledSubagents: true }, ) .pipe(Effect.mapError(threadManagementFailure)); const childRun = delegatedTaskRun(childControls, task); @@ -2537,7 +2549,7 @@ const make = Effect.gen(function* () { return yield* remoteDelegation.cancel(scope, remoteTask, input); } const key = yield* requestKey(input.clientRequestId); - const parentProjection = yield* loadProjection(scope.thread.threadId); + const parentProjection = yield* loadThreadRecords(scope.thread.threadId, []); // Cancelling stops the child and every task under it, each a write to a // thread its user may have raised above the parent's modes since it was // delegated. All of them are checked before anything is stopped. @@ -2554,13 +2566,11 @@ const make = Effect.gen(function* () { shell.interactionMode, ); } - const { subagents } = yield* threadManagement - .getThreadRecords(threadId, ["subagents"]) + const childThreadIds = yield* threadManagement + .listAppOwnedChildThreadIds(threadId) .pipe(Effect.mapError(threadManagementFailure)); - for (const task of subagents) { - if (task.origin === "app_owned" && task.childThreadId !== null) { - yield* assertStoppable(task.childThreadId); - } + for (const childThreadId of childThreadIds) { + yield* assertStoppable(childThreadId); } }); yield* assertStoppable(childThreadId); @@ -2701,7 +2711,7 @@ const make = Effect.gen(function* () { status: cancelled ? "cancelled" : current.status, } satisfies OrchestratorMcpTaskCancelResult; } - const child = yield* loadProjection(childThreadId); + const child = yield* loadThreadRecords(childThreadId, ["runs"]); if ( current.workState !== "waiting_for_children" && ThreadManagementService.latestActiveRun(child) === undefined && diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 2d57df568a499..035bd9c73db66 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -410,6 +410,9 @@ export interface OrchestratorV2Shape { fields: ReadonlyArray, filter?: ProjectionRecordFilter, ) => Effect.Effect, OrchestratorV2Error>; + readonly listAppOwnedChildThreadIds: ( + threadId: ThreadId, + ) => Effect.Effect, OrchestratorV2Error>; readonly getThreadProjection: ( threadId: ThreadId, ) => Effect.Effect; @@ -14046,6 +14049,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); }, ), + listAppOwnedChildThreadIds: Effect.fn("OrchestratorV2.listAppOwnedChildThreadIds")( + function (threadId) { + return projectionStore + .listAppOwnedChildThreadIds(threadId) + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }, + ), getThreadProjection: Effect.fn("OrchestratorV2.getThreadProjection")(function (threadId) { return projectionStore .getThreadProjection(threadId) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index d447547549760..179971019e6e3 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -1182,8 +1182,15 @@ const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { ["running", settledRun, "running", null], ["active-run-delivered", activeRun, "completed", "delivered"], ] as const; + // A follow-up reuses its task's child thread. + const childThreadIds: Partial> = { + delivered: ThreadId.make("thread:settled-subagents:child-a"), + running: ThreadId.make("thread:settled-subagents:child-a"), + "no-delivery": ThreadId.make("thread:settled-subagents:child-b"), + }; for (const [index, [name, run, status, delivery]] of subagents.entries()) { const id = NodeId.make(`node:settled-subagents:${name}`); + const childThreadId = childThreadIds[name] ?? null; yield* store.apply({ id: EventId.make(`event:settled-subagents:item:${name}`), type: "turn-item.updated", @@ -1212,7 +1219,7 @@ const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { origin: "app_owned", driver, providerInstanceId, - childThreadId: null, + childThreadId, prompt: "Do the work", result: null, }, @@ -1236,7 +1243,7 @@ const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { driver, providerInstanceId, providerThreadId: null, - childThreadId: null, + childThreadId, nativeTaskRef: null, prompt: "Do the work", title: name, @@ -1286,6 +1293,10 @@ const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { ["delivered"], ); assert.strictEqual(yield* store.getSubagentCount(threadId), subagents.length); + assert.deepEqual( + [...(yield* store.listAppOwnedChildThreadIds(threadId))], + [childThreadIds.delivered, childThreadIds["no-delivery"]], + ); }); const backgroundThreadUpdatesKeepTimestamp = Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 66fc1d985e92a..ab8d69f9a66d1 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -460,6 +460,10 @@ export interface ProjectionStoreV2Shape { ) => Effect.Effect; readonly getMessageCount: (threadId: ThreadId) => Effect.Effect; readonly getSubagentCount: (threadId: ThreadId) => Effect.Effect; + /** Child threads of the thread's app-owned tasks, in task order, without decoding the tasks. */ + readonly listAppOwnedChildThreadIds: ( + threadId: ThreadId, + ) => Effect.Effect, ProjectionStoreV2Error>; readonly getNextTurnItemOrdinal: ( threadId: ThreadId, ) => Effect.Effect; @@ -5388,6 +5392,16 @@ export const layer: Layer.Layer = Effect.map((rows) => rows[0]?.count ?? 0), Effect.mapError(controlReadError(threadId)), ); + const listAppOwnedChildThreadIds: ProjectionStoreV2Shape["listAppOwnedChildThreadIds"] = ( + threadId, + ) => + sql<{ readonly child_thread_id: string }>`SELECT child_thread_id + FROM orchestration_v2_projection_subagents + WHERE thread_id = ${threadId} AND origin = 'app_owned' AND child_thread_id IS NOT NULL + ORDER BY COALESCE(started_at, ''), subagent_id ASC`.pipe( + Effect.map((rows) => [...new Set(rows.map((row) => ThreadId.make(row.child_thread_id)))]), + Effect.mapError(controlReadError(threadId)), + ); const getNextTurnItemOrdinal: ProjectionStoreV2Shape["getNextTurnItemOrdinal"] = (threadId) => sql<{ ordinal: number | null }>`SELECT MAX(ordinal) AS ordinal FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId}`.pipe( @@ -7141,6 +7155,7 @@ export const layer: Layer.Layer = isNodeStored: readOnReader(isNodeStored), getMessageCount: readOnReader(getMessageCount), getSubagentCount: readOnReader(getSubagentCount), + listAppOwnedChildThreadIds: readOnReader(listAppOwnedChildThreadIds), getNextTurnItemOrdinal: readOnReader(getNextTurnItemOrdinal), getTurnItem: readOnReader(getTurnItem), getThreadRecords: (threadId, fields, filter) => diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 7932a03809c94..77caf03712571 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -237,6 +237,7 @@ it.effect( getTimelinePage: () => Effect.die("Unused timeline read"), getMessageCount: () => Effect.die("unused message count"), getSubagentCount: () => Effect.die("unused subagent count"), + listAppOwnedChildThreadIds: () => Effect.die("unused listAppOwnedChildThreadIds"), getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"), getTurnItem: () => Effect.die("unused turn item read"), getThreadRecords: () => Effect.die("unused record read"), diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index c1727567f9e3d..f0346b2bec4ec 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -419,6 +419,7 @@ export interface ThreadManagementServiceShape { Orchestrator.OrchestratorV2Error >; readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"]; + readonly listAppOwnedChildThreadIds: Orchestrator.OrchestratorV2["Service"]["listAppOwnedChildThreadIds"]; /** Omit `projectId` to list every project's threads. Side chats are never listed. */ readonly listProjectThreads: (input: { readonly projectId?: ProjectId | undefined; @@ -1526,6 +1527,13 @@ const make = Effect.gen(function* () { listOlderSettledThreads: orchestrator.listOlderSettledThreads, readShellSnapshot: orchestrator.readShellSnapshot, getThreadShell: orchestrator.getThreadShell, + listAppOwnedChildThreadIds: Effect.fn("ThreadManagementService.listAppOwnedChildThreadIds")( + function (threadId) { + return ensureProjectionTranscript(threadId).pipe( + Effect.andThen(orchestrator.listAppOwnedChildThreadIds(threadId)), + ); + }, + ), listProjectThreads, sendToThread, assertProviderInstanceEnabled, diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 2a259114b0926..87838fd5a51ed 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -190,6 +190,7 @@ const makeTestRelay = Effect.fnUntraced(function* ( return { schemaVersion: 2, snapshotSequence: 1, threads: [], archivedThreads: [] }; }), listActiveSubagentThreadIds: unused, + listAppOwnedChildThreadIds: unused, countThreads: unused, listActiveShellIndex: () => Effect.succeed([]), listOlderSettledThreads: unused, From 5b9731cedc06f310c394f48e66d50a614397c0aa Mon Sep 17 00:00:00 2001 From: nibarAhmed <61316519+nibarAhmed@users.noreply.github.com> Date: Tue, 3 Nov 2026 01:02:49 +0100 Subject: [PATCH 063/163] fix(web): screen readers can browse and Tab through the threads sidebar again without going into focus mode (#26690) Co-authored-by: nibarAhmed Co-authored-by: Claude Opus 5.5 Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- .../components/ChatView.logic.browser.test.ts | 20 +- apps/web/src/components/ChatView.logic.ts | 2 +- apps/web/src/components/Sidebar.tsx | 8 +- .../components/sidebar/SidebarDraftBlock.tsx | 4 +- .../components/sidebar/SidebarListMarkers.tsx | 2 - .../sidebar/SidebarProjectFolderHeader.tsx | 2 - .../components/sidebar/SidebarThreadRow.tsx | 8 +- apps/web/src/lib/sidebarTree.browser.test.ts | 66 ++---- apps/web/src/lib/sidebarTree.ts | 188 +++++------------- apps/web/src/lib/workspaceFocus.ts | 2 +- docs/user/keyboard-focus.md | 6 +- 11 files changed, 99 insertions(+), 209 deletions(-) diff --git a/apps/web/src/components/ChatView.logic.browser.test.ts b/apps/web/src/components/ChatView.logic.browser.test.ts index e1c1f04a0c3a5..233af7115eeb3 100644 --- a/apps/web/src/components/ChatView.logic.browser.test.ts +++ b/apps/web/src/components/ChatView.logic.browser.test.ts @@ -3,20 +3,20 @@ import { userEvent } from "vite-plus/test/browser"; import { shouldRefocusComposerOnWindowFocus } from "./ChatView.logic"; it("keeps keyboard focus on a sidebar row on window return, but not a clicked row", async () => { - const tree = document.createElement("div"); - tree.setAttribute("role", "tree"); - const row = (name: string, tabIndex: number) => { + const list = document.createElement("ul"); + const row = (name: string) => { const element = document.createElement("div"); - element.setAttribute("role", "treeitem"); - element.tabIndex = tabIndex; + element.setAttribute("role", "button"); + element.tabIndex = 0; + element.dataset.sidebarRow = name; element.textContent = name; - tree.append(element); + list.append(element); return element; }; - const clicked = row("Clicked thread", -1); - const tabbed = row("Tabbed thread", 0); - document.body.append(tree); - using _tree = { [Symbol.dispose]: () => tree.remove() }; + const clicked = row("Clicked thread"); + const tabbed = row("Tabbed thread"); + document.body.append(list); + using _list = { [Symbol.dispose]: () => list.remove() }; await userEvent.click(clicked); expect(document.activeElement).toBe(clicked); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 93468b9e04abf..229b72b035e78 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1166,7 +1166,7 @@ export function shouldRefocusComposerOnWindowFocus( } return ( activeElement.closest( - '[data-workspace-area]:focus-visible, [role="treeitem"]:focus-visible, [role="dialog"], [role="alertdialog"], [role="application"], [role="menu"], [role="listbox"], [data-slot$="-popup"], [data-terminal-owner]', + '[data-workspace-area]:focus-visible, [data-sidebar-row]:focus-visible, [role="dialog"], [role="alertdialog"], [role="application"], [role="menu"], [role="listbox"], [data-slot$="-popup"], [data-terminal-owner]', ) === null ); } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index deede26763fdd..8eb32a605822a 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,5 +1,5 @@ import { liveShellEnvironmentIdsAtom } from "../state/shell"; -import { attachSidebarTree, SIDEBAR_TREE_PROPS } from "../lib/sidebarTree"; +import { attachSidebarTree } from "../lib/sidebarTree"; import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts"; import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; import { ThreadContextDragGhost } from "./chat/ThreadContextDragGhost"; @@ -3292,8 +3292,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve >