diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index f679f23df1..726954682c 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -1071,50 +1071,15 @@ export function HomeScreen(props: HomeScreenProps) { onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined} variant="plain" /> -<<<<<<< HEAD -<<<<<<< HEAD {emptyState.loading ? ( -======= - {emptyState.loading && !shouldShowConnectionStatus ? ( ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) ) : null} -<<<<<<< HEAD ); } -======= - ) : !hasResults ? ( - - ) : ( - projectGroups.map((group) => { - const isExpanded = expandedProjects.has(group.key); - const visibleThreads = isExpanded - ? group.threads - : group.threads.slice(0, COLLAPSED_THREAD_LIMIT); ->>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover) -======= - {shouldShowConnectionStatus && Platform.OS === "ios" ? ( - - - - ) : null} - - {connectionStatus} - - ); - } ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) const listHeader = Platform.OS === "ios" ? null : ; diff --git a/apps/mobile/src/lib/modelOptions.ts b/apps/mobile/src/lib/modelOptions.ts index cb7a8c4198..8f3f8c34a4 100644 --- a/apps/mobile/src/lib/modelOptions.ts +++ b/apps/mobile/src/lib/modelOptions.ts @@ -1,3 +1,4 @@ +import type { MenuAction } from "@react-native-menu/menu"; import type { ModelCapabilities, ModelSelection, @@ -187,3 +188,53 @@ export function groupByProvider(options: ReadonlyArray): ReadonlyAr models: group.models, })); } + +function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction { + return { + id: `model:${option.key}`, + title: option.label, + state: + option.selection.instanceId === selectedModel?.instanceId && + option.selection.model === selectedModel.model + ? "on" + : undefined, + }; +} + +export function buildModelMenuActions( + groups: ReadonlyArray, + selectedModel: ModelSelection | null, +): MenuAction[] { + return groups.flatMap((group) => { + const currentModels = group.models.filter((model) => !model.isLegacy); + const legacyModels = group.models.filter((model) => model.isLegacy); + const selected = group.models.find( + (model) => + model.selection.instanceId === selectedModel?.instanceId && + model.selection.model === selectedModel.model, + ); + + return [ + ...(currentModels.length > 0 + ? [ + { + id: `provider:${group.providerKey}`, + title: group.providerLabel, + subtitle: selected && !selected.isLegacy ? selected.label : undefined, + subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)), + }, + ] + : []), + ...(legacyModels.length > 0 + ? [ + { + id: `legacy-models:${group.providerKey}`, + title: `${group.providerLabel} legacy models`, + subtitle: selected?.isLegacy ? selected.label : undefined, + subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)), + }, + ] + : []), + ]; + }); +} diff --git a/apps/mobile/src/lib/projectThreadStartTurn.ts b/apps/mobile/src/lib/projectThreadStartTurn.ts index f8461e494b..37171c2d88 100644 --- a/apps/mobile/src/lib/projectThreadStartTurn.ts +++ b/apps/mobile/src/lib/projectThreadStartTurn.ts @@ -79,3 +79,13 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe createdAt: spec.createdAt, }; } + +export function deriveThreadTitleFromPrompt(value: string): string { + const trimmed = value.trim(); + if (trimmed.length === 0) { + return "New thread"; + } + + const compact = trimmed.replace(/\s+/g, " "); + return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`; +} diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 5d0355d883..6742b60bf0 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -145,24 +145,7 @@ function resolvePendingUserInputAnswer( draft: PendingUserInputDraftAnswer | undefined, ): string | null { return ( -<<<<<<< HEAD - normalized.includes("file not found") || - normalized.includes("no files found") || - normalized.includes("enoent") || - normalized.includes("no such file or directory") || - normalized.includes("no such file") || - normalized.includes("commandnotfoundexception") || - normalized.includes("command not found") || - (normalized.includes("cannot find path") && normalized.includes("because it does not exist")) || - (normalized.includes("is not recognized") && normalized.includes("the term '")) || - normalized.includes("is not recognized as the name of a cmdlet") || - normalized.includes("a parameter cannot be found that matches parameter name") || - //i.test(text) || - /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) || - /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text) -======= normalizeDraftAnswer(draft?.customAnswer) ?? normalizeDraftAnswer(draft?.selectedOptionLabel) ->>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover) ); } diff --git a/apps/server/integration/providerService.integration.test.ts b/apps/server/integration/providerService.integration.test.ts deleted file mode 100644 index 6089d22d9a..0000000000 --- a/apps/server/integration/providerService.integration.test.ts +++ /dev/null @@ -1,386 +0,0 @@ -import type { ProviderRuntimeEvent } from "@t3tools/contracts"; -import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; -import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { it, assert } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; -import * as Path from "effect/Path"; -import * as Queue from "effect/Queue"; -import * as Ref from "effect/Ref"; -import * as Stream from "effect/Stream"; - -import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts"; -import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts"; -import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts"; -import { - NoOpProviderEventLoggers, - ProviderEventLoggers, -} from "../src/provider/Layers/ProviderEventLoggers.ts"; -import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts"; -import { - ProviderService, - type ProviderServiceShape, -} from "../src/provider/Services/ProviderService.ts"; -import * as ServerConfig from "../src/config.ts"; -import { ServerSettingsService } from "../src/serverSettings.ts"; -import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts"; -import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts"; -import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts"; - -import { - makeTestProviderAdapterHarness, - type TestProviderAdapterHarness, - type TestTurnResponse, -} from "./TestProviderAdapter.integration.ts"; -import { - codexTurnApprovalFixture, - codexTurnToolFixture, - codexTurnTextFixture, -} from "./fixtures/providerRuntime.ts"; - -const codexInstanceId = ProviderInstanceId.make("codex"); - -const makeWorkspaceDirectory = Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const pathService = yield* Path.Path; - const cwd = yield* fs.makeTempDirectory(); - yield* fs.writeFileString(pathService.join(cwd, "README.md"), "v1\n"); - return cwd; -}).pipe(Effect.provide(NodeServices.layer)); - -interface IntegrationFixture { - readonly cwd: string; - readonly harness: TestProviderAdapterHarness; - readonly layer: Layer.Layer; -} - -interface RecordedAnalyticsEvent { - readonly event: string; - readonly properties: Readonly> | undefined; -} - -/** - * Analytics layer that keeps captured events in memory so tests can assert on - * telemetry payloads. `AnalyticsService.layerTest` discards them. - */ -const makeRecordingAnalytics = Effect.gen(function* () { - const recorded = yield* Ref.make>([]); - const layer = Layer.succeed( - AnalyticsService, - AnalyticsService.of({ - record: (event, properties) => - Ref.update(recorded, (current) => [...current, { event, properties }]), - flush: Effect.void, - }), - ); - return { layer, get: Ref.get(recorded) } as const; -}); - -const makeIntegrationFixture = (options?: { readonly analytics?: Layer.Layer }) => - Effect.gen(function* () { - const cwd = yield* makeWorkspaceDirectory; - const harness = yield* makeTestProviderAdapterHarness(); - - const registry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("codex")]: harness.adapter, - }); - - const directoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(ProviderSessionRuntime.layer), - ); - - const shared = Layer.mergeAll( - directoryLayer, - Layer.succeed(ProviderAdapterRegistry, registry), - ServerConfig.layerTest(cwd, cwd).pipe(Layer.provide(NodeServices.layer)), - ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS), - options?.analytics ?? AnalyticsService.layerTest, - Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers), - ).pipe(Layer.provide(SqlitePersistenceMemory)); - - const layer = makeProviderServiceLive().pipe(Layer.provide(shared)); - - return { - cwd, - harness, - layer, - } satisfies IntegrationFixture; - }); - -const collectEventsDuring = ( - stream: Stream.Stream, - count: number, - action: Effect.Effect, -) => - Effect.gen(function* () { - const queue = yield* Queue.unbounded(); - yield* Stream.runForEach(stream, (event) => Queue.offer(queue, event).pipe(Effect.asVoid)).pipe( - Effect.forkScoped, - ); - - yield* Effect.sleep("50 millis"); - yield* action; - - return yield* Effect.forEach( - Array.from({ length: count }, () => undefined), - () => Queue.take(queue), - { discard: false }, - ); - }); - -const runTurn = (input: { - readonly provider: ProviderServiceShape; - readonly harness: TestProviderAdapterHarness; - readonly threadId: ThreadId; - readonly userText: string; - readonly response: TestTurnResponse; -}) => - Effect.gen(function* () { - yield* input.harness.queueTurnResponse(input.threadId, input.response); - return yield* collectEventsDuring( - input.provider.streamEvents, - input.response.events.length, - input.provider.sendTurn({ - threadId: input.threadId, - input: input.userText, - attachments: [], - }), - ); - }); - -it.live("replays typed runtime fixture events", () => - Effect.gen(function* () { - const fixture = yield* makeIntegrationFixture(); - - yield* Effect.gen(function* () { - const provider = yield* ProviderService; - const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), { - threadId: ThreadId.make("thread-integration-typed"), - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - cwd: fixture.cwd, - runtimeMode: "full-access", - }); - assert.equal((session.threadId ?? "").length > 0, true); - - const observedEvents = yield* runTurn({ - provider, - harness: fixture.harness, - threadId: session.threadId, - userText: "hello", - response: { events: codexTurnTextFixture }, - }); - - assert.deepEqual( - observedEvents.map((event) => event.type), - codexTurnTextFixture.map((event) => event.type), - ); - assert.deepEqual( - observedEvents.map((event) => event.providerInstanceId), - codexTurnTextFixture.map(() => codexInstanceId), - ); - }).pipe(Effect.provide(fixture.layer)); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.live("replays file-changing fixture turn events", () => - Effect.gen(function* () { - const fixture = yield* makeIntegrationFixture(); - const { join } = yield* Path.Path; - const { writeFileString } = yield* FileSystem.FileSystem; - - yield* Effect.gen(function* () { - const provider = yield* ProviderService; - const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), { - threadId: ThreadId.make("thread-integration-tools"), - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - cwd: fixture.cwd, - runtimeMode: "full-access", - }); - assert.equal((session.threadId ?? "").length > 0, true); - - const observedEvents = yield* runTurn({ - provider, - harness: fixture.harness, - threadId: session.threadId, - userText: "make a small change", - response: { - events: codexTurnToolFixture, - mutateWorkspace: ({ cwd }) => - writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore), - }, - }); - - assert.deepEqual( - observedEvents.map((event) => event.type), - codexTurnToolFixture.map((event) => event.type), - ); - }).pipe(Effect.provide(fixture.layer)); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.live("runs multi-turn tool/approval flow", () => - Effect.gen(function* () { - const fixture = yield* makeIntegrationFixture(); - const { join } = yield* Path.Path; - const { writeFileString } = yield* FileSystem.FileSystem; - - yield* Effect.gen(function* () { - const provider = yield* ProviderService; - const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), { - threadId: ThreadId.make("thread-integration-multi"), - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - cwd: fixture.cwd, - runtimeMode: "full-access", - }); - assert.equal((session.threadId ?? "").length > 0, true); - - const firstTurnEvents = yield* runTurn({ - provider, - harness: fixture.harness, - threadId: session.threadId, - userText: "turn 1", - response: { - events: codexTurnToolFixture, - mutateWorkspace: ({ cwd }) => - writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore), - }, - }); - assert.deepEqual( - firstTurnEvents.map((event) => event.type), - codexTurnToolFixture.map((event) => event.type), - ); - - const secondTurnEvents = yield* runTurn({ - provider, - harness: fixture.harness, - threadId: session.threadId, - userText: "turn 2 approval", - response: { - events: codexTurnApprovalFixture, - mutateWorkspace: ({ cwd }) => - writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore), - }, - }); - assert.deepEqual( - secondTurnEvents.map((event) => event.type), - codexTurnApprovalFixture.map((event) => event.type), - ); - }).pipe(Effect.provide(fixture.layer)); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.live("rolls back provider conversation state only", () => - Effect.gen(function* () { - const fixture = yield* makeIntegrationFixture(); - const { join } = yield* Path.Path; - const { writeFileString, readFileString } = yield* FileSystem.FileSystem; - - yield* Effect.gen(function* () { - const provider = yield* ProviderService; - const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), { - threadId: ThreadId.make("thread-integration-rollback"), - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - cwd: fixture.cwd, - runtimeMode: "full-access", - }); - assert.equal((session.threadId ?? "").length > 0, true); - - yield* runTurn({ - provider, - harness: fixture.harness, - threadId: session.threadId, - userText: "turn 1", - response: { - events: codexTurnToolFixture, - mutateWorkspace: ({ cwd }) => - writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore), - }, - }); - - yield* runTurn({ - provider, - harness: fixture.harness, - threadId: session.threadId, - userText: "turn 2 approval", - response: { - events: codexTurnApprovalFixture, - mutateWorkspace: ({ cwd }) => - writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore), - }, - }); - - yield* provider.rollbackConversation({ - threadId: session.threadId, - numTurns: 1, - }); - - const rollbackCalls = fixture.harness.getRollbackCalls(session.threadId); - assert.deepEqual(rollbackCalls, [1]); - - const readme = yield* readFileString(join(fixture.cwd, "README.md")); - assert.equal(readme, "v3\n"); - }).pipe(Effect.provide(fixture.layer)); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.live("reports runtime mode per turn and on mode transitions", () => - Effect.gen(function* () { - const analytics = yield* makeRecordingAnalytics; - const fixture = yield* makeIntegrationFixture({ analytics: analytics.layer }); - const threadId = ThreadId.make("thread-integration-runtime-mode"); - - yield* Effect.gen(function* () { - const provider = yield* ProviderService; - const startSession = (runtimeMode: "approval-required" | "full-access") => - provider.startSession(threadId, { - threadId, - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - cwd: fixture.cwd, - runtimeMode, - }); - - yield* startSession("approval-required"); - yield* runTurn({ - provider, - harness: fixture.harness, - threadId, - userText: "supervised turn", - response: { events: codexTurnTextFixture }, - }); - - // Toggling the mode restarts the session, which is the only place the - // transition is observable. - yield* startSession("full-access"); - yield* runTurn({ - provider, - harness: fixture.harness, - threadId, - userText: "full access turn", - response: { events: codexTurnTextFixture }, - }); - - const recorded = yield* analytics.get; - - assert.deepEqual( - recorded - .filter((entry) => entry.event === "provider.turn.sent") - .map((entry) => entry.properties?.runtimeMode), - ["approval-required", "full-access"], - ); - - assert.deepEqual( - recorded - .filter((entry) => entry.event === "provider.runtime_mode.changed") - .map((entry) => [entry.properties?.from, entry.properties?.to]), - [["approval-required", "full-access"]], - ); - }).pipe(Effect.provide(fixture.layer)); - }).pipe(Effect.provide(NodeServices.layer)), -); diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index b82bf0f583..a5f8fa659f 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -1018,8 +1018,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { expect(Duration.toMillis(GitManager.prLookupFailureTtl(20))).toBe(900_000); }); - it.effect( - effect( it.effect( "status ignores unrelated fork PRs when the current branch tracks the same repository", () => diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 17ec6290fb..fb209a7de4 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -197,6 +197,7 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId { case "thread.unsnooze": case "thread.pin": case "thread.unpin": + case "thread.pin.reorder": case "thread.visit": case "thread.mark-unread": case "thread.metadata.update": @@ -1346,6 +1347,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio | "thread.unsnooze" | "thread.pin" | "thread.unpin" + | "thread.pin.reorder" | "thread.visit" | "thread.mark-unread" | "thread.metadata.update" @@ -1407,7 +1409,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.type === "thread.snooze" || command.type === "thread.unsnooze" || command.type === "thread.pin" || - command.type === "thread.unpin") && + command.type === "thread.unpin" || + command.type === "thread.pin.reorder") && thread.archivedAt !== null ) { return yield* new OrchestratorDispatchError({ @@ -1416,6 +1419,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Thread ${command.threadId} is archived.`, }); } + // Only pinned threads have a slot in the arranged order. Rejecting + // (rather than silently pinning) keeps a raced reorder-after-unpin from + // resurrecting a pin the user just cleared. + if (command.type === "thread.pin.reorder" && thread.pinnedAt == null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} is not pinned and cannot be reordered.`, + }); + } if ( command.type === "thread.settle" && (projection.runs.some((run) => @@ -1530,6 +1543,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio settledOverride: "settled", settledAt: alreadySettled ? thread.settledAt : now, pinnedAt: null, + pinOrderKey: null, updatedAt: alreadySettled ? thread.updatedAt : now, }; } @@ -1573,6 +1587,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return { ...thread, pinnedAt: alreadyPinned ? thread.pinnedAt : now, + // A fresh pin takes the client's slot in the arranged order; on a + // re-pin the existing key wins so raced duplicates cannot move a + // thread the user already placed. + ...(alreadyPinned || command.orderKey === undefined + ? {} + : { pinOrderKey: command.orderKey }), settledOverride: thread.settledOverride === "settled" ? "active" : thread.settledOverride, settledAt: thread.settledOverride === "settled" ? null : thread.settledAt, @@ -1586,9 +1606,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return { ...thread, pinnedAt: null, + // Unpin clears the slot: re-pinning is "pin again", not "restore + // an ancient position". + pinOrderKey: null, updatedAt: alreadyUnpinned ? thread.updatedAt : now, }; } + case "thread.pin.reorder": { + // Idempotent by re-emission (see thread.settle): a duplicate drop on + // the same slot keeps the existing updatedAt so it projects as a + // no-op. + const keyUnchanged = thread.pinOrderKey === command.orderKey; + return { + ...thread, + pinOrderKey: command.orderKey, + updatedAt: keyUnchanged ? thread.updatedAt : now, + }; + } // Visited tracking records read state only; it must not bump updatedAt, // otherwise viewing a thread would count as activity (and re-trigger the // clients that dispatch thread.visit whenever updatedAt advances). @@ -1660,6 +1694,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return "thread.pinned" as const; case "thread.unpin": return "thread.unpinned" as const; + case "thread.pin.reorder": + return "thread.pin-reordered" as const; case "thread.visit": return "thread.visited" as const; case "thread.mark-unread": @@ -6692,6 +6728,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.unsnooze": case "thread.pin": case "thread.unpin": + case "thread.pin.reorder": case "thread.visit": case "thread.mark-unread": case "thread.metadata.update": diff --git a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts index 8ec03f9117..4a5f6b4df4 100644 --- a/apps/server/src/orchestration-v2/ProjectionMaintenance.ts +++ b/apps/server/src/orchestration-v2/ProjectionMaintenance.ts @@ -232,6 +232,7 @@ export const layer: Layer.Layer< "thread.unsnoozed", "thread.pinned", "thread.unpinned", + "thread.pin-reordered", "thread.metadata-updated", "thread.runtime-mode-updated", "thread.interaction-mode-updated", diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 84fb7e7a89..25263ea93c 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -209,6 +209,7 @@ export function applyToProjection( case "thread.unsnoozed": case "thread.pinned": case "thread.unpinned": + case "thread.pin-reordered": case "thread.metadata-updated": case "thread.runtime-mode-updated": case "thread.interaction-mode-updated": @@ -914,6 +915,7 @@ export function threadShellFromProjection( snoozedUntil: projection.thread.snoozedUntil ?? null, snoozedAt: projection.thread.snoozedAt ?? null, pinnedAt: projection.thread.pinnedAt ?? null, + pinOrderKey: projection.thread.pinOrderKey ?? null, lastVisitedAt: projection.thread.lastVisitedAt, titleRegeneration: projection.thread.titleRegeneration ?? null, deletedAt: projection.thread.deletedAt, @@ -1098,6 +1100,7 @@ function shellFromState(input: { snoozedUntil: input.state.thread.snoozedUntil ?? null, snoozedAt: input.state.thread.snoozedAt ?? null, pinnedAt: input.state.thread.pinnedAt ?? null, + pinOrderKey: input.state.thread.pinOrderKey ?? null, lastVisitedAt: input.state.thread.lastVisitedAt, titleRegeneration: input.state.thread.titleRegeneration ?? null, deletedAt: input.state.thread.deletedAt, @@ -1122,6 +1125,7 @@ export const layer: Layer.Layer = case "thread.unsnoozed": case "thread.pinned": case "thread.unpinned": + case "thread.pin-reordered": case "thread.visited": case "thread.marked-unread": case "thread.metadata-updated": @@ -1923,6 +1927,7 @@ export const layer: Layer.Layer = event.type !== "thread.unsnoozed" && event.type !== "thread.pinned" && event.type !== "thread.unpinned" && + event.type !== "thread.pin-reordered" && event.type !== "thread.visited" && event.type !== "thread.marked-unread" && event.type !== "thread.metadata-updated" && diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index c6a8c24afe..1fa61dcde2 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -780,7 +780,7 @@ export const layer: Layer.Layer< startRootRun: (input) => Effect.gen(function* () { const assistantStreamingEnabled = yield* serverSettings.getSettings.pipe( - Effect.map((settings) => settings.enableAssistantStreaming), + Effect.map((settings) => settings.enableLegacyTokenStreaming), Effect.mapError( (cause) => new RunExecutionStartError({ diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.test.ts b/apps/server/src/orchestration-v2/RuntimePolicy.test.ts index 5e10c592f7..349b4492b9 100644 --- a/apps/server/src/orchestration-v2/RuntimePolicy.test.ts +++ b/apps/server/src/orchestration-v2/RuntimePolicy.test.ts @@ -65,6 +65,7 @@ const TestLayer = layerFromProjectRepository.pipe( title: "Project", workspaceRoot: "/project-root", defaultModelSelection: null, + defaultThreadEnvMode: null, scripts: [], createdAt: "2026-06-21T00:00:00.000Z", updatedAt: "2026-06-21T00:00:00.000Z", diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 57280e6c44..7f8b86b80c 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -51,6 +51,7 @@ const project = { repositoryIdentity: null, faviconPath: null, defaultModelSelection: modelSelection, + defaultThreadEnvMode: null, scripts: [], createdAt: "2026-06-20T00:00:00.000Z", updatedAt: "2026-06-20T00:00:00.000Z", @@ -145,6 +146,7 @@ function makeHarness(options: HarnessOptions = {}) { title: project.title, workspaceRoot: project.workspaceRoot, defaultModelSelection: project.defaultModelSelection, + defaultThreadEnvMode: null, scripts: project.scripts, createdAt: project.createdAt, updatedAt: project.updatedAt, diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts index c7056ae72e..d1b175432c 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.test.ts @@ -65,6 +65,7 @@ function makeHarness( title: "Project", workspaceRoot: "/repo", defaultModelSelection: modelSelection, + defaultThreadEnvMode: null, scripts: [], createdAt: "2026-06-20T00:00:00.000Z", updatedAt: "2026-06-20T00:00:00.000Z", diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts index b822220d76..72f03b21b0 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts @@ -79,7 +79,7 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* < readonly buildInput: () => OrchestratorFixtureInput; readonly driver: ProviderOrchestratorReplayVariant; readonly harness: OrchestratorV2ProviderReplayHarness; - readonly enableAssistantStreaming?: boolean; + readonly enableLegacyTokenStreaming?: boolean; }) { const rawTranscript = yield* readTranscript(input.driver.transcriptFile); const replayTranscript = transcriptEntriesThroughLabel( @@ -111,10 +111,10 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* < }; const result = yield* runOrchestratorV2ProviderReplayScenario(scenario, input.harness, { - enableAssistantStreaming: input.enableAssistantStreaming ?? false, + enableLegacyTokenStreaming: input.enableLegacyTokenStreaming ?? false, }).pipe(provideDeterministicTestRuntime); input.driver.assertOutput(result, transcript); - if (input.enableAssistantStreaming !== true) { + if (input.enableLegacyTokenStreaming !== true) { assert.isFalse( result.domainEvents.some(isStreamingAssistantEvent), "buffered delivery must not persist streaming assistant artifacts", @@ -143,7 +143,7 @@ function runFixtureProviderWithRegisteredHarness(input: { readonly fixtureName: string; readonly buildInput: () => OrchestratorFixtureInput; readonly driver: ProviderOrchestratorReplayVariant; - readonly enableAssistantStreaming?: boolean; + readonly enableLegacyTokenStreaming?: boolean; }) { switch (input.driver.driver) { case "codex": @@ -225,7 +225,7 @@ describe("orchestrator replay fixtures", () => { fixtureName: "simple-cursor-streaming", buildInput: simpleFixture.buildInput, driver: simpleCursorProvider, - enableAssistantStreaming: true, + enableLegacyTokenStreaming: true, }); assert.deepEqual( diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index ba8a13b974..a2e4a06610 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -123,6 +123,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray; - readonly enableAssistantStreaming?: boolean; + readonly enableLegacyTokenStreaming?: boolean; readonly runEffectWorker?: boolean; } = {}, ): Effect.Effect< @@ -211,7 +211,7 @@ export function makeOrchestratorV2ProviderReplayLayer< SqlClient.SqlClient, MigrationError | PlatformError.PlatformError | SqlError >; - readonly enableAssistantStreaming?: boolean; + readonly enableLegacyTokenStreaming?: boolean; readonly runEffectWorker?: boolean; readonly replayGate?: ProviderReplayGate; } = {}, @@ -231,7 +231,7 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( SqlClient.SqlClient, MigrationError | PlatformError.PlatformError | SqlError >; - readonly enableAssistantStreaming?: boolean; + readonly enableLegacyTokenStreaming?: boolean; readonly runEffectWorker?: boolean; } = {}, ): Layer.Layer { @@ -247,7 +247,7 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( ); const databaseLayer = options.databaseLayer ?? SqlitePersistenceMemory; const serverSettingsLayer = ServerSettingsService.layerTest({ - enableAssistantStreaming: options.enableAssistantStreaming ?? false, + enableLegacyTokenStreaming: options.enableLegacyTokenStreaming ?? false, }).pipe(Layer.orDie); const storesLayer = Layer.mergeAll( eventStoreLayer, diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts deleted file mode 100644 index e3b18d74a9..0000000000 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ /dev/null @@ -1,2792 +0,0 @@ -import { - CheckpointRef, - CommandId, - CorrelationId, - EventId, - MessageId, - ProjectId, - ThreadId, - TurnId, - ProviderInstanceId, -} from "@t3tools/contracts"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; -import * as Path from "effect/Path"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; - -import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; -import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; -import { - makeSqlitePersistenceLive, - SqlitePersistenceMemory, -} from "../../persistence/Layers/Sqlite.ts"; -import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts"; -import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts"; -import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; -import { - ORCHESTRATION_PROJECTOR_NAMES, - OrchestrationProjectionPipelineLive, -} from "./ProjectionPipeline.ts"; -import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; -import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts"; -import * as ThreadPlanProgress from "../ThreadPlanProgress.ts"; -import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; -import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts"; -import { ServerConfig } from "../../config.ts"; - -const makeProjectionPipelinePrefixedTestLayer = (prefix: string) => - OrchestrationProjectionPipelineLive.pipe( - Layer.provideMerge(OrchestrationEventStoreLive), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix })), - Layer.provideMerge(SqlitePersistenceMemory), - Layer.provideMerge(NodeServices.layer), - ); - -const exists = (filePath: string) => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const fileInfo = yield* Effect.result(fileSystem.stat(filePath)); - return fileInfo._tag === "Success"; - }); - -const BaseTestLayer = makeProjectionPipelinePrefixedTestLayer("t3-projection-pipeline-test-"); - -it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { - it.effect("bootstraps all projection states and writes projection rows", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-01T00:00:00.000Z"; - - yield* eventStore.append({ - type: "project.created", - eventId: EventId.make("evt-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-1"), - occurredAt: now, - commandId: CommandId.make("cmd-1"), - causationEventId: null, - correlationId: CommandId.make("cmd-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-1"), - title: "Project 1", - workspaceRoot: "/tmp/project-1", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.created", - eventId: EventId.make("evt-2"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - occurredAt: now, - commandId: CommandId.make("cmd-2"), - causationEventId: null, - correlationId: CommandId.make("cmd-2"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-1"), - title: "Thread 1", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-3"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - occurredAt: now, - commandId: CommandId.make("cmd-3"), - causationEventId: null, - correlationId: CommandId.make("cmd-3"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-1"), - messageId: MessageId.make("message-1"), - role: "assistant", - text: "hello", - turnId: null, - streaming: false, - createdAt: now, - updatedAt: now, - }, - }); - - yield* projectionPipeline.bootstrap; - - const projectRows = yield* sql<{ - readonly projectId: string; - readonly title: string; - readonly scriptsJson: string; - }>` - SELECT - project_id AS "projectId", - title, - scripts_json AS "scriptsJson" - FROM projection_projects - `; - assert.deepEqual(projectRows, [ - { projectId: "project-1", title: "Project 1", scriptsJson: "[]" }, - ]); - - const messageRows = yield* sql<{ - readonly messageId: string; - readonly text: string; - }>` - SELECT - message_id AS "messageId", - text - FROM projection_thread_messages - `; - assert.deepEqual(messageRows, [{ messageId: "message-1", text: "hello" }]); - - const stateRows = yield* sql<{ - readonly projector: string; - readonly lastAppliedSequence: number; - }>` - SELECT - projector, - last_applied_sequence AS "lastAppliedSequence" - FROM projection_state - ORDER BY projector ASC - `; - assert.equal(stateRows.length, Object.keys(ORCHESTRATION_PROJECTOR_NAMES).length); - for (const row of stateRows) { - assert.equal(row.lastAppliedSequence, 3); - } - - // Settled lifecycle through the DB pipeline: thread.settled writes the - // override + timestamp, thread.unsettled(user) flips to the active pin. - yield* eventStore.append({ - type: "thread.settled", - eventId: EventId.make("evt-settle-1"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - occurredAt: "2026-01-01T00:00:01.000Z", - commandId: CommandId.make("cmd-settle-1"), - causationEventId: null, - correlationId: CommandId.make("cmd-settle-1"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-1"), - settledAt: "2026-01-01T00:00:01.000Z", - updatedAt: "2026-01-01T00:00:01.000Z", - }, - }); - yield* projectionPipeline.bootstrap; - - const settledRows = yield* sql<{ - readonly settledOverride: string | null; - readonly settledAt: string | null; - }>` - SELECT - settled_override AS "settledOverride", - settled_at AS "settledAt" - FROM projection_threads - WHERE thread_id = 'thread-1' - `; - assert.deepEqual(settledRows, [ - { settledOverride: "settled", settledAt: "2026-01-01T00:00:01.000Z" }, - ]); - - yield* eventStore.append({ - type: "thread.unsettled", - eventId: EventId.make("evt-unsettle-1"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - occurredAt: "2026-01-01T00:00:02.000Z", - commandId: CommandId.make("cmd-unsettle-1"), - causationEventId: null, - correlationId: CommandId.make("cmd-unsettle-1"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-1"), - reason: "user", - updatedAt: "2026-01-01T00:00:02.000Z", - }, - }); - yield* projectionPipeline.bootstrap; - - const unsettledRows = yield* sql<{ - readonly settledOverride: string | null; - readonly settledAt: string | null; - }>` - SELECT - settled_override AS "settledOverride", - settled_at AS "settledAt" - FROM projection_threads - WHERE thread_id = 'thread-1' - `; - assert.deepEqual(unsettledRows, [{ settledOverride: "active", settledAt: null }]); - }), - ); -}); - -it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-base-")))( - "OrchestrationProjectionPipeline", - (it) => { - it.effect("stores message attachment references without mutating payloads", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-01T00:00:00.000Z"; - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-attachments"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-attachments"), - occurredAt: now, - commandId: CommandId.make("cmd-attachments"), - causationEventId: null, - correlationId: CommandId.make("cmd-attachments"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-attachments"), - messageId: MessageId.make("message-attachments"), - role: "user", - text: "Inspect this", - attachments: [ - { - type: "image", - id: "thread-attachments-att-1", - name: "example.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - turnId: null, - streaming: false, - createdAt: now, - updatedAt: now, - }, - }); - - yield* projectionPipeline.bootstrap; - - const rows = yield* sql<{ - readonly attachmentsJson: string | null; - }>` - SELECT - attachments_json AS "attachmentsJson" - FROM projection_thread_messages - WHERE message_id = 'message-attachments' - `; - assert.equal(rows.length, 1); - // @effect-diagnostics-next-line preferSchemaOverJson:off - assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [ - { - type: "image", - id: "thread-attachments-att-1", - name: "example.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ]); - }), - ); - }, -); - -it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-safe-")))( - "OrchestrationProjectionPipeline", - (it) => { - it.effect("preserves mixed image attachment metadata as-is", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-01T00:00:00.000Z"; - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-attachments-safe"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-attachments-safe"), - occurredAt: now, - commandId: CommandId.make("cmd-attachments-safe"), - causationEventId: null, - correlationId: CommandId.make("cmd-attachments-safe"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-attachments-safe"), - messageId: MessageId.make("message-attachments-safe"), - role: "user", - text: "Inspect this", - attachments: [ - { - type: "image", - id: "thread-attachments-safe-att-1", - name: "untrusted.exe", - mimeType: "image/x-unknown", - sizeBytes: 5, - }, - { - type: "image", - id: "thread-attachments-safe-att-2", - name: "not-image.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - turnId: null, - streaming: false, - createdAt: now, - updatedAt: now, - }, - }); - - yield* projectionPipeline.bootstrap; - - const rows = yield* sql<{ - readonly attachmentsJson: string | null; - }>` - SELECT - attachments_json AS "attachmentsJson" - FROM projection_thread_messages - WHERE message_id = 'message-attachments-safe' - `; - assert.equal(rows.length, 1); - // @effect-diagnostics-next-line preferSchemaOverJson:off - assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [ - { - type: "image", - id: "thread-attachments-safe-att-1", - name: "untrusted.exe", - mimeType: "image/x-unknown", - sizeBytes: 5, - }, - { - type: "image", - id: "thread-attachments-safe-att-2", - name: "not-image.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ]); - }), - ); - }, -); - -it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { - it.effect( - "passes explicit empty attachment arrays through the projection pipeline to clear attachments", - () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-01T00:00:00.000Z"; - const later = "2026-01-01T00:00:01.000Z"; - - yield* eventStore.append({ - type: "project.created", - eventId: EventId.make("evt-clear-attachments-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-clear-attachments"), - occurredAt: now, - commandId: CommandId.make("cmd-clear-attachments-1"), - causationEventId: null, - correlationId: CommandId.make("cmd-clear-attachments-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-clear-attachments"), - title: "Project Clear Attachments", - workspaceRoot: "/tmp/project-clear-attachments", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.created", - eventId: EventId.make("evt-clear-attachments-2"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-clear-attachments"), - occurredAt: now, - commandId: CommandId.make("cmd-clear-attachments-2"), - causationEventId: null, - correlationId: CommandId.make("cmd-clear-attachments-2"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-clear-attachments"), - projectId: ProjectId.make("project-clear-attachments"), - title: "Thread Clear Attachments", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-clear-attachments-3"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-clear-attachments"), - occurredAt: now, - commandId: CommandId.make("cmd-clear-attachments-3"), - causationEventId: null, - correlationId: CommandId.make("cmd-clear-attachments-3"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-clear-attachments"), - messageId: MessageId.make("message-clear-attachments"), - role: "user", - text: "Has attachments", - attachments: [ - { - type: "image", - id: "thread-clear-attachments-att-1", - name: "clear.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - turnId: null, - streaming: false, - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-clear-attachments-4"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-clear-attachments"), - occurredAt: later, - commandId: CommandId.make("cmd-clear-attachments-4"), - causationEventId: null, - correlationId: CommandId.make("cmd-clear-attachments-4"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-clear-attachments"), - messageId: MessageId.make("message-clear-attachments"), - role: "user", - text: "", - attachments: [], - turnId: null, - streaming: false, - createdAt: now, - updatedAt: later, - }, - }); - - yield* projectionPipeline.bootstrap; - - const rows = yield* sql<{ - readonly attachmentsJson: string | null; - }>` - SELECT - attachments_json AS "attachmentsJson" - FROM projection_thread_messages - WHERE message_id = 'message-clear-attachments' - `; - assert.equal(rows.length, 1); - // @effect-diagnostics-next-line preferSchemaOverJson:off - assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), []); - }), - ); -}); - -it.layer( - Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-overwrite-")), -)("OrchestrationProjectionPipeline", (it) => { - it.effect("overwrites stored attachment references when a message updates attachments", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-01T00:00:00.000Z"; - const later = "2026-01-01T00:00:01.000Z"; - - yield* eventStore.append({ - type: "project.created", - eventId: EventId.make("evt-overwrite-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-overwrite"), - occurredAt: now, - commandId: CommandId.make("cmd-overwrite-1"), - causationEventId: null, - correlationId: CommandId.make("cmd-overwrite-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-overwrite"), - title: "Project Overwrite", - workspaceRoot: "/tmp/project-overwrite", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.created", - eventId: EventId.make("evt-overwrite-2"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-overwrite"), - occurredAt: now, - commandId: CommandId.make("cmd-overwrite-2"), - causationEventId: null, - correlationId: CommandId.make("cmd-overwrite-2"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-overwrite"), - projectId: ProjectId.make("project-overwrite"), - title: "Thread Overwrite", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-overwrite-3"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-overwrite"), - occurredAt: now, - commandId: CommandId.make("cmd-overwrite-3"), - causationEventId: null, - correlationId: CommandId.make("cmd-overwrite-3"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-overwrite"), - messageId: MessageId.make("message-overwrite"), - role: "user", - text: "first image", - attachments: [ - { - type: "image", - id: "thread-overwrite-att-1", - name: "file.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - turnId: null, - streaming: false, - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-overwrite-4"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-overwrite"), - occurredAt: later, - commandId: CommandId.make("cmd-overwrite-4"), - causationEventId: null, - correlationId: CommandId.make("cmd-overwrite-4"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-overwrite"), - messageId: MessageId.make("message-overwrite"), - role: "user", - text: "", - attachments: [ - { - type: "image", - id: "thread-overwrite-att-2", - name: "file.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - turnId: null, - streaming: false, - createdAt: now, - updatedAt: later, - }, - }); - - yield* projectionPipeline.bootstrap; - - const rows = yield* sql<{ - readonly attachmentsJson: string | null; - }>` - SELECT attachments_json AS "attachmentsJson" - FROM projection_thread_messages - WHERE message_id = 'message-overwrite' - `; - assert.equal(rows.length, 1); - // @effect-diagnostics-next-line preferSchemaOverJson:off - assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [ - { - type: "image", - id: "thread-overwrite-att-2", - name: "file.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ]); - }), - ); -}); - -it.layer( - Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-rollback-")), -)("OrchestrationProjectionPipeline", (it) => { - it.effect("does not persist attachment files when projector transaction rolls back", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const path = yield* Path.Path; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-01T00:00:00.000Z"; - - const appendAndProject = (event: Parameters[0]) => - eventStore - .append(event) - .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); - - yield* appendAndProject({ - type: "project.created", - eventId: EventId.make("evt-rollback-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-rollback"), - occurredAt: now, - commandId: CommandId.make("cmd-rollback-1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-rollback-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-rollback"), - title: "Project Rollback", - workspaceRoot: "/tmp/project-rollback", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - yield* appendAndProject({ - type: "thread.created", - eventId: EventId.make("evt-rollback-2"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-rollback"), - occurredAt: now, - commandId: CommandId.make("cmd-rollback-2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-rollback-2"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-rollback"), - projectId: ProjectId.make("project-rollback"), - title: "Thread Rollback", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - yield* sql` - CREATE TRIGGER fail_thread_messages_projection_state_update - BEFORE UPDATE ON projection_state - WHEN NEW.projector = 'projection.thread-messages' - BEGIN - SELECT RAISE(ABORT, 'forced-projection-state-failure'); - END; - `; - - const result = yield* Effect.result( - appendAndProject({ - type: "thread.message-sent", - eventId: EventId.make("evt-rollback-3"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-rollback"), - occurredAt: now, - commandId: CommandId.make("cmd-rollback-3"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-rollback-3"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-rollback"), - messageId: MessageId.make("message-rollback"), - role: "user", - text: "Rollback me", - attachments: [ - { - type: "image", - id: "thread-rollback-att-1", - name: "rollback.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - turnId: null, - streaming: false, - createdAt: now, - updatedAt: now, - }, - }), - ); - assert.equal(result._tag, "Failure"); - - const rows = yield* sql<{ - readonly count: number; - }>` - SELECT COUNT(*) AS "count" - FROM projection_thread_messages - WHERE message_id = 'message-rollback' - `; - assert.equal(rows[0]?.count ?? 0, 0); - - const { attachmentsDir } = yield* ServerConfig; - const attachmentPath = path.join(attachmentsDir, "thread-rollback-att-1.png"); - assert.isFalse(yield* exists(attachmentPath)); - yield* sql`DROP TRIGGER IF EXISTS fail_thread_messages_projection_state_update`; - }), - ); -}); - -it.layer( - Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-overwrite-")), -)("OrchestrationProjectionPipeline", (it) => { - it.effect("removes unreferenced attachment files when a thread is reverted", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const { attachmentsDir } = yield* ServerConfig; - const now = "2026-01-01T00:00:00.000Z"; - const threadId = ThreadId.make("Thread Revert.Files"); - const keepAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000001"; - const removeAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000002"; - const otherThreadAttachmentId = - "thread-revert-files-extra-00000000-0000-4000-8000-000000000003"; - - const appendAndProject = (event: Parameters[0]) => - eventStore - .append(event) - .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); - - yield* appendAndProject({ - type: "project.created", - eventId: EventId.make("evt-revert-files-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-revert-files"), - occurredAt: now, - commandId: CommandId.make("cmd-revert-files-1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-files-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-revert-files"), - title: "Project Revert Files", - workspaceRoot: "/tmp/project-revert-files", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - yield* appendAndProject({ - type: "thread.created", - eventId: EventId.make("evt-revert-files-2"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: CommandId.make("cmd-revert-files-2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-files-2"), - metadata: {}, - payload: { - threadId, - projectId: ProjectId.make("project-revert-files"), - title: "Thread Revert Files", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - yield* appendAndProject({ - type: "thread.turn-diff-completed", - eventId: EventId.make("evt-revert-files-3"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: CommandId.make("cmd-revert-files-3"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-files-3"), - metadata: {}, - payload: { - threadId, - turnId: TurnId.make("turn-keep"), - checkpointTurnCount: 1, - checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-files/turn/1"), - status: "ready", - files: [], - assistantMessageId: MessageId.make("message-keep"), - completedAt: now, - }, - }); - - yield* appendAndProject({ - type: "thread.message-sent", - eventId: EventId.make("evt-revert-files-4"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: CommandId.make("cmd-revert-files-4"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-files-4"), - metadata: {}, - payload: { - threadId, - messageId: MessageId.make("message-keep"), - role: "assistant", - text: "Keep", - attachments: [ - { - type: "image", - id: keepAttachmentId, - name: "keep.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - turnId: TurnId.make("turn-keep"), - streaming: false, - createdAt: now, - updatedAt: now, - }, - }); - - yield* appendAndProject({ - type: "thread.turn-diff-completed", - eventId: EventId.make("evt-revert-files-5"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: CommandId.make("cmd-revert-files-5"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-files-5"), - metadata: {}, - payload: { - threadId, - turnId: TurnId.make("turn-remove"), - checkpointTurnCount: 2, - checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert-files/turn/2"), - status: "ready", - files: [], - assistantMessageId: MessageId.make("message-remove"), - completedAt: now, - }, - }); - - yield* appendAndProject({ - type: "thread.message-sent", - eventId: EventId.make("evt-revert-files-6"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: CommandId.make("cmd-revert-files-6"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-files-6"), - metadata: {}, - payload: { - threadId, - messageId: MessageId.make("message-remove"), - role: "assistant", - text: "Remove", - attachments: [ - { - type: "image", - id: removeAttachmentId, - name: "remove.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - turnId: TurnId.make("turn-remove"), - streaming: false, - createdAt: now, - updatedAt: now, - }, - }); - - const keepPath = path.join(attachmentsDir, `${keepAttachmentId}.png`); - const removePath = path.join(attachmentsDir, `${removeAttachmentId}.png`); - yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true }); - yield* fileSystem.writeFileString(keepPath, "keep"); - yield* fileSystem.writeFileString(removePath, "remove"); - const otherThreadPath = path.join(attachmentsDir, `${otherThreadAttachmentId}.png`); - yield* fileSystem.writeFileString(otherThreadPath, "other"); - assert.isTrue(yield* exists(keepPath)); - assert.isTrue(yield* exists(removePath)); - assert.isTrue(yield* exists(otherThreadPath)); - - yield* appendAndProject({ - type: "thread.reverted", - eventId: EventId.make("evt-revert-files-7"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: CommandId.make("cmd-revert-files-7"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-files-7"), - metadata: {}, - payload: { - threadId, - turnCount: 1, - }, - }); - - assert.isTrue(yield* exists(keepPath)); - assert.isFalse(yield* exists(removePath)); - assert.isTrue(yield* exists(otherThreadPath)); - }), - ); -}); - -it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-revert-")))( - "OrchestrationProjectionPipeline", - (it) => { - it.effect("removes thread attachment directory when thread is deleted", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const { attachmentsDir } = yield* ServerConfig; - const now = "2026-01-01T00:00:00.000Z"; - const threadId = ThreadId.make("Thread Delete.Files"); - const attachmentId = "thread-delete-files-00000000-0000-4000-8000-000000000001"; - const otherThreadAttachmentId = - "thread-delete-files-extra-00000000-0000-4000-8000-000000000002"; - - const appendAndProject = (event: Parameters[0]) => - eventStore - .append(event) - .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); - - yield* appendAndProject({ - type: "project.created", - eventId: EventId.make("evt-delete-files-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-delete-files"), - occurredAt: now, - commandId: CommandId.make("cmd-delete-files-1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-delete-files-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-delete-files"), - title: "Project Delete Files", - workspaceRoot: "/tmp/project-delete-files", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - yield* appendAndProject({ - type: "thread.created", - eventId: EventId.make("evt-delete-files-2"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: CommandId.make("cmd-delete-files-2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-delete-files-2"), - metadata: {}, - payload: { - threadId, - projectId: ProjectId.make("project-delete-files"), - title: "Thread Delete Files", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - yield* appendAndProject({ - type: "thread.message-sent", - eventId: EventId.make("evt-delete-files-3"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: CommandId.make("cmd-delete-files-3"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-delete-files-3"), - metadata: {}, - payload: { - threadId, - messageId: MessageId.make("message-delete-files"), - role: "user", - text: "Delete", - attachments: [ - { - type: "image", - id: attachmentId, - name: "delete.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - turnId: null, - streaming: false, - createdAt: now, - updatedAt: now, - }, - }); - - const threadAttachmentPath = path.join(attachmentsDir, `${attachmentId}.png`); - const otherThreadAttachmentPath = path.join( - attachmentsDir, - `${otherThreadAttachmentId}.png`, - ); - yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true }); - yield* fileSystem.writeFileString(threadAttachmentPath, "delete"); - yield* fileSystem.writeFileString(otherThreadAttachmentPath, "other-thread"); - assert.isTrue(yield* exists(threadAttachmentPath)); - assert.isTrue(yield* exists(otherThreadAttachmentPath)); - - yield* appendAndProject({ - type: "thread.deleted", - eventId: EventId.make("evt-delete-files-4"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: CommandId.make("cmd-delete-files-4"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-delete-files-4"), - metadata: {}, - payload: { - threadId, - deletedAt: now, - }, - }); - - assert.isFalse(yield* exists(threadAttachmentPath)); - assert.isTrue(yield* exists(otherThreadAttachmentPath)); - }), - ); - }, -); - -it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-attachments-delete-")))( - "OrchestrationProjectionPipeline", - (it) => { - it.effect("ignores unsafe thread ids for attachment cleanup paths", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const now = "2026-01-01T00:00:00.000Z"; - const { attachmentsDir: attachmentsRootDir, stateDir } = yield* ServerConfig; - const attachmentsSentinelPath = path.join(attachmentsRootDir, "sentinel.txt"); - const stateDirSentinelPath = path.join(stateDir, "state-sentinel.txt"); - yield* fileSystem.makeDirectory(attachmentsRootDir, { recursive: true }); - yield* fileSystem.writeFileString(attachmentsSentinelPath, "keep-attachments-root"); - yield* fileSystem.writeFileString(stateDirSentinelPath, "keep-state-dir"); - - yield* eventStore.append({ - type: "thread.deleted", - eventId: EventId.make("evt-unsafe-thread-delete"), - aggregateKind: "thread", - aggregateId: ThreadId.make(".."), - occurredAt: now, - commandId: CommandId.make("cmd-unsafe-thread-delete"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-unsafe-thread-delete"), - metadata: {}, - payload: { - threadId: ThreadId.make(".."), - deletedAt: now, - }, - }); - - yield* projectionPipeline.bootstrap; - - assert.isTrue(yield* exists(attachmentsRootDir)); - assert.isTrue(yield* exists(attachmentsSentinelPath)); - assert.isTrue(yield* exists(stateDirSentinelPath)); - }), - ); - }, -); - -it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { - it.effect("resumes from projector last_applied_sequence without replaying older events", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-01T00:00:00.000Z"; - - yield* eventStore.append({ - type: "project.created", - eventId: EventId.make("evt-a1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-a"), - occurredAt: now, - commandId: CommandId.make("cmd-a1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-a1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-a"), - title: "Project A", - workspaceRoot: "/tmp/project-a", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.created", - eventId: EventId.make("evt-a2"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-a"), - occurredAt: now, - commandId: CommandId.make("cmd-a2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-a2"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-a"), - projectId: ProjectId.make("project-a"), - title: "Thread A", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-a3"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-a"), - occurredAt: now, - commandId: CommandId.make("cmd-a3"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-a3"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-a"), - messageId: MessageId.make("message-a"), - role: "assistant", - text: "hello", - turnId: null, - streaming: false, - createdAt: now, - updatedAt: now, - }, - }); - - yield* projectionPipeline.bootstrap; - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-a4"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-a"), - occurredAt: now, - commandId: CommandId.make("cmd-a4"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-a4"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-a"), - messageId: MessageId.make("message-a"), - role: "assistant", - text: " world", - turnId: null, - streaming: true, - createdAt: now, - updatedAt: now, - }, - }); - - yield* projectionPipeline.bootstrap; - yield* projectionPipeline.bootstrap; - - const messageRows = yield* sql<{ readonly text: string }>` - SELECT text FROM projection_thread_messages WHERE message_id = 'message-a' - `; - assert.deepEqual(messageRows, [{ text: "hello world" }]); - - const stateRows = yield* sql<{ - readonly projector: string; - readonly lastAppliedSequence: number; - }>` - SELECT - projector, - last_applied_sequence AS "lastAppliedSequence" - FROM projection_state - `; - const maxSequenceRows = yield* sql<{ readonly maxSequence: number }>` - SELECT MAX(sequence) AS "maxSequence" FROM orchestration_events - `; - const maxSequence = maxSequenceRows[0]?.maxSequence ?? 0; - for (const row of stateRows) { - assert.equal(row.lastAppliedSequence, maxSequence); - } - }), - ); - - it.effect("keeps the turn running across interim assistant messages until the session ends", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-01T00:00:00.000Z"; - const threadId = ThreadId.make("thread-turn-lifecycle"); - const turnId = TurnId.make("turn-lifecycle-1"); - - yield* eventStore.append({ - type: "thread.created", - eventId: EventId.make("evt-tl1"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: CommandId.make("cmd-tl1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-tl1"), - metadata: {}, - payload: { - threadId, - projectId: ProjectId.make("project-turn-lifecycle"), - title: "Turn lifecycle", - modelSelection: { - instanceId: ProviderInstanceId.make("claude"), - model: "claude-opus", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.session-set", - eventId: EventId.make("evt-tl2"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: "2026-01-01T00:00:01.000Z", - commandId: CommandId.make("cmd-tl2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-tl2"), - metadata: {}, - payload: { - threadId, - session: { - threadId, - status: "running", - providerName: "claude", - runtimeMode: "full-access", - activeTurnId: turnId, - lastError: null, - updatedAt: "2026-01-01T00:00:01.000Z", - }, - }, - }); - - // Interim assistant message completes mid-turn (commentary between - // tool calls) — the turn must stay running and unsettled. - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-tl3"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: "2026-01-01T00:00:05.000Z", - commandId: CommandId.make("cmd-tl3"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-tl3"), - metadata: {}, - payload: { - threadId, - messageId: MessageId.make("message-tl-interim"), - role: "assistant", - text: "interim commentary", - turnId, - streaming: false, - createdAt: "2026-01-01T00:00:05.000Z", - updatedAt: "2026-01-01T00:00:05.000Z", - }, - }); - - yield* projectionPipeline.bootstrap; - - const runningRows = yield* sql<{ - readonly state: string; - readonly completedAt: string | null; - }>` - SELECT state, completed_at AS "completedAt" - FROM projection_turns - WHERE thread_id = ${threadId} AND turn_id = ${turnId} - `; - assert.deepEqual(runningRows, [{ state: "running", completedAt: null }]); - - // The session leaving "running" is the turn-end signal. - yield* eventStore.append({ - type: "thread.session-set", - eventId: EventId.make("evt-tl4"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: "2026-01-01T00:01:00.000Z", - commandId: CommandId.make("cmd-tl4"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-tl4"), - metadata: {}, - payload: { - threadId, - session: { - threadId, - status: "ready", - providerName: "claude", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: "2026-01-01T00:01:00.000Z", - }, - }, - }); - - yield* projectionPipeline.bootstrap; - - const settledRows = yield* sql<{ - readonly state: string; - readonly completedAt: string | null; - }>` - SELECT state, completed_at AS "completedAt" - FROM projection_turns - WHERE thread_id = ${threadId} AND turn_id = ${turnId} - `; - assert.deepEqual(settledRows, [ - { state: "completed", completedAt: "2026-01-01T00:01:00.000Z" }, - ]); - - const threadRows = yield* sql<{ readonly latestTurnId: string | null }>` - SELECT latest_turn_id AS "latestTurnId" - FROM projection_threads - WHERE thread_id = ${threadId} - `; - assert.deepEqual(threadRows, [{ latestTurnId: turnId }]); - }), - ); - - it.effect("settles a superseded running turn when a new turn becomes active", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-01T00:00:00.000Z"; - const threadId = ThreadId.make("thread-turn-supersede"); - const oldTurnId = TurnId.make("turn-superseded"); - const newTurnId = TurnId.make("turn-steer"); - - yield* eventStore.append({ - type: "thread.created", - eventId: EventId.make("evt-ts1"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: CommandId.make("cmd-ts1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-ts1"), - metadata: {}, - payload: { - threadId, - projectId: ProjectId.make("project-turn-supersede"), - title: "Turn supersede", - modelSelection: { - instanceId: ProviderInstanceId.make("opencode"), - model: "big-pickle", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - const appendRunningSessionSet = (eventId: string, turnId: TurnId, updatedAt: string) => - eventStore.append({ - type: "thread.session-set", - eventId: EventId.make(eventId), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: updatedAt, - commandId: CommandId.make(`cmd-${eventId}`), - causationEventId: null, - correlationId: CorrelationId.make(`cmd-${eventId}`), - metadata: {}, - payload: { - threadId, - session: { - threadId, - status: "running", - providerName: "opencode", - runtimeMode: "full-access", - activeTurnId: turnId, - lastError: null, - updatedAt, - }, - }, - }); - - yield* appendRunningSessionSet("evt-ts2", oldTurnId, "2026-01-01T00:00:01.000Z"); - // A steer: a new turn becomes active without the provider ever - // completing the previous one. - yield* appendRunningSessionSet("evt-ts3", newTurnId, "2026-01-01T00:00:30.000Z"); - - yield* projectionPipeline.bootstrap; - - const rows = yield* sql<{ - readonly turnId: string; - readonly state: string; - readonly completedAt: string | null; - }>` - SELECT turn_id AS "turnId", state, completed_at AS "completedAt" - FROM projection_turns - WHERE thread_id = ${threadId} - ORDER BY requested_at - `; - assert.deepEqual(rows, [ - { turnId: oldTurnId, state: "completed", completedAt: "2026-01-01T00:00:30.000Z" }, - { turnId: newTurnId, state: "running", completedAt: null }, - ]); - }), - ); - - it.effect("keeps accumulated assistant text when completion payload text is empty", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const now = "2026-01-01T00:00:00.000Z"; - - yield* eventStore.append({ - type: "project.created", - eventId: EventId.make("evt-empty-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-empty"), - occurredAt: now, - commandId: CommandId.make("cmd-empty-1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-empty-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-empty"), - title: "Project Empty", - workspaceRoot: "/tmp/project-empty", - defaultModelSelection: null, - scripts: [], - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.created", - eventId: EventId.make("evt-empty-2"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-empty"), - occurredAt: now, - commandId: CommandId.make("cmd-empty-2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-empty-2"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-empty"), - projectId: ProjectId.make("project-empty"), - title: "Thread Empty", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-empty-3"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-empty"), - occurredAt: now, - commandId: CommandId.make("cmd-empty-3"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-empty-3"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-empty"), - messageId: MessageId.make("assistant-empty"), - role: "assistant", - text: "Hello", - turnId: null, - streaming: true, - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-empty-4"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-empty"), - occurredAt: now, - commandId: CommandId.make("cmd-empty-4"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-empty-4"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-empty"), - messageId: MessageId.make("assistant-empty"), - role: "assistant", - text: " world", - turnId: null, - streaming: true, - createdAt: now, - updatedAt: now, - }, - }); - - yield* eventStore.append({ - type: "thread.message-sent", - eventId: EventId.make("evt-empty-5"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-empty"), - occurredAt: now, - commandId: CommandId.make("cmd-empty-5"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-empty-5"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-empty"), - messageId: MessageId.make("assistant-empty"), - role: "assistant", - text: "", - turnId: null, - streaming: false, - createdAt: now, - updatedAt: now, - }, - }); - - yield* projectionPipeline.bootstrap; - - const messageRows = yield* sql<{ readonly text: string; readonly isStreaming: unknown }>` - SELECT - text, - is_streaming AS "isStreaming" - FROM projection_thread_messages - WHERE message_id = 'assistant-empty' - `; - assert.equal(messageRows.length, 1); - assert.equal(messageRows[0]?.text, "Hello world"); - assert.isFalse(Boolean(messageRows[0]?.isStreaming)); - }), - ); - - it.effect( - "resolves turn-count conflicts when checkpoint completion rewrites provisional turns", - () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const appendAndProject = (event: Parameters[0]) => - eventStore - .append(event) - .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); - - yield* appendAndProject({ - type: "project.created", - eventId: EventId.make("evt-conflict-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-conflict"), - occurredAt: "2026-02-26T13:00:00.000Z", - commandId: CommandId.make("cmd-conflict-1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-conflict-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-conflict"), - title: "Project Conflict", - workspaceRoot: "/tmp/project-conflict", - defaultModelSelection: null, - scripts: [], - createdAt: "2026-02-26T13:00:00.000Z", - updatedAt: "2026-02-26T13:00:00.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.created", - eventId: EventId.make("evt-conflict-2"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-conflict"), - occurredAt: "2026-02-26T13:00:01.000Z", - commandId: CommandId.make("cmd-conflict-2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-conflict-2"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-conflict"), - projectId: ProjectId.make("project-conflict"), - title: "Thread Conflict", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: "2026-02-26T13:00:01.000Z", - updatedAt: "2026-02-26T13:00:01.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.turn-interrupt-requested", - eventId: EventId.make("evt-conflict-3"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-conflict"), - occurredAt: "2026-02-26T13:00:02.000Z", - commandId: CommandId.make("cmd-conflict-3"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-conflict-3"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-conflict"), - turnId: TurnId.make("turn-interrupted"), - createdAt: "2026-02-26T13:00:02.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.message-sent", - eventId: EventId.make("evt-conflict-4"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-conflict"), - occurredAt: "2026-02-26T13:00:03.000Z", - commandId: CommandId.make("cmd-conflict-4"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-conflict-4"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-conflict"), - messageId: MessageId.make("assistant-conflict"), - role: "assistant", - text: "done", - turnId: TurnId.make("turn-completed"), - streaming: false, - createdAt: "2026-02-26T13:00:03.000Z", - updatedAt: "2026-02-26T13:00:03.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.turn-diff-completed", - eventId: EventId.make("evt-conflict-5"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-conflict"), - occurredAt: "2026-02-26T13:00:04.000Z", - commandId: CommandId.make("cmd-conflict-5"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-conflict-5"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-conflict"), - turnId: TurnId.make("turn-completed"), - checkpointTurnCount: 1, - checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-conflict/turn/1"), - status: "ready", - files: [], - assistantMessageId: MessageId.make("assistant-conflict"), - completedAt: "2026-02-26T13:00:04.000Z", - }, - }); - - const turnRows = yield* sql<{ - readonly turnId: string; - readonly checkpointTurnCount: number | null; - readonly status: string; - }>` - SELECT - turn_id AS "turnId", - checkpoint_turn_count AS "checkpointTurnCount", - state AS "status" - FROM projection_turns - WHERE thread_id = 'thread-conflict' - ORDER BY - CASE - WHEN checkpoint_turn_count IS NULL THEN 1 - ELSE 0 - END ASC, - checkpoint_turn_count ASC, - requested_at ASC - `; - assert.deepEqual(turnRows, [ - { turnId: "turn-completed", checkpointTurnCount: 1, status: "completed" }, - { turnId: "turn-interrupted", checkpointTurnCount: null, status: "interrupted" }, - ]); - }), - ); - - it.effect("clears stale pending approvals from projected shell summaries", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const appendAndProject = (event: Parameters[0]) => - eventStore - .append(event) - .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); - - yield* appendAndProject({ - type: "project.created", - eventId: EventId.make("evt-stale-approval-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-stale-approval"), - occurredAt: "2026-02-26T12:30:00.000Z", - commandId: CommandId.make("cmd-stale-approval-1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-stale-approval-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-stale-approval"), - title: "Project Stale Approval", - workspaceRoot: "/tmp/project-stale-approval", - defaultModelSelection: null, - scripts: [], - createdAt: "2026-02-26T12:30:00.000Z", - updatedAt: "2026-02-26T12:30:00.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.created", - eventId: EventId.make("evt-stale-approval-2"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-stale-approval"), - occurredAt: "2026-02-26T12:30:01.000Z", - commandId: CommandId.make("cmd-stale-approval-2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-stale-approval-2"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-stale-approval"), - projectId: ProjectId.make("project-stale-approval"), - title: "Thread Stale Approval", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "approval-required", - interactionMode: "default", - branch: null, - worktreePath: null, - createdAt: "2026-02-26T12:30:01.000Z", - updatedAt: "2026-02-26T12:30:01.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.activity-appended", - eventId: EventId.make("evt-stale-approval-3"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-stale-approval"), - occurredAt: "2026-02-26T12:30:02.000Z", - commandId: CommandId.make("cmd-stale-approval-3"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-stale-approval-3"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-stale-approval"), - activity: { - id: EventId.make("activity-stale-approval-requested"), - tone: "approval", - kind: "approval.requested", - summary: "Command approval requested", - payload: { - requestId: "approval-request-stale-1", - requestKind: "command", - }, - turnId: null, - createdAt: "2026-02-26T12:30:02.000Z", - }, - }, - }); - - yield* appendAndProject({ - type: "thread.activity-appended", - eventId: EventId.make("evt-stale-approval-4"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-stale-approval"), - occurredAt: "2026-02-26T12:30:03.000Z", - commandId: CommandId.make("cmd-stale-approval-4"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-stale-approval-4"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-stale-approval"), - activity: { - id: EventId.make("activity-stale-approval-failed"), - tone: "error", - kind: "provider.approval.respond.failed", - summary: "Provider approval response failed", - payload: { - requestId: "approval-request-stale-1", - detail: "Unknown pending permission request: approval-request-stale-1", - }, - turnId: null, - createdAt: "2026-02-26T12:30:03.000Z", - }, - }, - }); - - const approvalRows = yield* sql<{ - readonly requestId: string; - readonly status: string; - readonly resolvedAt: string | null; - }>` - SELECT - request_id AS "requestId", - status, - resolved_at AS "resolvedAt" - FROM projection_pending_approvals - WHERE request_id = 'approval-request-stale-1' - `; - assert.deepEqual(approvalRows, [ - { - requestId: "approval-request-stale-1", - status: "resolved", - resolvedAt: "2026-02-26T12:30:03.000Z", - }, - ]); - - const threadRows = yield* sql<{ - readonly pendingApprovalCount: number; - }>` - SELECT pending_approval_count AS "pendingApprovalCount" - FROM projection_threads - WHERE thread_id = 'thread-stale-approval' - `; - assert.deepEqual(threadRows, [{ pendingApprovalCount: 0 }]); - }), - ); - - it.effect("clears stale pending user input from projected shell summaries", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const appendAndProject = (event: Parameters[0]) => - eventStore - .append(event) - .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); - - yield* appendAndProject({ - type: "project.created", - eventId: EventId.make("evt-stale-user-input-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-stale-user-input"), - occurredAt: "2026-02-26T12:35:00.000Z", - commandId: CommandId.make("cmd-stale-user-input-1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-stale-user-input-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-stale-user-input"), - title: "Project Stale User Input", - workspaceRoot: "/tmp/project-stale-user-input", - defaultModelSelection: null, - scripts: [], - createdAt: "2026-02-26T12:35:00.000Z", - updatedAt: "2026-02-26T12:35:00.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.created", - eventId: EventId.make("evt-stale-user-input-2"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-stale-user-input"), - occurredAt: "2026-02-26T12:35:01.000Z", - commandId: CommandId.make("cmd-stale-user-input-2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-stale-user-input-2"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-stale-user-input"), - projectId: ProjectId.make("project-stale-user-input"), - title: "Thread Stale User Input", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "approval-required", - interactionMode: "default", - branch: null, - worktreePath: null, - createdAt: "2026-02-26T12:35:01.000Z", - updatedAt: "2026-02-26T12:35:01.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.activity-appended", - eventId: EventId.make("evt-stale-user-input-3"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-stale-user-input"), - occurredAt: "2026-02-26T12:35:02.000Z", - commandId: CommandId.make("cmd-stale-user-input-3"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-stale-user-input-3"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-stale-user-input"), - activity: { - id: EventId.make("activity-stale-user-input-requested"), - tone: "info", - kind: "user-input.requested", - summary: "User input requested", - payload: { - requestId: "user-input-request-stale-1", - questions: [ - { - id: "sandbox_mode", - header: "Sandbox", - question: "Which mode should be used?", - options: [ - { - label: "workspace-write", - description: "Allow workspace writes only", - }, - ], - }, - ], - }, - turnId: null, - createdAt: "2026-02-26T12:35:02.000Z", - }, - }, - }); - - yield* appendAndProject({ - type: "thread.activity-appended", - eventId: EventId.make("evt-stale-user-input-4"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-stale-user-input"), - occurredAt: "2026-02-26T12:35:03.000Z", - commandId: CommandId.make("cmd-stale-user-input-4"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-stale-user-input-4"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-stale-user-input"), - activity: { - id: EventId.make("activity-stale-user-input-failed"), - tone: "error", - kind: "provider.user-input.respond.failed", - summary: "Provider user input response failed", - payload: { - requestId: "user-input-request-stale-1", - detail: - "Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: user-input-request-stale-1", - }, - turnId: null, - createdAt: "2026-02-26T12:35:03.000Z", - }, - }, - }); - - const threadRows = yield* sql<{ - readonly pendingUserInputCount: number; - }>` - SELECT pending_user_input_count AS "pendingUserInputCount" - FROM projection_threads - WHERE thread_id = 'thread-stale-user-input' - `; - assert.deepEqual(threadRows, [{ pendingUserInputCount: 0 }]); - }), - ); - - it.effect("ignores non-stale provider approval response failures", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const appendAndProject = (event: Parameters[0]) => - eventStore - .append(event) - .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); - - yield* appendAndProject({ - type: "project.created", - eventId: EventId.make("evt-nonstale-approval-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-nonstale-approval"), - occurredAt: "2026-02-26T12:45:00.000Z", - commandId: CommandId.make("cmd-nonstale-approval-1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-nonstale-approval-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-nonstale-approval"), - title: "Project Non-Stale Approval", - workspaceRoot: "/tmp/project-nonstale-approval", - defaultModelSelection: null, - scripts: [], - createdAt: "2026-02-26T12:45:00.000Z", - updatedAt: "2026-02-26T12:45:00.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.created", - eventId: EventId.make("evt-nonstale-approval-2"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-nonstale-approval"), - occurredAt: "2026-02-26T12:45:01.000Z", - commandId: CommandId.make("cmd-nonstale-approval-2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-nonstale-approval-2"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-nonstale-approval"), - projectId: ProjectId.make("project-nonstale-approval"), - title: "Thread Non-Stale Approval", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "approval-required", - interactionMode: "default", - branch: null, - worktreePath: null, - createdAt: "2026-02-26T12:45:01.000Z", - updatedAt: "2026-02-26T12:45:01.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.activity-appended", - eventId: EventId.make("evt-nonstale-approval-3"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-nonstale-approval"), - occurredAt: "2026-02-26T12:45:02.000Z", - commandId: CommandId.make("cmd-nonstale-approval-3"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-nonstale-approval-3"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-nonstale-approval"), - activity: { - id: EventId.make("activity-nonstale-approval-requested"), - tone: "approval", - kind: "approval.requested", - summary: "Command approval requested", - payload: { - requestId: "approval-request-nonstale-existing", - requestKind: "command", - }, - turnId: null, - createdAt: "2026-02-26T12:45:02.000Z", - }, - }, - }); - - yield* appendAndProject({ - type: "thread.activity-appended", - eventId: EventId.make("evt-nonstale-approval-4"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-nonstale-approval"), - occurredAt: "2026-02-26T12:45:03.000Z", - commandId: CommandId.make("cmd-nonstale-approval-4"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-nonstale-approval-4"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-nonstale-approval"), - activity: { - id: EventId.make("activity-nonstale-approval-failed-existing"), - tone: "error", - kind: "provider.approval.respond.failed", - summary: "Provider approval response failed", - payload: { - requestId: "approval-request-nonstale-existing", - detail: "Provider timed out while responding to approval request", - }, - turnId: TurnId.make("turn-nonstale-failure"), - createdAt: "2026-02-26T12:45:03.000Z", - }, - }, - }); - - yield* appendAndProject({ - type: "thread.activity-appended", - eventId: EventId.make("evt-nonstale-approval-5"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-nonstale-approval"), - occurredAt: "2026-02-26T12:45:04.000Z", - commandId: CommandId.make("cmd-nonstale-approval-5"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-nonstale-approval-5"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-nonstale-approval"), - activity: { - id: EventId.make("activity-nonstale-approval-failed-missing"), - tone: "error", - kind: "provider.approval.respond.failed", - summary: "Provider approval response failed", - payload: { - requestId: "approval-request-nonstale-missing", - detail: "Provider timed out while responding to approval request", - }, - turnId: null, - createdAt: "2026-02-26T12:45:04.000Z", - }, - }, - }); - - const approvalRows = yield* sql<{ - readonly requestId: string; - readonly status: string; - readonly turnId: string | null; - readonly createdAt: string; - readonly resolvedAt: string | null; - }>` - SELECT - request_id AS "requestId", - status, - turn_id AS "turnId", - created_at AS "createdAt", - resolved_at AS "resolvedAt" - FROM projection_pending_approvals - WHERE request_id IN ( - 'approval-request-nonstale-existing', - 'approval-request-nonstale-missing' - ) - ORDER BY request_id - `; - assert.deepEqual(approvalRows, [ - { - requestId: "approval-request-nonstale-existing", - status: "pending", - turnId: null, - createdAt: "2026-02-26T12:45:02.000Z", - resolvedAt: null, - }, - ]); - - const threadRows = yield* sql<{ - readonly pendingApprovalCount: number; - }>` - SELECT pending_approval_count AS "pendingApprovalCount" - FROM projection_threads - WHERE thread_id = 'thread-nonstale-approval' - `; - assert.deepEqual(threadRows, [{ pendingApprovalCount: 1 }]); - }), - ); - - it.effect("does not fallback-retain messages whose turnId is removed by revert", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - const appendAndProject = (event: Parameters[0]) => - eventStore - .append(event) - .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent))); - - yield* appendAndProject({ - type: "project.created", - eventId: EventId.make("evt-revert-1"), - aggregateKind: "project", - aggregateId: ProjectId.make("project-revert"), - occurredAt: "2026-02-26T12:00:00.000Z", - commandId: CommandId.make("cmd-revert-1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-1"), - metadata: {}, - payload: { - projectId: ProjectId.make("project-revert"), - title: "Project Revert", - workspaceRoot: "/tmp/project-revert", - defaultModelSelection: null, - scripts: [], - createdAt: "2026-02-26T12:00:00.000Z", - updatedAt: "2026-02-26T12:00:00.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.created", - eventId: EventId.make("evt-revert-2"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-revert"), - occurredAt: "2026-02-26T12:00:01.000Z", - commandId: CommandId.make("cmd-revert-2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-2"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-revert"), - projectId: ProjectId.make("project-revert"), - title: "Thread Revert", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - runtimeMode: "full-access", - branch: null, - worktreePath: null, - createdAt: "2026-02-26T12:00:01.000Z", - updatedAt: "2026-02-26T12:00:01.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.turn-diff-completed", - eventId: EventId.make("evt-revert-3"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-revert"), - occurredAt: "2026-02-26T12:00:02.000Z", - commandId: CommandId.make("cmd-revert-3"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-3"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-revert"), - turnId: TurnId.make("turn-1"), - checkpointTurnCount: 1, - checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert/turn/1"), - status: "ready", - files: [], - assistantMessageId: MessageId.make("assistant-keep"), - completedAt: "2026-02-26T12:00:02.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.message-sent", - eventId: EventId.make("evt-revert-4"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-revert"), - occurredAt: "2026-02-26T12:00:02.100Z", - commandId: CommandId.make("cmd-revert-4"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-4"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-revert"), - messageId: MessageId.make("assistant-keep"), - role: "assistant", - text: "kept", - turnId: TurnId.make("turn-1"), - streaming: false, - createdAt: "2026-02-26T12:00:02.100Z", - updatedAt: "2026-02-26T12:00:02.100Z", - }, - }); - - yield* appendAndProject({ - type: "thread.turn-diff-completed", - eventId: EventId.make("evt-revert-5"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-revert"), - occurredAt: "2026-02-26T12:00:03.000Z", - commandId: CommandId.make("cmd-revert-5"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-5"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-revert"), - turnId: TurnId.make("turn-2"), - checkpointTurnCount: 2, - checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread-revert/turn/2"), - status: "ready", - files: [], - assistantMessageId: MessageId.make("assistant-remove"), - completedAt: "2026-02-26T12:00:03.000Z", - }, - }); - - yield* appendAndProject({ - type: "thread.message-sent", - eventId: EventId.make("evt-revert-6"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-revert"), - occurredAt: "2026-02-26T12:00:03.050Z", - commandId: CommandId.make("cmd-revert-6"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-6"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-revert"), - messageId: MessageId.make("user-remove"), - role: "user", - text: "removed", - turnId: TurnId.make("turn-2"), - streaming: false, - createdAt: "2026-02-26T12:00:03.050Z", - updatedAt: "2026-02-26T12:00:03.050Z", - }, - }); - - yield* appendAndProject({ - type: "thread.message-sent", - eventId: EventId.make("evt-revert-7"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-revert"), - occurredAt: "2026-02-26T12:00:03.100Z", - commandId: CommandId.make("cmd-revert-7"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-7"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-revert"), - messageId: MessageId.make("assistant-remove"), - role: "assistant", - text: "removed", - turnId: TurnId.make("turn-2"), - streaming: false, - createdAt: "2026-02-26T12:00:03.100Z", - updatedAt: "2026-02-26T12:00:03.100Z", - }, - }); - - yield* appendAndProject({ - type: "thread.reverted", - eventId: EventId.make("evt-revert-8"), - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-revert"), - occurredAt: "2026-02-26T12:00:04.000Z", - commandId: CommandId.make("cmd-revert-8"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-revert-8"), - metadata: {}, - payload: { - threadId: ThreadId.make("thread-revert"), - turnCount: 1, - }, - }); - - const messageRows = yield* sql<{ - readonly messageId: string; - readonly turnId: string | null; - readonly role: string; - }>` - SELECT - message_id AS "messageId", - turn_id AS "turnId", - role - FROM projection_thread_messages - WHERE thread_id = 'thread-revert' - ORDER BY created_at ASC, message_id ASC - `; - assert.deepEqual(messageRows, [ - { - messageId: "assistant-keep", - turnId: "turn-1", - role: "assistant", - }, - ]); - }), - ); -}); - -it.layer(makeProjectionPipelinePrefixedTestLayer("t3-pending-turn-terminal-test-"))( - "OrchestrationProjectionPipeline pending turn cleanup", - (it) => { - it.effect("clears pending turn starts when startup reaches a terminal session state", () => - Effect.gen(function* () { - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const eventStore = yield* OrchestrationEventStore; - const sql = yield* SqlClient.SqlClient; - - for (const [index, status] of (["error", "interrupted", "stopped"] as const).entries()) { - const threadId = ThreadId.make(`thread-terminal-${status}`); - const requestedAt = `2026-02-26T14:00:0${index}.000Z`; - yield* eventStore.append({ - type: "thread.turn-start-requested", - eventId: EventId.make(`evt-terminal-pending-${status}`), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: requestedAt, - commandId: CommandId.make(`cmd-terminal-pending-${status}`), - causationEventId: null, - correlationId: CorrelationId.make(`cmd-terminal-pending-${status}`), - metadata: {}, - payload: { - threadId, - messageId: MessageId.make(`message-terminal-${status}`), - runtimeMode: "approval-required", - createdAt: requestedAt, - }, - }); - yield* eventStore.append({ - type: "thread.session-set", - eventId: EventId.make(`evt-terminal-session-${status}`), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: requestedAt, - commandId: CommandId.make(`cmd-terminal-session-${status}`), - causationEventId: null, - correlationId: CorrelationId.make(`cmd-terminal-session-${status}`), - metadata: {}, - payload: { - threadId, - session: { - threadId, - status, - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: null, - lastError: status === "error" ? "startup failed" : null, - updatedAt: requestedAt, - }, - }, - }); - } - - yield* projectionPipeline.bootstrap; - - const pendingRows = yield* sql<{ readonly threadId: string }>` - SELECT thread_id AS "threadId" - FROM projection_turns - WHERE turn_id IS NULL - AND state = 'pending' - `; - assert.deepEqual(pendingRows, []); - }), - ); - }, -); - -it.effect("restores pending turn-start metadata across projection pipeline restart", () => - Effect.gen(function* () { - const { dbPath } = yield* ServerConfig; - const persistenceLayer = makeSqlitePersistenceLive(dbPath); - const firstProjectionLayer = OrchestrationProjectionPipelineLive.pipe( - Layer.provideMerge(OrchestrationEventStoreLive), - Layer.provideMerge(persistenceLayer), - ); - const secondProjectionLayer = OrchestrationProjectionPipelineLive.pipe( - Layer.provideMerge(OrchestrationEventStoreLive), - Layer.provideMerge(persistenceLayer), - ); - - const threadId = ThreadId.make("thread-restart"); - const turnId = TurnId.make("turn-restart"); - const messageId = MessageId.make("message-restart"); - const sourcePlanThreadId = ThreadId.make("thread-plan-source"); - const sourcePlanId = "plan-source"; - const turnStartedAt = "2026-02-26T14:00:00.000Z"; - const sessionSetAt = "2026-02-26T14:00:05.000Z"; - - yield* Effect.gen(function* () { - const eventStore = yield* OrchestrationEventStore; - const projectionPipeline = yield* OrchestrationProjectionPipeline; - - yield* eventStore.append({ - type: "thread.turn-start-requested", - eventId: EventId.make("evt-restart-1"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: turnStartedAt, - commandId: CommandId.make("cmd-restart-1"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-restart-1"), - metadata: {}, - payload: { - threadId, - messageId, - sourceProposedPlan: { - threadId: sourcePlanThreadId, - planId: sourcePlanId, - }, - runtimeMode: "approval-required", - createdAt: turnStartedAt, - }, - }); - - yield* projectionPipeline.bootstrap; - }).pipe(Effect.provide(firstProjectionLayer)); - - const turnRows = yield* Effect.gen(function* () { - const eventStore = yield* OrchestrationEventStore; - const projectionPipeline = yield* OrchestrationProjectionPipeline; - const sql = yield* SqlClient.SqlClient; - - yield* eventStore.append({ - type: "thread.session-set", - eventId: EventId.make("evt-restart-2"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: sessionSetAt, - commandId: CommandId.make("cmd-restart-2"), - causationEventId: null, - correlationId: CorrelationId.make("cmd-restart-2"), - metadata: {}, - payload: { - threadId, - session: { - threadId, - status: "running", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: turnId, - lastError: null, - updatedAt: sessionSetAt, - }, - }, - }); - - yield* projectionPipeline.bootstrap; - - const pendingRows = yield* sql<{ readonly threadId: string }>` - SELECT thread_id AS "threadId" - FROM projection_turns - WHERE thread_id = ${threadId} - AND turn_id IS NULL - AND state = 'pending' - `; - assert.deepEqual(pendingRows, []); - - return yield* sql<{ - readonly turnId: string; - readonly userMessageId: string | null; - readonly sourceProposedPlanThreadId: string | null; - readonly sourceProposedPlanId: string | null; - readonly startedAt: string; - }>` - SELECT - turn_id AS "turnId", - pending_message_id AS "userMessageId", - source_proposed_plan_thread_id AS "sourceProposedPlanThreadId", - source_proposed_plan_id AS "sourceProposedPlanId", - started_at AS "startedAt" - FROM projection_turns - WHERE turn_id = ${turnId} - `; - }).pipe(Effect.provide(secondProjectionLayer)); - - assert.deepEqual(turnRows, [ - { - turnId: "turn-restart", - userMessageId: "message-restart", - sourceProposedPlanThreadId: "thread-plan-source", - sourceProposedPlanId: "plan-source", - startedAt: turnStartedAt, - }, - ]); - }).pipe( - Effect.provide( - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-projection-pipeline-restart-", - }), - NodeServices.layer, - ), - ), - ), -); - -const engineLayer = it.layer( - OrchestrationEngineLive.pipe( - Layer.provide(OrchestrationProjectionSnapshotQueryLive), - Layer.provide(ThreadBackgroundLiveness.layer), - Layer.provide(ThreadPlanProgress.layer), - Layer.provide(OrchestrationProjectionPipelineLive), - Layer.provide(OrchestrationEventStoreLive), - Layer.provide(OrchestrationCommandReceiptRepositoryLive), - Layer.provide(RepositoryIdentityResolver.layer), - Layer.provideMerge(SqlitePersistenceMemory), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-projection-pipeline-engine-dispatch-", - }), - ), - Layer.provideMerge(NodeServices.layer), - ), -); - -engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => { - it.effect("projects dispatched engine events immediately", () => - Effect.gen(function* () { - const engine = yield* OrchestrationEngineService; - const sql = yield* SqlClient.SqlClient; - const createdAt = "2026-01-01T00:00:00.000Z"; - - yield* engine.dispatch({ - type: "project.create", - commandId: CommandId.make("cmd-live-project"), - projectId: ProjectId.make("project-live"), - title: "Live Project", - workspaceRoot: "/tmp/project-live", - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - createdAt, - }); - - const projectRows = yield* sql<{ readonly title: string; readonly scriptsJson: string }>` - SELECT - title, - scripts_json AS "scriptsJson" - FROM projection_projects - WHERE project_id = 'project-live' - `; - assert.deepEqual(projectRows, [{ title: "Live Project", scriptsJson: "[]" }]); - - const projectorRows = yield* sql<{ readonly lastAppliedSequence: number }>` - SELECT - last_applied_sequence AS "lastAppliedSequence" - FROM projection_state - WHERE projector = 'projection.projects' - `; - assert.deepEqual(projectorRows, [{ lastAppliedSequence: 1 }]); - }), - ); - - it.effect("projects persist updated scripts from project.meta.update", () => - Effect.gen(function* () { - const engine = yield* OrchestrationEngineService; - const sql = yield* SqlClient.SqlClient; - const createdAt = "2026-01-01T00:00:00.000Z"; - - yield* engine.dispatch({ - type: "project.create", - commandId: CommandId.make("cmd-scripts-project-create"), - projectId: ProjectId.make("project-scripts"), - title: "Scripts Project", - workspaceRoot: "/tmp/project-scripts", - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - createdAt, - }); - - yield* engine.dispatch({ - type: "project.meta.update", - commandId: CommandId.make("cmd-scripts-project-update"), - projectId: ProjectId.make("project-scripts"), - scripts: [ - { - id: "script-1", - name: "Build", - command: "bun run build", - icon: "build", - runOnWorktreeCreate: false, - }, - ], - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5", - }, - faviconPath: "brand/icon.svg", - }); - - const projectRows = yield* sql<{ - readonly scriptsJson: string; - readonly defaultModelSelection: string; - readonly faviconPath: string | null; - }>` - SELECT - scripts_json AS "scriptsJson", - default_model_selection_json AS "defaultModelSelection", - favicon_path AS "faviconPath" - FROM projection_projects - WHERE project_id = 'project-scripts' - `; - assert.deepEqual(projectRows, [ - { - scriptsJson: - '[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]', - defaultModelSelection: '{"instanceId":"codex","model":"gpt-5"}', - faviconPath: "brand/icon.svg", - }, - ]); - }), - ); -}); diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts deleted file mode 100644 index be596b36b8..0000000000 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ /dev/null @@ -1,2338 +0,0 @@ -import { - CheckpointRef, - EventId, - MessageId, - ProjectId, - ThreadId, - TurnId, - ProviderInstanceId, -} from "@t3tools/contracts"; -import { assert, it } from "@effect/vitest"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; - -import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; -import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts"; -import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts"; -import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; -import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts"; -import * as ThreadPlanProgress from "../ThreadPlanProgress.ts"; -import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; -import { encodeThreadDetailPageCursor } from "../threadDetailCursor.ts"; - -const asProjectId = (value: string): ProjectId => ProjectId.make(value); -const asTurnId = (value: string): TurnId => TurnId.make(value); -const asMessageId = (value: string): MessageId => MessageId.make(value); -const asEventId = (value: string): EventId => EventId.make(value); -const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value); - -const projectionSnapshotLayer = it.layer( - OrchestrationProjectionSnapshotQueryLive.pipe( - Layer.provide(ThreadBackgroundLiveness.layer), - Layer.provide(ThreadPlanProgress.layer), - Layer.provideMerge(RepositoryIdentityResolver.layer), - Layer.provideMerge(SqlitePersistenceMemory), - Layer.provideMerge(NodeServices.layer), - ), -); - -projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { - it.effect("hydrates read model from projection tables and computes snapshot sequence", () => - Effect.gen(function* () { - const snapshotQuery = yield* ProjectionSnapshotQuery; - const sql = yield* SqlClient.SqlClient; - - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_state`; - yield* sql`DELETE FROM projection_thread_proposed_plans`; - yield* sql`DELETE FROM projection_turns`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, - title, - workspace_root, - default_model_selection_json, - scripts_json, - created_at, - updated_at, - deleted_at - ) - VALUES ( - 'project-1', - 'Project 1', - '/tmp/project-1', - '{"provider":"codex","model":"gpt-5-codex"}', - '[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]', - '2026-02-24T00:00:00.000Z', - '2026-02-24T00:00:01.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_threads ( - thread_id, - project_id, - title, - model_selection_json, - runtime_mode, - interaction_mode, - branch, - worktree_path, - latest_turn_id, - latest_user_message_at, - pending_approval_count, - pending_user_input_count, - has_actionable_proposed_plan, - pinned_at, - pin_order_key, - created_at, - updated_at, - deleted_at - ) - VALUES ( - 'thread-1', - 'project-1', - 'Thread 1', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - 'turn-1', - '2026-02-24T00:00:04.000Z', - 1, - 0, - 0, - '2026-02-24T00:00:01.000Z', - 'gm', - '2026-02-24T00:00:02.000Z', - '2026-02-24T00:00:03.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_thread_messages ( - message_id, - thread_id, - turn_id, - role, - text, - is_streaming, - created_at, - updated_at - ) - VALUES ( - 'message-1', - 'thread-1', - 'turn-1', - 'assistant', - 'hello from projection', - 0, - '2026-02-24T00:00:04.000Z', - '2026-02-24T00:00:05.000Z' - ) - `; - - yield* sql` - INSERT INTO projection_thread_proposed_plans ( - plan_id, - thread_id, - turn_id, - plan_markdown, - implemented_at, - implementation_thread_id, - created_at, - updated_at - ) - VALUES ( - 'plan-1', - 'thread-1', - 'turn-1', - '# Ship it', - '2026-02-24T00:00:05.500Z', - 'thread-2', - '2026-02-24T00:00:05.000Z', - '2026-02-24T00:00:05.500Z' - ) - `; - - yield* sql` - INSERT INTO projection_thread_activities ( - activity_id, - thread_id, - turn_id, - tone, - kind, - summary, - payload_json, - created_at - ) - VALUES ( - 'activity-1', - 'thread-1', - 'turn-1', - 'info', - 'runtime.note', - 'provider started', - '{"stage":"start"}', - '2026-02-24T00:00:06.000Z' - ) - `; - - yield* sql` - INSERT INTO projection_thread_sessions ( - thread_id, - status, - provider_name, - provider_session_id, - provider_thread_id, - runtime_mode, - active_turn_id, - last_error, - updated_at - ) - VALUES ( - 'thread-1', - 'running', - 'codex', - 'provider-session-1', - 'provider-thread-1', - 'approval-required', - 'turn-1', - NULL, - '2026-02-24T00:00:07.000Z' - ) - `; - - yield* sql` - INSERT INTO projection_turns ( - thread_id, - turn_id, - pending_message_id, - source_proposed_plan_thread_id, - source_proposed_plan_id, - assistant_message_id, - state, - requested_at, - started_at, - completed_at, - checkpoint_turn_count, - checkpoint_ref, - checkpoint_status, - checkpoint_files_json - ) - VALUES ( - 'thread-1', - 'turn-1', - NULL, - 'thread-1', - 'plan-1', - 'message-1', - 'completed', - '2026-02-24T00:00:08.000Z', - '2026-02-24T00:00:08.000Z', - '2026-02-24T00:00:08.000Z', - 1, - 'checkpoint-1', - 'ready', - '[{"path":"README.md","kind":"modified","additions":2,"deletions":1}]' - ) - `; - - let sequence = 5; - for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) { - yield* sql` - INSERT INTO projection_state ( - projector, - last_applied_sequence, - updated_at - ) - VALUES ( - ${projector}, - ${sequence}, - '2026-02-24T00:00:09.000Z' - ) - `; - sequence += 1; - } - - const snapshot = yield* snapshotQuery.getSnapshot(); - - assert.equal(snapshot.snapshotSequence, 5); - assert.equal(snapshot.updatedAt, "2026-02-24T00:00:09.000Z"); - assert.deepEqual(snapshot.projects, [ - { - id: asProjectId("project-1"), - title: "Project 1", - workspaceRoot: "/tmp/project-1", - repositoryIdentity: null, - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - faviconPath: null, - scripts: [ - { - id: "script-1", - name: "Build", - command: "bun run build", - icon: "build", - runOnWorktreeCreate: false, - }, - ], - defaultThreadEnvMode: null, - createdAt: "2026-02-24T00:00:00.000Z", - updatedAt: "2026-02-24T00:00:01.000Z", - deletedAt: null, - }, - ]); - assert.deepEqual(snapshot.threads, [ - { - id: ThreadId.make("thread-1"), - projectId: asProjectId("project-1"), - title: "Thread 1", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: "default", - runtimeMode: "full-access", - branch: null, - worktreePath: null, - latestTurn: { - turnId: asTurnId("turn-1"), - state: "completed", - requestedAt: "2026-02-24T00:00:08.000Z", - startedAt: "2026-02-24T00:00:08.000Z", - completedAt: "2026-02-24T00:00:08.000Z", - assistantMessageId: asMessageId("message-1"), - sourceProposedPlan: { - threadId: ThreadId.make("thread-1"), - planId: "plan-1", - }, - }, - createdAt: "2026-02-24T00:00:02.000Z", - updatedAt: "2026-02-24T00:00:03.000Z", - archivedAt: null, - settledOverride: null, - settledAt: null, - snoozedUntil: null, - snoozedAt: null, - pinnedAt: "2026-02-24T00:00:01.000Z", - pinOrderKey: "gm", - titleRegeneration: null, - deletedAt: null, - messages: [ - { - id: asMessageId("message-1"), - role: "assistant", - text: "hello from projection", - turnId: asTurnId("turn-1"), - streaming: false, - createdAt: "2026-02-24T00:00:04.000Z", - updatedAt: "2026-02-24T00:00:05.000Z", - }, - ], - proposedPlans: [ - { - id: "plan-1", - turnId: asTurnId("turn-1"), - planMarkdown: "# Ship it", - implementedAt: "2026-02-24T00:00:05.500Z", - implementationThreadId: ThreadId.make("thread-2"), - createdAt: "2026-02-24T00:00:05.000Z", - updatedAt: "2026-02-24T00:00:05.500Z", - }, - ], - activities: [ - { - id: asEventId("activity-1"), - tone: "info", - kind: "runtime.note", - summary: "provider started", - payload: { stage: "start" }, - turnId: asTurnId("turn-1"), - createdAt: "2026-02-24T00:00:06.000Z", - }, - ], - checkpoints: [ - { - turnId: asTurnId("turn-1"), - checkpointTurnCount: 1, - checkpointRef: asCheckpointRef("checkpoint-1"), - status: "ready", - files: [{ path: "README.md", kind: "modified", additions: 2, deletions: 1 }], - assistantMessageId: asMessageId("message-1"), - completedAt: "2026-02-24T00:00:08.000Z", - }, - ], - session: { - threadId: ThreadId.make("thread-1"), - status: "running", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: asTurnId("turn-1"), - lastError: null, - updatedAt: "2026-02-24T00:00:07.000Z", - }, - }, - ]); - - const shellSnapshot = yield* snapshotQuery.getShellSnapshot(); - assert.equal(shellSnapshot.snapshotSequence, 5); - assert.deepEqual(shellSnapshot.projects, [ - { - id: asProjectId("project-1"), - title: "Project 1", - workspaceRoot: "/tmp/project-1", - repositoryIdentity: null, - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - faviconPath: null, - scripts: [ - { - id: "script-1", - name: "Build", - command: "bun run build", - icon: "build", - runOnWorktreeCreate: false, - }, - ], - defaultThreadEnvMode: null, - createdAt: "2026-02-24T00:00:00.000Z", - updatedAt: "2026-02-24T00:00:01.000Z", - }, - ]); - assert.deepEqual(shellSnapshot.threads, [ - { - id: ThreadId.make("thread-1"), - projectId: asProjectId("project-1"), - title: "Thread 1", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: "default", - runtimeMode: "full-access", - branch: null, - worktreePath: null, - latestTurn: { - turnId: asTurnId("turn-1"), - state: "completed", - requestedAt: "2026-02-24T00:00:08.000Z", - startedAt: "2026-02-24T00:00:08.000Z", - completedAt: "2026-02-24T00:00:08.000Z", - assistantMessageId: asMessageId("message-1"), - sourceProposedPlan: { - threadId: ThreadId.make("thread-1"), - planId: "plan-1", - }, - }, - createdAt: "2026-02-24T00:00:02.000Z", - updatedAt: "2026-02-24T00:00:03.000Z", - archivedAt: null, - settledOverride: null, - settledAt: null, - snoozedUntil: null, - snoozedAt: null, - pinnedAt: "2026-02-24T00:00:01.000Z", - pinOrderKey: "gm", - titleRegeneration: null, - session: { - threadId: ThreadId.make("thread-1"), - status: "running", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: asTurnId("turn-1"), - lastError: null, - updatedAt: "2026-02-24T00:00:07.000Z", - }, - latestUserMessageAt: "2026-02-24T00:00:04.000Z", - hasPendingApprovals: true, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - backgroundLiveness: null, - planProgress: null, - }, - ]); - - const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1")); - assert.equal(threadDetail._tag, "Some"); - if (threadDetail._tag === "Some") { - assert.deepEqual(threadDetail.value, snapshot.threads[0]); - } - }), - ); - - it.effect("keeps archived threads out of the main shell snapshot", () => - Effect.gen(function* () { - const snapshotQuery = yield* ProjectionSnapshotQuery; - const sql = yield* SqlClient.SqlClient; - - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_state`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, - title, - workspace_root, - default_model_selection_json, - scripts_json, - created_at, - updated_at, - deleted_at - ) - VALUES ( - 'project-archive-test', - 'Archive Test', - '/tmp/archive-test', - '{"provider":"codex","model":"gpt-5-codex"}', - '[]', - '2026-04-06T00:00:00.000Z', - '2026-04-06T00:00:01.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_threads ( - thread_id, - project_id, - title, - model_selection_json, - runtime_mode, - interaction_mode, - branch, - worktree_path, - latest_turn_id, - latest_user_message_at, - pending_approval_count, - pending_user_input_count, - has_actionable_proposed_plan, - created_at, - updated_at, - archived_at, - deleted_at - ) - VALUES - ( - 'thread-active', - 'project-archive-test', - 'Active Thread', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - NULL, - NULL, - 0, - 0, - 0, - '2026-04-06T00:00:02.000Z', - '2026-04-06T00:00:03.000Z', - NULL, - NULL - ), - ( - 'thread-archived', - 'project-archive-test', - 'Archived Thread', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - NULL, - NULL, - 0, - 0, - 0, - '2026-04-06T00:00:04.000Z', - '2026-04-06T00:00:05.000Z', - '2026-04-06T00:00:06.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_state (projector, last_applied_sequence, updated_at) - VALUES - (${ORCHESTRATION_PROJECTOR_NAMES.projects}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threads}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 4, '2026-04-06T00:00:07.000Z') - `; - - const shellSnapshot = yield* snapshotQuery.getShellSnapshot(); - assert.deepEqual( - shellSnapshot.threads.map((thread) => thread.id), - [ThreadId.make("thread-active")], - ); - - const archivedShellSnapshot = yield* snapshotQuery.getArchivedShellSnapshot(); - assert.deepEqual( - archivedShellSnapshot.threads.map((thread) => thread.id), - [ThreadId.make("thread-archived")], - ); - assert.equal(archivedShellSnapshot.threads[0]?.archivedAt, "2026-04-06T00:00:06.000Z"); - }), - ); - - it.effect("keeps settled threads in the shell snapshot with non-null settlement fields", () => - Effect.gen(function* () { - const snapshotQuery = yield* ProjectionSnapshotQuery; - const sql = yield* SqlClient.SqlClient; - - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_state`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, - title, - workspace_root, - default_model_selection_json, - scripts_json, - created_at, - updated_at, - deleted_at - ) - VALUES ( - 'project-settled-test', - 'Settled Test', - '/tmp/settled-test', - '{"provider":"codex","model":"gpt-5-codex"}', - '[]', - '2026-04-06T00:00:00.000Z', - '2026-04-06T00:00:01.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_threads ( - thread_id, - project_id, - title, - model_selection_json, - runtime_mode, - interaction_mode, - branch, - worktree_path, - latest_turn_id, - latest_user_message_at, - pending_approval_count, - pending_user_input_count, - has_actionable_proposed_plan, - created_at, - updated_at, - archived_at, - settled_override, - settled_at, - deleted_at - ) - VALUES ( - 'thread-settled', - 'project-settled-test', - 'Settled Thread', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - NULL, - NULL, - 0, - 0, - 0, - '2026-04-06T00:00:02.000Z', - '2026-04-06T00:00:05.000Z', - NULL, - 'settled', - '2026-04-06T00:00:04.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_state (projector, last_applied_sequence, updated_at) - VALUES - (${ORCHESTRATION_PROJECTOR_NAMES.projects}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threads}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 4, '2026-04-06T00:00:07.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 4, '2026-04-06T00:00:07.000Z') - `; - - // Settled ≠ archived: the thread must appear in the LIVE shell - // snapshot, carrying its settlement fields through the row aliases. - const shellSnapshot = yield* snapshotQuery.getShellSnapshot(); - assert.deepEqual( - shellSnapshot.threads.map((thread) => thread.id), - [ThreadId.make("thread-settled")], - ); - assert.equal(shellSnapshot.threads[0]?.settledOverride, "settled"); - assert.equal(shellSnapshot.threads[0]?.settledAt, "2026-04-06T00:00:04.000Z"); - - // And the full command read model carries them too. - const readModel = yield* snapshotQuery.getCommandReadModel(); - const thread = readModel.threads.find( - (candidate) => candidate.id === ThreadId.make("thread-settled"), - ); - assert.equal(thread?.settledOverride, "settled"); - assert.equal(thread?.settledAt, "2026-04-06T00:00:04.000Z"); - }), - ); - - it.effect( - "reads targeted project, thread, and count queries without hydrating the full snapshot", - () => - Effect.gen(function* () { - const snapshotQuery = yield* ProjectionSnapshotQuery; - const sql = yield* SqlClient.SqlClient; - - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_turns`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, - title, - workspace_root, - default_model_selection_json, - scripts_json, - created_at, - updated_at, - deleted_at - ) - VALUES - ( - 'project-active', - 'Active Project', - '/tmp/workspace', - '{"provider":"codex","model":"gpt-5-codex"}', - '[]', - '2026-03-01T00:00:00.000Z', - '2026-03-01T00:00:01.000Z', - NULL - ), - ( - 'project-deleted', - 'Deleted Project', - '/tmp/deleted', - NULL, - '[]', - '2026-03-01T00:00:02.000Z', - '2026-03-01T00:00:03.000Z', - '2026-03-01T00:00:04.000Z' - ) - `; - - yield* sql` - INSERT INTO projection_threads ( - thread_id, - project_id, - title, - model_selection_json, - runtime_mode, - interaction_mode, - branch, - worktree_path, - latest_turn_id, - created_at, - updated_at, - archived_at, - deleted_at - ) - VALUES - ( - 'thread-first', - 'project-active', - 'First Thread', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - NULL, - '2026-03-01T00:00:05.000Z', - '2026-03-01T00:00:06.000Z', - NULL, - NULL - ), - ( - 'thread-second', - 'project-active', - 'Second Thread', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - NULL, - '2026-03-01T00:00:07.000Z', - '2026-03-01T00:00:08.000Z', - NULL, - NULL - ), - ( - 'thread-deleted', - 'project-active', - 'Deleted Thread', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - NULL, - '2026-03-01T00:00:09.000Z', - '2026-03-01T00:00:10.000Z', - NULL, - '2026-03-01T00:00:11.000Z' - ) - `; - - const counts = yield* snapshotQuery.getCounts(); - assert.deepEqual(counts, { - projectCount: 2, - threadCount: 3, - }); - - const project = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/workspace"); - assert.equal(project._tag, "Some"); - if (project._tag === "Some") { - assert.equal(project.value.id, asProjectId("project-active")); - } - - const missingProject = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/missing"); - assert.equal(missingProject._tag, "None"); - - const firstThreadId = yield* snapshotQuery.getFirstActiveThreadIdByProjectId( - asProjectId("project-active"), - ); - assert.equal(firstThreadId._tag, "Some"); - if (firstThreadId._tag === "Some") { - assert.equal(firstThreadId.value, ThreadId.make("thread-first")); - } - }), - ); - - it.effect("reads single-thread checkpoint context without hydrating unrelated threads", () => - Effect.gen(function* () { - const snapshotQuery = yield* ProjectionSnapshotQuery; - const sql = yield* SqlClient.SqlClient; - - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_turns`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, - title, - workspace_root, - default_model_selection_json, - scripts_json, - created_at, - updated_at, - deleted_at - ) - VALUES ( - 'project-context', - 'Context Project', - '/tmp/context-workspace', - NULL, - '[]', - '2026-03-02T00:00:00.000Z', - '2026-03-02T00:00:01.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_threads ( - thread_id, - project_id, - title, - model_selection_json, - runtime_mode, - interaction_mode, - branch, - worktree_path, - latest_turn_id, - created_at, - updated_at, - archived_at, - deleted_at - ) - VALUES ( - 'thread-context', - 'project-context', - 'Context Thread', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - 'feature/perf', - '/tmp/context-worktree', - NULL, - '2026-03-02T00:00:02.000Z', - '2026-03-02T00:00:03.000Z', - NULL, - NULL - ) - `; - - yield* sql` - INSERT INTO projection_turns ( - thread_id, - turn_id, - pending_message_id, - source_proposed_plan_thread_id, - source_proposed_plan_id, - assistant_message_id, - state, - requested_at, - started_at, - completed_at, - checkpoint_turn_count, - checkpoint_ref, - checkpoint_status, - checkpoint_files_json - ) - VALUES - ( - 'thread-context', - 'turn-1', - NULL, - NULL, - NULL, - NULL, - 'completed', - '2026-03-02T00:00:04.000Z', - '2026-03-02T00:00:04.000Z', - '2026-03-02T00:00:04.000Z', - 1, - 'checkpoint-a', - 'ready', - '[]' - ), - ( - 'thread-context', - 'turn-2', - NULL, - NULL, - NULL, - NULL, - 'completed', - '2026-03-02T00:00:05.000Z', - '2026-03-02T00:00:05.000Z', - '2026-03-02T00:00:05.000Z', - 2, - 'checkpoint-b', - 'ready', - '[]' - ) - `; - - const context = yield* snapshotQuery.getThreadCheckpointContext( - ThreadId.make("thread-context"), - ); - assert.equal(context._tag, "Some"); - if (context._tag === "Some") { - assert.deepEqual(context.value, { - threadId: ThreadId.make("thread-context"), - projectId: asProjectId("project-context"), - workspaceRoot: "/tmp/context-workspace", - worktreePath: "/tmp/context-worktree", - checkpoints: [ - { - turnId: asTurnId("turn-1"), - checkpointTurnCount: 1, - checkpointRef: asCheckpointRef("checkpoint-a"), - status: "ready", - files: [], - assistantMessageId: null, - completedAt: "2026-03-02T00:00:04.000Z", - }, - { - turnId: asTurnId("turn-2"), - checkpointTurnCount: 2, - checkpointRef: asCheckpointRef("checkpoint-b"), - status: "ready", - files: [], - assistantMessageId: null, - completedAt: "2026-03-02T00:00:05.000Z", - }, - ], - }); - } - }), - ); - - it.effect("keeps thread detail activity ordering consistent with shell snapshot ordering", () => - Effect.gen(function* () { - const snapshotQuery = yield* ProjectionSnapshotQuery; - const sql = yield* SqlClient.SqlClient; - - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_thread_activities`; - yield* sql`DELETE FROM projection_state`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, - title, - workspace_root, - default_model_selection_json, - scripts_json, - created_at, - updated_at, - deleted_at - ) - VALUES ( - 'project-1', - 'Project 1', - '/tmp/project-1', - '{"provider":"codex","model":"gpt-5-codex"}', - '[]', - '2026-04-01T00:00:00.000Z', - '2026-04-01T00:00:01.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_threads ( - thread_id, - project_id, - title, - model_selection_json, - runtime_mode, - interaction_mode, - branch, - worktree_path, - latest_turn_id, - latest_user_message_at, - pending_approval_count, - pending_user_input_count, - has_actionable_proposed_plan, - created_at, - updated_at, - deleted_at - ) - VALUES ( - 'thread-1', - 'project-1', - 'Thread 1', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - NULL, - NULL, - 0, - 0, - 0, - '2026-04-01T00:00:02.000Z', - '2026-04-01T00:00:03.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_thread_activities ( - activity_id, - thread_id, - turn_id, - tone, - kind, - summary, - payload_json, - sequence, - created_at - ) - VALUES - ( - 'activity-unsequenced', - 'thread-1', - NULL, - 'info', - 'runtime.note', - 'unsequenced first', - '{"source":"unsequenced"}', - NULL, - '2026-04-01T00:00:06.000Z' - ), - ( - 'activity-sequence-2', - 'thread-1', - NULL, - 'info', - 'runtime.note', - 'sequence two', - '{"source":"sequence-2"}', - 2, - '2026-04-01T00:00:04.000Z' - ), - ( - 'activity-sequence-1', - 'thread-1', - NULL, - 'info', - 'runtime.note', - 'sequence one', - '{"source":"sequence-1"}', - 1, - '2026-04-01T00:00:05.000Z' - ) - `; - - const snapshot = yield* snapshotQuery.getSnapshot(); - const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1")); - - assert.equal(threadDetail._tag, "Some"); - if (threadDetail._tag === "Some") { - assert.deepEqual(threadDetail.value.activities, snapshot.threads[0]?.activities ?? []); - } - - assert.deepEqual(snapshot.threads[0]?.activities ?? [], [ - { - id: asEventId("activity-unsequenced"), - tone: "info", - kind: "runtime.note", - summary: "unsequenced first", - payload: { source: "unsequenced" }, - turnId: null, - createdAt: "2026-04-01T00:00:06.000Z", - }, - { - id: asEventId("activity-sequence-1"), - tone: "info", - kind: "runtime.note", - summary: "sequence one", - payload: { source: "sequence-1" }, - turnId: null, - sequence: 1, - createdAt: "2026-04-01T00:00:05.000Z", - }, - { - id: asEventId("activity-sequence-2"), - tone: "info", - kind: "runtime.note", - summary: "sequence two", - payload: { source: "sequence-2" }, - turnId: null, - sequence: 2, - createdAt: "2026-04-01T00:00:04.000Z", - }, - ]); - }), - ); - - it.effect("uses projection_threads.latest_turn_id for targeted thread latest turn queries", () => - Effect.gen(function* () { - const snapshotQuery = yield* ProjectionSnapshotQuery; - const sql = yield* SqlClient.SqlClient; - - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_turns`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, - title, - workspace_root, - default_model_selection_json, - scripts_json, - created_at, - updated_at, - deleted_at - ) - VALUES ( - 'project-1', - 'Project 1', - '/tmp/project-1', - '{"provider":"codex","model":"gpt-5-codex"}', - '[]', - '2026-04-02T00:00:00.000Z', - '2026-04-02T00:00:01.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_threads ( - thread_id, - project_id, - title, - model_selection_json, - runtime_mode, - interaction_mode, - branch, - worktree_path, - latest_turn_id, - latest_user_message_at, - pending_approval_count, - pending_user_input_count, - has_actionable_proposed_plan, - created_at, - updated_at, - archived_at, - deleted_at - ) - VALUES ( - 'thread-1', - 'project-1', - 'Thread 1', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - 'turn-running', - '2026-04-02T00:00:04.000Z', - 0, - 0, - 0, - '2026-04-02T00:00:02.000Z', - '2026-04-02T00:00:03.000Z', - NULL, - NULL - ) - `; - - yield* sql` - INSERT INTO projection_turns ( - thread_id, - turn_id, - pending_message_id, - source_proposed_plan_thread_id, - source_proposed_plan_id, - assistant_message_id, - state, - requested_at, - started_at, - completed_at, - checkpoint_turn_count, - checkpoint_ref, - checkpoint_status, - checkpoint_files_json - ) - VALUES - ( - 'thread-1', - 'turn-completed', - 'message-user-1', - NULL, - NULL, - 'message-assistant-1', - 'completed', - '2026-04-02T00:00:05.000Z', - '2026-04-02T00:00:06.000Z', - '2026-04-02T00:00:20.000Z', - 5, - 'checkpoint-5', - 'ready', - '[]' - ), - ( - 'thread-1', - 'turn-running', - 'message-user-2', - NULL, - NULL, - NULL, - 'running', - '2026-04-02T00:00:30.000Z', - '2026-04-02T00:00:30.000Z', - NULL, - NULL, - NULL, - NULL, - '[]' - ) - `; - - const threadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1")); - assert.equal(threadShell._tag, "Some"); - if (threadShell._tag === "Some") { - assert.equal(threadShell.value.latestTurn?.turnId, asTurnId("turn-running")); - assert.equal(threadShell.value.latestTurn?.state, "running"); - assert.equal(threadShell.value.latestTurn?.startedAt, "2026-04-02T00:00:30.000Z"); - } - - const threadDetail = yield* snapshotQuery.getThreadDetailById(ThreadId.make("thread-1")); - assert.equal(threadDetail._tag, "Some"); - if (threadDetail._tag === "Some") { - assert.equal(threadDetail.value.latestTurn?.turnId, asTurnId("turn-running")); - assert.equal(threadDetail.value.latestTurn?.state, "running"); - assert.equal(threadDetail.value.latestTurn?.startedAt, "2026-04-02T00:00:30.000Z"); - } - }), - ); - - it.effect("uses projection_threads.latest_turn_id for bulk command and shell snapshots", () => - Effect.gen(function* () { - const snapshotQuery = yield* ProjectionSnapshotQuery; - const sql = yield* SqlClient.SqlClient; - - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_turns`; - yield* sql`DELETE FROM projection_state`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, - title, - workspace_root, - default_model_selection_json, - scripts_json, - created_at, - updated_at, - deleted_at - ) - VALUES ( - 'project-1', - 'Project 1', - '/tmp/project-1', - '{"provider":"codex","model":"gpt-5-codex"}', - '[]', - '2026-04-03T00:00:00.000Z', - '2026-04-03T00:00:01.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_threads ( - thread_id, - project_id, - title, - model_selection_json, - runtime_mode, - interaction_mode, - branch, - worktree_path, - latest_turn_id, - latest_user_message_at, - pending_approval_count, - pending_user_input_count, - has_actionable_proposed_plan, - created_at, - updated_at, - archived_at, - deleted_at - ) - VALUES ( - 'thread-1', - 'project-1', - 'Thread 1', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - 'turn-running', - '2026-04-03T00:00:04.000Z', - 0, - 0, - 0, - '2026-04-03T00:00:02.000Z', - '2026-04-03T00:00:03.000Z', - NULL, - NULL - ) - `; - - yield* sql` - INSERT INTO projection_turns ( - thread_id, - turn_id, - pending_message_id, - source_proposed_plan_thread_id, - source_proposed_plan_id, - assistant_message_id, - state, - requested_at, - started_at, - completed_at, - checkpoint_turn_count, - checkpoint_ref, - checkpoint_status, - checkpoint_files_json - ) - VALUES - ( - 'thread-1', - 'turn-running', - 'message-user-2', - NULL, - NULL, - NULL, - 'running', - '2026-04-03T00:00:30.000Z', - '2026-04-03T00:00:30.000Z', - NULL, - NULL, - NULL, - NULL, - '[]' - ), - ( - 'thread-1', - 'turn-completed', - 'message-user-1', - NULL, - NULL, - 'message-assistant-1', - 'completed', - '2026-04-03T00:00:05.000Z', - '2026-04-03T00:00:06.000Z', - '2026-04-03T00:00:20.000Z', - NULL, - NULL, - NULL, - '[]' - ) - `; - - yield* sql` - INSERT INTO projection_state (projector, last_applied_sequence, updated_at) - VALUES - (${ORCHESTRATION_PROJECTOR_NAMES.projects}, 3, '2026-04-03T00:00:40.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threads}, 3, '2026-04-03T00:00:40.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 3, '2026-04-03T00:00:40.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 3, '2026-04-03T00:00:40.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 3, '2026-04-03T00:00:40.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 3, '2026-04-03T00:00:40.000Z'), - (${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 3, '2026-04-03T00:00:40.000Z') - `; - - const commandReadModel = yield* snapshotQuery.getCommandReadModel(); - assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-running")); - assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "running"); - - const shellSnapshot = yield* snapshotQuery.getShellSnapshot(); - assert.equal(shellSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running")); - assert.equal(shellSnapshot.threads[0]?.latestTurn?.state, "running"); - - const fullSnapshot = yield* snapshotQuery.getSnapshot(); - assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-running")); - assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "running"); - }), - ); - - it.effect("keeps deleted project and thread tombstones in the command read model", () => - Effect.gen(function* () { - const snapshotQuery = yield* ProjectionSnapshotQuery; - const sql = yield* SqlClient.SqlClient; - - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_turns`; - yield* sql`DELETE FROM projection_state`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, - title, - workspace_root, - default_model_selection_json, - scripts_json, - created_at, - updated_at, - deleted_at - ) - VALUES ( - 'project-deleted', - 'Deleted Project', - '/tmp/deleted-project', - '{"provider":"codex","model":"gpt-5-codex"}', - '[]', - '2026-04-05T00:00:00.000Z', - '2026-04-05T00:00:01.000Z', - '2026-04-05T00:00:02.000Z' - ) - `; - - yield* sql` - INSERT INTO projection_threads ( - thread_id, - project_id, - title, - model_selection_json, - runtime_mode, - interaction_mode, - branch, - worktree_path, - latest_turn_id, - latest_user_message_at, - pending_approval_count, - pending_user_input_count, - has_actionable_proposed_plan, - created_at, - updated_at, - archived_at, - deleted_at - ) - VALUES ( - 'thread-deleted', - 'project-deleted', - 'Deleted Thread', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - 'turn-deleted', - NULL, - 0, - 0, - 0, - '2026-04-05T00:00:03.000Z', - '2026-04-05T00:00:04.000Z', - NULL, - '2026-04-05T00:00:05.000Z' - ) - `; - - yield* sql` - INSERT INTO projection_turns ( - thread_id, - turn_id, - pending_message_id, - source_proposed_plan_thread_id, - source_proposed_plan_id, - assistant_message_id, - state, - requested_at, - started_at, - completed_at, - checkpoint_turn_count, - checkpoint_ref, - checkpoint_status, - checkpoint_files_json - ) - VALUES ( - 'thread-deleted', - 'turn-deleted', - 'message-deleted-user', - NULL, - NULL, - 'message-deleted-assistant', - 'completed', - '2026-04-05T00:00:04.100Z', - '2026-04-05T00:00:04.200Z', - '2026-04-05T00:00:04.300Z', - NULL, - NULL, - NULL, - '[]' - ) - `; - - const commandReadModel = yield* snapshotQuery.getCommandReadModel(); - assert.equal(commandReadModel.projects[0]?.id, asProjectId("project-deleted")); - assert.equal(commandReadModel.projects[0]?.deletedAt, "2026-04-05T00:00:02.000Z"); - assert.equal(commandReadModel.threads[0]?.id, ThreadId.make("thread-deleted")); - assert.equal(commandReadModel.threads[0]?.deletedAt, "2026-04-05T00:00:05.000Z"); - assert.equal(commandReadModel.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted")); - assert.equal(commandReadModel.threads[0]?.latestTurn?.state, "completed"); - - const fullSnapshot = yield* snapshotQuery.getSnapshot(); - assert.equal(fullSnapshot.threads[0]?.id, ThreadId.make("thread-deleted")); - assert.equal(fullSnapshot.threads[0]?.latestTurn?.turnId, asTurnId("turn-deleted")); - assert.equal(fullSnapshot.threads[0]?.latestTurn?.state, "completed"); - - const shellSnapshot = yield* snapshotQuery.getShellSnapshot(); - assert.equal(shellSnapshot.projects.length, 0); - assert.equal(shellSnapshot.threads.length, 0); - }), - ); - - it.effect("searches active user messages and canonical assistant outputs", () => - Effect.gen(function* () { - const snapshotQuery = yield* ProjectionSnapshotQuery; - const sql = yield* SqlClient.SqlClient; - - yield* sql`DELETE FROM projection_thread_messages`; - yield* sql`DELETE FROM projection_turns`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_projects`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, - title, - workspace_root, - default_model_selection_json, - scripts_json, - created_at, - updated_at, - deleted_at - ) - VALUES ( - 'project-search', - 'Project Needle', - '/tmp/project-search', - '{"provider":"codex","model":"gpt-5-codex"}', - '[]', - '2026-05-01T00:00:00.000Z', - '2026-05-01T00:00:01.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_threads ( - thread_id, - project_id, - title, - model_selection_json, - runtime_mode, - interaction_mode, - branch, - worktree_path, - latest_turn_id, - latest_user_message_at, - pending_approval_count, - pending_user_input_count, - has_actionable_proposed_plan, - created_at, - updated_at, - archived_at, - deleted_at - ) - VALUES - ( - 'thread-active', - 'project-search', - 'Literal 100% fix', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - 'search-branch', - NULL, - 'turn-active', - '2026-05-01T00:00:02.000Z', - 0, - 0, - 0, - '2026-05-01T00:00:02.000Z', - '2026-05-01T00:00:03.000Z', - NULL, - NULL - ), - ( - 'thread-percent-decoy', - 'project-search', - 'Literal 100x fix', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - NULL, - NULL, - 0, - 0, - 0, - '2026-05-01T00:00:04.000Z', - '2026-05-01T00:00:05.000Z', - NULL, - NULL - ), - ( - 'thread-hidden', - 'project-search', - 'Archived search', - '{"provider":"codex","model":"gpt-5-codex"}', - 'full-access', - 'default', - NULL, - NULL, - NULL, - NULL, - 0, - 0, - 0, - '2026-05-01T00:00:06.000Z', - '2026-05-01T00:00:07.000Z', - '2026-05-01T00:00:08.000Z', - NULL - ) - `; - - yield* sql` - INSERT INTO projection_thread_messages ( - message_id, - thread_id, - turn_id, - role, - text, - is_streaming, - created_at, - updated_at - ) - VALUES - ( - 'message-user', - 'thread-active', - 'turn-active', - 'user', - 'Please find this USER needle in an old prompt.', - 0, - '2026-05-01T00:00:12.000Z', - '2026-05-01T00:00:12.000Z' - ), - ( - 'message-percent', - 'thread-active', - NULL, - 'user', - 'Literal 100% fix in a prompt.', - 0, - '2026-05-01T00:00:11.000Z', - '2026-05-01T00:00:11.000Z' - ), - ( - 'message-percent-decoy', - 'thread-percent-decoy', - NULL, - 'user', - 'Literal 100x fix in a prompt.', - 0, - '2026-05-01T00:00:11.000Z', - '2026-05-01T00:00:11.000Z' - ), - ( - 'message-final', - 'thread-active', - 'turn-active', - 'assistant', - 'The canonical final needle appears in this completed answer.', - 0, - '2026-05-01T00:00:13.000Z', - '2026-05-01T00:00:13.000Z' - ), - ( - 'message-interim', - 'thread-active', - 'turn-active', - 'assistant', - 'Interim needle must not be searchable.', - 0, - '2026-05-01T00:00:14.000Z', - '2026-05-01T00:00:14.000Z' - ), - ( - 'message-system', - 'thread-active', - NULL, - 'system', - 'System needle must not be searchable.', - 0, - '2026-05-01T00:00:15.000Z', - '2026-05-01T00:00:15.000Z' - ), - ( - 'message-hidden', - 'thread-hidden', - NULL, - 'user', - 'Hidden needle in archive.', - 0, - '2026-05-01T00:00:16.000Z', - '2026-05-01T00:00:16.000Z' - ) - `; - - yield* sql` - INSERT INTO projection_turns ( - thread_id, - turn_id, - pending_message_id, - assistant_message_id, - state, - requested_at, - started_at, - completed_at, - checkpoint_files_json - ) - VALUES ( - 'thread-active', - 'turn-active', - 'message-user', - 'message-final', - 'completed', - '2026-05-01T00:00:12.000Z', - '2026-05-01T00:00:12.000Z', - '2026-05-01T00:00:13.000Z', - '[]' - ) - `; - - const literalPercent = yield* snapshotQuery.searchThreads({ query: "100%" }); - assert.deepStrictEqual( - literalPercent.matches.map((match) => [match.threadId, match.source]), - [[ThreadId.make("thread-active"), "user"]], - ); - - const user = yield* snapshotQuery.searchThreads({ query: "user needle" }); - assert.equal(user.matches[0]?.source, "user"); - assert.match(user.matches[0]?.snippet ?? "", /USER needle/); - - const assistant = yield* snapshotQuery.searchThreads({ query: "FINAL NEEDLE" }); - assert.equal(assistant.matches[0]?.source, "assistant"); - - const deduped = yield* snapshotQuery.searchThreads({ query: "needle" }); - assert.deepStrictEqual( - deduped.matches.map((match) => [match.threadId, match.source]), - [[ThreadId.make("thread-active"), "user"]], - ); - - assert.deepStrictEqual( - (yield* snapshotQuery.searchThreads({ query: "interim needle" })).matches, - [], - ); - assert.deepStrictEqual( - (yield* snapshotQuery.searchThreads({ query: "system needle" })).matches, - [], - ); - assert.deepStrictEqual( - (yield* snapshotQuery.searchThreads({ query: "hidden needle" })).matches, - [], - ); - yield* sql` - UPDATE projection_threads - SET deleted_at = '2026-05-01T00:00:20.000Z' - WHERE thread_id = 'thread-active' - `; - assert.deepStrictEqual( - (yield* snapshotQuery.searchThreads({ query: "user needle" })).matches, - [], - ); - }), - ); -}); - -it.effect( - "ProjectionSnapshotQuery dedupes repository identity resolution by workspace root and skips deleted projects for shell snapshots", - () => { - const resolveCalls: string[] = []; - const layer = OrchestrationProjectionSnapshotQueryLive.pipe( - Layer.provide(ThreadBackgroundLiveness.layer), - Layer.provide(ThreadPlanProgress.layer), - Layer.provideMerge( - Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { - resolve: (cwd: string) => - Effect.sync(() => { - resolveCalls.push(cwd); - return { - canonicalKey: `github.com/acme${cwd}`, - locator: { - source: "git-remote" as const, - remoteName: "origin", - remoteUrl: `https://github.com/acme${cwd}.git`, - }, - rootPath: cwd, - }; - }), - }), - ), - Layer.provideMerge(SqlitePersistenceMemory), - ); - - return Effect.gen(function* () { - const snapshotQuery = yield* ProjectionSnapshotQuery; - const sql = yield* SqlClient.SqlClient; - - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_turns`; - yield* sql`DELETE FROM projection_state`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, - title, - workspace_root, - default_model_selection_json, - scripts_json, - created_at, - updated_at, - deleted_at - ) - VALUES - ( - 'project-1', - 'Shared Project 1', - '/tmp/shared-root', - '{"provider":"codex","model":"gpt-5-codex"}', - '[]', - '2026-04-04T00:00:00.000Z', - '2026-04-04T00:00:01.000Z', - NULL - ), - ( - 'project-2', - 'Shared Project 2', - '/tmp/shared-root', - '{"provider":"codex","model":"gpt-5-codex"}', - '[]', - '2026-04-04T00:00:02.000Z', - '2026-04-04T00:00:03.000Z', - NULL - ), - ( - 'project-3', - 'Deleted Project', - '/tmp/deleted-root', - '{"provider":"codex","model":"gpt-5-codex"}', - '[]', - '2026-04-04T00:00:04.000Z', - '2026-04-04T00:00:05.000Z', - '2026-04-04T00:00:06.000Z' - ) - `; - - const shellSnapshot = yield* snapshotQuery.getShellSnapshot(); - assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/shared-root"]); - assert.equal(shellSnapshot.projects.length, 2); - assert.equal(shellSnapshot.projects[0]?.repositoryIdentity?.rootPath, "/tmp/shared-root"); - assert.equal(shellSnapshot.projects[1]?.repositoryIdentity?.rootPath, "/tmp/shared-root"); - - resolveCalls.length = 0; - - const fullSnapshot = yield* snapshotQuery.getSnapshot(); - assert.deepStrictEqual(resolveCalls.toSorted(), ["/tmp/deleted-root", "/tmp/shared-root"]); - assert.equal(fullSnapshot.projects.length, 3); - assert.equal(fullSnapshot.projects[2]?.repositoryIdentity?.rootPath, "/tmp/deleted-root"); - }).pipe(Effect.provide(layer)); - }, -); - -projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) => { - // A thread shaped like real fan-out usage: user turns interleaved with - // subagent turns (no user pending message), plus a turnless straggler user - // message and a turnless activity anchored between turns. - // - // row turn pending msg anchor (requested_at) - // 1 turn-1 user-msg-1 T00 - // 2 turn-2 (subagent) T01 - // 3 turn-3 (subagent) T02 - // 4 turn-4 user-msg-4 T03 - // 5 turn-5 user-msg-5 T04 - // - // Straggler user message at T03.5 (turn_id NULL, not any pending_message_id) - // and a turnless activity at T03.6 — both belong to the page containing T03+. - const seedFanOutThread = Effect.fnUntraced(function* () { - const sql = yield* SqlClient.SqlClient; - - // Tests in this block share one in-memory database; reset before seeding. - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_turns`; - yield* sql`DELETE FROM projection_thread_messages`; - yield* sql`DELETE FROM projection_thread_activities`; - yield* sql`DELETE FROM projection_state`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at - ) - VALUES ('project-w', 'Windowed', '/tmp/project-w', '[]', - '2026-03-01T00:00:00.000Z', '2026-03-01T00:00:00.000Z', NULL) - `; - yield* sql` - INSERT INTO projection_threads ( - thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode, - latest_turn_id, pending_approval_count, pending_user_input_count, - has_actionable_proposed_plan, created_at, updated_at, deleted_at - ) - VALUES ('thread-w', 'project-w', 'Windowed thread', - '{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default', - 'turn-5', 0, 0, 0, '2026-03-01T00:00:00.000Z', '2026-03-01T00:00:10.000Z', NULL) - `; - - const turns: ReadonlyArray<{ - turn: string; - pendingMessage: string | null; - at: string; - }> = [ - { turn: "turn-1", pendingMessage: "user-msg-1", at: "2026-03-01T00:00:00.000Z" }, - { turn: "turn-2", pendingMessage: null, at: "2026-03-01T00:01:00.000Z" }, - { turn: "turn-3", pendingMessage: null, at: "2026-03-01T00:02:00.000Z" }, - { turn: "turn-4", pendingMessage: "user-msg-4", at: "2026-03-01T00:03:00.000Z" }, - { turn: "turn-5", pendingMessage: "user-msg-5", at: "2026-03-01T00:04:00.000Z" }, - ]; - for (const { turn, pendingMessage, at } of turns) { - yield* sql` - INSERT INTO projection_turns ( - thread_id, turn_id, pending_message_id, state, requested_at, started_at, completed_at, - checkpoint_files_json - ) - VALUES ('thread-w', ${turn}, ${pendingMessage}, 'completed', ${at}, ${at}, ${at}, '[]') - `; - if (pendingMessage !== null) { - yield* sql` - INSERT INTO projection_thread_messages ( - message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at - ) - VALUES (${pendingMessage}, 'thread-w', NULL, 'user', ${"prompt for " + turn}, 0, ${at}, ${at}) - `; - } - yield* sql` - INSERT INTO projection_thread_messages ( - message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at - ) - VALUES (${turn + "-reply"}, 'thread-w', ${turn}, 'assistant', ${"reply from " + turn}, 0, ${at}, ${at}) - `; - yield* sql` - INSERT INTO projection_thread_activities ( - activity_id, thread_id, turn_id, tone, kind, summary, payload_json, created_at - ) - VALUES (${turn + "-activity"}, 'thread-w', ${turn}, 'tool', 'tool.completed', - 'ran tool', '{"ok":true}', ${at}) - `; - } - - // Straggler user message sent while turn-4 ran: turn_id NULL and not any - // turn's pending_message_id. - yield* sql` - INSERT INTO projection_thread_messages ( - message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at - ) - VALUES ('user-msg-straggler', 'thread-w', NULL, 'user', 'while you are at it', - 0, '2026-03-01T00:03:30.000Z', '2026-03-01T00:03:30.000Z') - `; - // Turnless activity in the same time range. - yield* sql` - INSERT INTO projection_thread_activities ( - activity_id, thread_id, turn_id, tone, kind, summary, payload_json, created_at - ) - VALUES ('turnless-activity', 'thread-w', NULL, 'info', 'context-window.updated', - 'usage', '{"usedTokens":1}', '2026-03-01T00:03:36.000Z') - `; - - for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) { - yield* sql` - INSERT INTO projection_state (projector, last_applied_sequence, updated_at) - VALUES (${projector}, 42, '2026-03-01T00:00:10.000Z') - `; - } - }); - - const threadW = ThreadId.make("thread-w"); - const messageIds = (snapshot: { thread: { messages: ReadonlyArray<{ id: string }> } }) => - snapshot.thread.messages.map((message) => message.id).toSorted(); - const activityIds = (snapshot: { thread: { activities: ReadonlyArray<{ id: string }> } }) => - snapshot.thread.activities.map((activity) => activity.id).toSorted(); - - it.effect("returns the full thread with no page metadata when no window is requested", () => - Effect.gen(function* () { - yield* seedFanOutThread(); - const snapshotQuery = yield* ProjectionSnapshotQuery; - - const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW); - assert.equal(snapshot._tag, "Some"); - if (snapshot._tag === "Some") { - assert.equal(snapshot.value.page, undefined); - assert.equal(snapshot.value.thread.messages.length, 9); - assert.equal(snapshot.value.thread.activities.length, 6); - assert.equal(snapshot.value.snapshotSequence, 42); - } - }), - ); - - it.effect("windows to the last N user-anchored turns with subagent turns riding along", () => - Effect.gen(function* () { - yield* seedFanOutThread(); - const snapshotQuery = yield* ProjectionSnapshotQuery; - - // turnLimit 2 walks back: turn-5 (user), turn-4 (user) -> window is - // rows 4..5. Subagent turns 2-3 are older than the 2nd user turn and - // stay out; the straggler message and turnless activity (T03.5/T03.6, - // after turn-4's anchor) ride along. - const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 }); - assert.equal(snapshot._tag, "Some"); - if (snapshot._tag === "Some") { - assert.deepEqual(messageIds(snapshot.value), [ - "turn-4-reply", - "turn-5-reply", - "user-msg-4", - "user-msg-5", - "user-msg-straggler", - ]); - assert.deepEqual(activityIds(snapshot.value), [ - "turn-4-activity", - "turn-5-activity", - "turnless-activity", - ]); - assert.equal(snapshot.value.page?.hasMore, true); - assert.notEqual(snapshot.value.page?.beforeCursor, null); - assert.equal(snapshot.value.page?.snapshotSequence, 42); - } - }), - ); - - it.effect("subagent turns between user turns ride along inside the window", () => - Effect.gen(function* () { - yield* seedFanOutThread(); - const snapshotQuery = yield* ProjectionSnapshotQuery; - - // turnLimit 3 reaches user turn-1, dragging subagent turns 2-3 along: - // the full thread, so no further pages. - const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 3 }); - assert.equal(snapshot._tag, "Some"); - if (snapshot._tag === "Some") { - assert.equal(snapshot.value.thread.messages.length, 9); - assert.equal(snapshot.value.thread.activities.length, 6); - assert.equal(snapshot.value.page?.hasMore, false); - assert.equal(snapshot.value.page?.beforeCursor, null); - } - }), - ); - - it.effect("cursors survive a projection rewrite that reassigns turn row ids", () => - Effect.gen(function* () { - // The revert projector (and any projection rebuild) deletes and - // re-upserts projection_turns, assigning fresh autoincrement row ids. - // The keyset cursor is derived from event content, so a page cursor - // minted before the rewrite must keep working after it. - yield* seedFanOutThread(); - const sql = yield* SqlClient.SqlClient; - const snapshotQuery = yield* ProjectionSnapshotQuery; - - const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 }); - assert.equal(firstPage._tag, "Some"); - if (firstPage._tag !== "Some") return; - const cursor = firstPage.value.page?.beforeCursor; - assert.notEqual(cursor, null); - if (cursor === null || cursor === undefined) return; - - // Simulate the rewrite: delete and re-insert every turn row with the - // same content, which reassigns all row ids. - const turnRows = yield* sql` - SELECT thread_id, turn_id, pending_message_id, state, requested_at, started_at, - completed_at, checkpoint_files_json - FROM projection_turns WHERE thread_id = 'thread-w' ORDER BY row_id - `; - yield* sql`DELETE FROM projection_turns WHERE thread_id = 'thread-w'`; - for (const row of turnRows) { - yield* sql` - INSERT INTO projection_turns ( - thread_id, turn_id, pending_message_id, state, requested_at, started_at, - completed_at, checkpoint_files_json - ) - VALUES (${row.thread_id as string}, ${row.turn_id as string}, - ${row.pending_message_id as string | null}, ${row.state as string}, - ${row.requested_at as string}, ${row.started_at as string}, - ${row.completed_at as string}, ${row.checkpoint_files_json as string}) - `; - } - - const olderPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { - turnLimit: 1, - beforeCursor: cursor, - }); - assert.equal(olderPage._tag, "Some"); - if (olderPage._tag === "Some") { - // Identical older slice to what the pre-rewrite cursor would return. - assert.deepEqual(messageIds(olderPage.value), [ - "turn-1-reply", - "turn-2-reply", - "turn-3-reply", - "user-msg-1", - ]); - assert.equal(olderPage.value.page?.hasMore, false); - } - }), - ); - - it.effect("beforeCursor returns the disjoint adjacent older slice", () => - Effect.gen(function* () { - yield* seedFanOutThread(); - const snapshotQuery = yield* ProjectionSnapshotQuery; - - const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 }); - assert.equal(firstPage._tag, "Some"); - if (firstPage._tag !== "Some") return; - const cursor = firstPage.value.page?.beforeCursor; - assert.notEqual(cursor, null); - assert.notEqual(cursor, undefined); - if (cursor === null || cursor === undefined) return; - - // Older page: user turn-1 plus subagent turns 2-3 riding along. Disjoint - // from the first page: no turn-4/5 rows, no straggler. - const olderPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { - turnLimit: 1, - beforeCursor: cursor, - }); - assert.equal(olderPage._tag, "Some"); - if (olderPage._tag === "Some") { - assert.deepEqual(messageIds(olderPage.value), [ - "turn-1-reply", - "turn-2-reply", - "turn-3-reply", - "user-msg-1", - ]); - assert.deepEqual(activityIds(olderPage.value), [ - "turn-1-activity", - "turn-2-activity", - "turn-3-activity", - ]); - assert.equal(olderPage.value.page?.hasMore, false); - assert.equal(olderPage.value.page?.beforeCursor, null); - } - }), - ); - - it.effect("a cursor for a different thread degrades to the first page", () => - Effect.gen(function* () { - yield* seedFanOutThread(); - const snapshotQuery = yield* ProjectionSnapshotQuery; - - const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 }); - assert.equal(firstPage._tag, "Some"); - if (firstPage._tag !== "Some") return; - - const foreign = encodeThreadDetailPageCursor({ - threadId: ThreadId.make("thread-other"), - beforeAnchorAt: "2026-03-01T00:01:00.000Z", - beforeTurnId: "turn-2", - }); - const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { - turnLimit: 2, - beforeCursor: foreign, - }); - assert.equal(snapshot._tag, "Some"); - if (snapshot._tag === "Some") { - assert.deepEqual(messageIds(snapshot.value), messageIds(firstPage.value)); - } - }), - ); - - it.effect("a malformed cursor degrades to the first page instead of failing", () => - Effect.gen(function* () { - yield* seedFanOutThread(); - const snapshotQuery = yield* ProjectionSnapshotQuery; - - const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { - turnLimit: 2, - beforeCursor: "not-a-cursor", - }); - assert.equal(snapshot._tag, "Some"); - if (snapshot._tag === "Some") { - assert.equal(snapshot.value.page?.hasMore, true); - assert.equal(snapshot.value.thread.messages.length, 5); - } - }), - ); - - it.effect("windows never split below the raw-turn ceiling boundary contiguously", () => - Effect.gen(function* () { - yield* seedFanOutThread(); - const snapshotQuery = yield* ProjectionSnapshotQuery; - - // Page repeatedly with turnLimit 1 and assert the union of all pages is - // exactly the full thread with no duplicates (disjointness + coverage). - const seenMessages: string[] = []; - const seenActivities: string[] = []; - let cursor: string | undefined; - for (let page = 0; page < 10; page += 1) { - const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { - turnLimit: 1, - ...(cursor !== undefined ? { beforeCursor: cursor } : {}), - }); - assert.equal(snapshot._tag, "Some"); - if (snapshot._tag !== "Some") return; - seenMessages.push(...snapshot.value.thread.messages.map((message) => message.id)); - seenActivities.push(...snapshot.value.thread.activities.map((activity) => activity.id)); - const next = snapshot.value.page?.beforeCursor; - if (next === null || next === undefined) break; - cursor = next; - } - assert.equal(new Set(seenMessages).size, seenMessages.length); - assert.equal(new Set(seenActivities).size, seenActivities.length); - assert.equal(seenMessages.length, 9); - assert.equal(seenActivities.length, 6); - }), - ); - - it.effect("a thread with no turns returns its content unwindowed on the first page", () => - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const snapshotQuery = yield* ProjectionSnapshotQuery; - - yield* sql`DELETE FROM projection_projects`; - yield* sql`DELETE FROM projection_threads`; - yield* sql`DELETE FROM projection_turns`; - yield* sql`DELETE FROM projection_thread_messages`; - yield* sql`DELETE FROM projection_thread_activities`; - yield* sql`DELETE FROM projection_state`; - - yield* sql` - INSERT INTO projection_projects ( - project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at - ) - VALUES ('project-e', 'Empty', '/tmp/project-e', '[]', - '2026-03-02T00:00:00.000Z', '2026-03-02T00:00:00.000Z', NULL) - `; - yield* sql` - INSERT INTO projection_threads ( - thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode, - pending_approval_count, pending_user_input_count, has_actionable_proposed_plan, - created_at, updated_at, deleted_at - ) - VALUES ('thread-e', 'project-e', 'Turnless thread', - '{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default', - 0, 0, 0, '2026-03-02T00:00:00.000Z', '2026-03-02T00:00:00.000Z', NULL) - `; - yield* sql` - INSERT INTO projection_thread_messages ( - message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at - ) - VALUES ('pre-turn-msg', 'thread-e', NULL, 'user', 'first prompt', 0, - '2026-03-02T00:00:01.000Z', '2026-03-02T00:00:01.000Z') - `; - for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) { - yield* sql` - INSERT INTO projection_state (projector, last_applied_sequence, updated_at) - VALUES (${projector}, 7, '2026-03-02T00:00:01.000Z') - `; - } - - const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(ThreadId.make("thread-e"), { - turnLimit: 5, - }); - assert.equal(snapshot._tag, "Some"); - if (snapshot._tag === "Some") { - assert.deepEqual(messageIds(snapshot.value), ["pre-turn-msg"]); - assert.equal(snapshot.value.page?.hasMore, false); - assert.equal(snapshot.value.page?.beforeCursor, null); - } - }), - ); -}); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts deleted file mode 100644 index 258aa010e3..0000000000 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ /dev/null @@ -1,3562 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; - -import { - OrchestrationReadModel, - ProviderDriverKind, - ProviderRuntimeEvent, - ProviderSession, - ProviderInstanceId, -} from "@t3tools/contracts"; -import { - ApprovalRequestId, - CommandId, - DEFAULT_PROVIDER_INTERACTION_MODE, - EventId, - MessageId, - type OrchestrationCommand, - ProjectId, - ProviderItemId, - type ServerSettings, - ThreadId, - TurnId, -} from "@t3tools/contracts"; -import * as Clock from "effect/Clock"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Layer from "effect/Layer"; -import * as ManagedRuntime from "effect/ManagedRuntime"; -import * as PubSub from "effect/PubSub"; -import * as Scope from "effect/Scope"; -import * as Stream from "effect/Stream"; -import { it as effectIt } from "@effect/vitest"; -import { afterEach, describe, expect, it } from "vite-plus/test"; - -import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; -import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts"; -import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; -import { - ProviderService, - type ProviderServiceShape, -} from "../../provider/Services/ProviderService.ts"; -import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts"; -import { OrchestrationEngineLive } from "./OrchestrationEngine.ts"; -import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts"; -import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts"; -import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts"; -import * as ThreadPlanProgress from "../ThreadPlanProgress.ts"; -import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts"; -import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; -import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts"; -import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; -import { ServerConfig } from "../../config.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; -import * as NodeServices from "@effect/platform-node/NodeServices"; - -function makeTestServerSettingsLayer(overrides: Partial = {}) { - return ServerSettingsService.layerTest(overrides); -} - -const asProjectId = (value: string): ProjectId => ProjectId.make(value); -const asItemId = (value: string): ProviderItemId => ProviderItemId.make(value); -const asEventId = (value: string): EventId => EventId.make(value); -const asMessageId = (value: string): MessageId => MessageId.make(value); -const asThreadId = (value: string): ThreadId => ThreadId.make(value); -const asTurnId = (value: string): TurnId => TurnId.make(value); - -type LegacyProviderRuntimeEvent = { - readonly type: string; - readonly eventId: EventId; - readonly provider: ProviderRuntimeEvent["provider"]; - readonly createdAt: string; - readonly threadId: ThreadId; - readonly turnId?: string | undefined; - readonly itemId?: string | undefined; - readonly requestId?: string | undefined; - readonly payload?: unknown | undefined; - readonly [key: string]: unknown; -}; - -type LegacyTurnCompletedEvent = LegacyProviderRuntimeEvent & { - readonly type: "turn.completed"; - readonly payload?: undefined; - readonly status: "completed" | "failed" | "interrupted" | "cancelled"; - readonly errorMessage?: string | undefined; -}; - -function isLegacyTurnCompletedEvent( - event: LegacyProviderRuntimeEvent, -): event is LegacyTurnCompletedEvent { - return ( - event.type === "turn.completed" && - event.payload === undefined && - typeof event.status === "string" - ); -} - -function createProviderServiceHarness() { - const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); - const runtimeSessions: ProviderSession[] = []; - - const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; - const service: ProviderServiceShape = { - startSession: () => unsupported(), - sendTurn: () => unsupported(), - interruptTurn: () => unsupported(), - respondToRequest: () => unsupported(), - respondToUserInput: () => unsupported(), - stopSession: () => unsupported(), - listSessions: () => Effect.succeed([...runtimeSessions]), - getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), - getInstanceInfo: (instanceId) => { - const driverKind = ProviderDriverKind.make(String(instanceId)); - return Effect.succeed({ - instanceId, - driverKind, - displayName: undefined, - enabled: true, - continuationIdentity: { - driverKind, - continuationKey: `${driverKind}:instance:${instanceId}`, - }, - }); - }, - rollbackConversation: () => unsupported(), - get streamEvents() { - return Stream.fromPubSub(runtimeEventPubSub); - }, - }; - - const setSession = (session: ProviderSession): void => { - const existingIndex = runtimeSessions.findIndex((entry) => entry.threadId === session.threadId); - if (existingIndex >= 0) { - runtimeSessions[existingIndex] = session; - return; - } - runtimeSessions.push(session); - }; - - const normalizeLegacyEvent = (event: LegacyProviderRuntimeEvent): ProviderRuntimeEvent => { - if (isLegacyTurnCompletedEvent(event)) { - const normalized: Extract = { - ...(event as Omit, "payload">), - payload: { - state: event.status, - ...(typeof event.errorMessage === "string" ? { errorMessage: event.errorMessage } : {}), - }, - }; - return normalized; - } - - return event as ProviderRuntimeEvent; - }; - - const emit = (event: LegacyProviderRuntimeEvent): void => { - Effect.runSync(PubSub.publish(runtimeEventPubSub, normalizeLegacyEvent(event))); - }; - - return { - service, - emit, - setSession, - }; -} - -type ProviderRuntimeTestReadModel = OrchestrationReadModel; -type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number]; -type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number]; -type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number]; -type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number]; -type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number]; - -async function waitForThread( - readModel: () => Promise, - predicate: (thread: ProviderRuntimeTestThread) => boolean, - timeoutMs = 2000, - threadId: ThreadId = asThreadId("thread-1"), -) { - const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs; - const poll = async (): Promise => { - const snapshot = await readModel(); - const thread = snapshot.threads.find((entry) => entry.id === threadId); - if (thread && predicate(thread)) { - return thread; - } - if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) { - throw new Error("Timed out waiting for thread state"); - } - await Effect.runPromise(Effect.yieldNow); - return poll(); - }; - return poll(); -} - -describe("ProviderRuntimeIngestion", () => { - let runtime: ManagedRuntime.ManagedRuntime< - OrchestrationEngineService | ProviderRuntimeIngestionService | ProjectionSnapshotQuery, - unknown - > | null = null; - let scope: Scope.Closeable | null = null; - const tempDirs: string[] = []; - - function makeTempDir(prefix: string): string { - const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), prefix)); - tempDirs.push(dir); - return dir; - } - - afterEach(async () => { - if (scope) { - await Effect.runPromise(Scope.close(scope, Exit.void)); - } - scope = null; - if (runtime) { - await runtime.dispose(); - } - runtime = null; - for (const dir of tempDirs.splice(0)) { - NodeFS.rmSync(dir, { recursive: true, force: true }); - } - }); - - async function createHarness(options?: { serverSettings?: Partial }) { - const workspaceRoot = makeTempDir("t3-provider-project-"); - NodeFS.mkdirSync(NodePath.join(workspaceRoot, ".git")); - const provider = createProviderServiceHarness(); - const orchestrationLayer = OrchestrationEngineLive.pipe( - Layer.provide(OrchestrationProjectionSnapshotQueryLive), - Layer.provide(OrchestrationProjectionPipelineLive), - Layer.provide(OrchestrationEventStoreLive), - Layer.provide(OrchestrationCommandReceiptRepositoryLive), - Layer.provide(RepositoryIdentityResolver.layer), - Layer.provide(SqlitePersistenceMemory), - ); - const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe( - Layer.provide(RepositoryIdentityResolver.layer), - Layer.provide(SqlitePersistenceMemory), - ); - const layer = ProviderRuntimeIngestionLive.pipe( - Layer.provideMerge(orchestrationLayer), - Layer.provideMerge(projectionSnapshotLayer), - // Single shared liveness instance across ingestion (writer), the - // engine, and the snapshot query (reader). - Layer.provideMerge(ThreadBackgroundLiveness.layer), - Layer.provideMerge(ThreadPlanProgress.layer), - Layer.provideMerge(SqlitePersistenceMemory), - Layer.provideMerge(Layer.succeed(ProviderService, provider.service)), - Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)), - Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())), - Layer.provideMerge(NodeServices.layer), - ); - runtime = ManagedRuntime.make(layer); - const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); - const snapshotQuery = await runtime.runPromise(Effect.service(ProjectionSnapshotQuery)); - const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService)); - scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope))); - const drain = () => Effect.runPromise(ingestion.drain); - const dispatch = (command: OrchestrationCommand) => Effect.runPromise(engine.dispatch(command)); - - const createdAt = "2026-01-01T00:00:00.000Z"; - await dispatch({ - type: "project.create", - commandId: CommandId.make("cmd-provider-project-create"), - projectId: asProjectId("project-1"), - title: "Provider Project", - workspaceRoot, - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - createdAt, - }); - await dispatch({ - type: "thread.create", - commandId: CommandId.make("cmd-thread-create"), - threadId: ThreadId.make("thread-1"), - projectId: asProjectId("project-1"), - title: "Thread", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt, - }); - await dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-seed"), - threadId: ThreadId.make("thread-1"), - session: { - threadId: ThreadId.make("thread-1"), - status: "ready", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: null, - updatedAt: createdAt, - lastError: null, - }, - createdAt, - }); - provider.setSession({ - provider: ProviderDriverKind.make("codex"), - status: "ready", - runtimeMode: "approval-required", - threadId: ThreadId.make("thread-1"), - createdAt, - updatedAt: createdAt, - }); - - return { - engine, - dispatch, - readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()), - emit: provider.emit, - setProviderSession: provider.setSession, - drain, - }; - } - - it("maps turn started/completed events into thread session updates", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started"), - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: now, - turnId: asTurnId("turn-1"), - }); - - await waitForThread( - harness.readModel, - (thread) => thread.session?.status === "running" && thread.session?.activeTurnId === "turn-1", - ); - - harness.emit({ - type: "turn.completed", - eventId: asEventId("evt-turn-completed"), - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - turnId: asTurnId("turn-1"), - payload: { - state: "failed", - errorMessage: "turn failed", - }, - }); - - const thread = await waitForThread( - harness.readModel, - (entry) => - entry.session?.status === "error" && - entry.session?.activeTurnId === null && - entry.session?.lastError === "turn failed", - ); - expect(thread.session?.status).toBe("error"); - expect(thread.session?.lastError).toBe("turn failed"); - }); - - it("applies provider session.state.changed transitions directly", async () => { - const harness = await createHarness(); - const waitingAt = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "session.state.changed", - eventId: asEventId("evt-session-state-waiting"), - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: waitingAt, - payload: { - state: "waiting", - reason: "awaiting approval", - }, - }); - - let thread = await waitForThread( - harness.readModel, - (entry) => entry.session?.status === "running" && entry.session?.activeTurnId === null, - ); - expect(thread.session?.status).toBe("running"); - expect(thread.session?.lastError).toBeNull(); - - harness.emit({ - type: "session.state.changed", - eventId: asEventId("evt-session-state-error"), - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - payload: { - state: "error", - reason: "provider crashed", - }, - }); - - thread = await waitForThread( - harness.readModel, - (entry) => - entry.session?.status === "error" && - entry.session?.activeTurnId === null && - entry.session?.lastError === "provider crashed", - ); - expect(thread.session?.status).toBe("error"); - expect(thread.session?.lastError).toBe("provider crashed"); - - harness.emit({ - type: "session.state.changed", - eventId: asEventId("evt-session-state-stopped"), - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - payload: { - state: "stopped", - }, - }); - - thread = await waitForThread( - harness.readModel, - (entry) => - entry.session?.status === "stopped" && - entry.session?.activeTurnId === null && - entry.session?.lastError === "provider crashed", - ); - expect(thread.session?.status).toBe("stopped"); - expect(thread.session?.lastError).toBe("provider crashed"); - - harness.emit({ - type: "session.state.changed", - eventId: asEventId("evt-session-state-ready"), - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:00.000Z", - payload: { - state: "ready", - }, - }); - - thread = await waitForThread( - harness.readModel, - (entry) => - entry.session?.status === "ready" && - entry.session?.activeTurnId === null && - entry.session?.lastError === null, - ); - expect(thread.session?.status).toBe("ready"); - expect(thread.session?.lastError).toBeNull(); - }); - - it("clears active turn when provider session becomes ready", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-session-ready"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-session-ready"), - }); - - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-session-ready", - 10_000, - ); - - harness.emit({ - type: "session.state.changed", - eventId: asEventId("evt-session-state-ready-with-active-turn"), - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-1"), - createdAt: "2026-01-01T00:00:01.000Z", - payload: { - state: "ready", - }, - }); - - const thread = await waitForThread( - harness.readModel, - (entry) => - entry.session?.status === "ready" && - entry.session?.activeTurnId === null && - entry.session?.lastError === null, - 10_000, - ); - expect(thread.session?.status).toBe("ready"); - expect(thread.session?.activeTurnId).toBeNull(); - expect(thread.session?.lastError).toBeNull(); - }); - - effectIt.effect( - "keeps a reconnecting pending turn starting while ready clears stale active state", - () => - Effect.gen(function* () { - const harness = yield* Effect.promise(() => createHarness()); - const threadId = asThreadId("thread-1"); - const staleTurnId = asTurnId("turn-stale-before-reconnect"); - - yield* harness.engine.dispatch({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-turn-start-pending-reconnect"), - threadId, - message: { - messageId: MessageId.make("message-pending-reconnect"), - role: "user", - text: "resume after reconnect", - attachments: [], - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - createdAt: "2026-01-01T00:00:01.000Z", - }); - yield* harness.engine.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-starting-pending-reconnect"), - threadId, - session: { - threadId, - status: "starting", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: staleTurnId, - lastError: null, - updatedAt: "2026-01-01T00:00:01.000Z", - }, - createdAt: "2026-01-01T00:00:01.000Z", - }); - - harness.emit({ - type: "session.state.changed", - eventId: asEventId("evt-session-ready-pending-reconnect"), - provider: ProviderDriverKind.make("codex"), - threadId, - createdAt: "2026-01-01T00:00:02.000Z", - payload: { state: "ready" }, - }); - - let thread = yield* Effect.promise(() => - waitForThread( - harness.readModel, - (entry) => entry.session?.status === "starting" && entry.session.activeTurnId === null, - ), - ); - expect(thread.session?.status).toBe("starting"); - expect(thread.session?.activeTurnId).toBeNull(); - - harness.emit({ - type: "session.started", - eventId: asEventId("evt-session-started-pending-reconnect"), - provider: ProviderDriverKind.make("codex"), - threadId, - createdAt: "2026-01-01T00:00:03.000Z", - }); - yield* Effect.promise(() => harness.drain()); - thread = (yield* Effect.promise(() => harness.readModel())).threads.find( - (entry) => entry.id === threadId, - )!; - expect(thread.session?.status).toBe("starting"); - expect(thread.session?.activeTurnId).toBeNull(); - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-pending-reconnect"), - provider: ProviderDriverKind.make("codex"), - threadId, - turnId: asTurnId("turn-after-reconnect"), - createdAt: "2026-01-01T00:00:04.000Z", - }); - thread = yield* Effect.promise(() => - waitForThread( - harness.readModel, - (entry) => - entry.session?.status === "running" && - entry.session.activeTurnId === asTurnId("turn-after-reconnect"), - ), - ); - expect(thread.session?.status).toBe("running"); - - harness.emit({ - type: "session.started", - eventId: asEventId("evt-session-started-duplicate-midturn"), - provider: ProviderDriverKind.make("codex"), - threadId, - createdAt: "2026-01-01T00:00:05.000Z", - }); - yield* Effect.promise(() => harness.drain()); - thread = (yield* Effect.promise(() => harness.readModel())).threads.find( - (entry) => entry.id === threadId, - )!; - expect(thread.session?.status).toBe("running"); - expect(thread.session?.activeTurnId).toBe(asTurnId("turn-after-reconnect")); - }), - ); - - effectIt.effect("keeps an aborted pending start stopped across duplicate exit events", () => - Effect.gen(function* () { - const harness = yield* Effect.promise(() => createHarness()); - const threadId = asThreadId("thread-1"); - const stoppedAt = "2026-01-01T00:00:02.000Z"; - - yield* harness.engine.dispatch({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-turn-start-before-stop"), - threadId, - message: { - messageId: MessageId.make("message-before-stop"), - role: "user", - text: "stop this startup", - attachments: [], - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - createdAt: "2026-01-01T00:00:01.000Z", - }); - yield* harness.engine.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-starting-before-stop"), - threadId, - session: { - threadId, - status: "starting", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: null, - lastError: null, - updatedAt: "2026-01-01T00:00:01.000Z", - }, - createdAt: "2026-01-01T00:00:01.000Z", - }); - yield* harness.engine.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-stop-pending-start"), - threadId, - session: { - threadId, - status: "stopped", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: null, - lastError: null, - updatedAt: stoppedAt, - }, - createdAt: stoppedAt, - }); - - harness.emit({ - type: "session.exited", - eventId: asEventId("evt-session-exited-after-stop"), - provider: ProviderDriverKind.make("codex"), - threadId, - createdAt: "2026-01-01T00:00:03.000Z", - }); - harness.emit({ - type: "session.exited", - eventId: asEventId("evt-duplicate-session-exited-after-stop"), - provider: ProviderDriverKind.make("codex"), - threadId, - createdAt: "2026-01-01T00:00:04.000Z", - }); - - yield* Effect.promise(() => harness.drain()); - const thread = (yield* Effect.promise(() => harness.readModel())).threads.find( - (entry) => entry.id === threadId, - ); - expect(thread?.session?.status).toBe("stopped"); - expect(thread?.session?.activeTurnId).toBeNull(); - }), - ); - - it("does not clear active turn when session/thread started arrives mid-turn", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-midturn-lifecycle"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-midturn-lifecycle"), - }); - - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-midturn-lifecycle", - 10_000, - ); - - harness.emit({ - type: "thread.started", - eventId: asEventId("evt-thread-started-midturn-lifecycle"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: asThreadId("thread-1"), - }); - harness.emit({ - type: "session.started", - eventId: asEventId("evt-session-started-midturn-lifecycle"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: asThreadId("thread-1"), - }); - - await harness.drain(); - const midReadModel = await harness.readModel(); - const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); - expect(midThread?.session?.status).toBe("running"); - expect(midThread?.session?.activeTurnId).toBe("turn-midturn-lifecycle"); - - harness.emit({ - type: "turn.completed", - eventId: asEventId("evt-turn-completed-midturn-lifecycle"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-midturn-lifecycle"), - status: "completed", - }); - - await waitForThread( - harness.readModel, - (thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null, - 10_000, - ); - }); - - it("accepts claude turn lifecycle when seeded thread id is a synthetic placeholder", async () => { - const harness = await createHarness(); - const seededAt = "2026-01-01T00:00:00.000Z"; - - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-seed-claude-placeholder"), - threadId: ThreadId.make("thread-1"), - session: { - threadId: ThreadId.make("thread-1"), - status: "ready", - providerName: "claudeAgent", - runtimeMode: "approval-required", - activeTurnId: null, - updatedAt: seededAt, - lastError: null, - }, - createdAt: seededAt, - }), - ); - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-claude-placeholder"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-claude-placeholder"), - }); - - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-claude-placeholder", - ); - - harness.emit({ - type: "turn.completed", - eventId: asEventId("evt-turn-completed-claude-placeholder"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-claude-placeholder"), - status: "completed", - }); - - await waitForThread( - harness.readModel, - (thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null, - ); - }); - - it("ignores auxiliary turn completions from a different provider thread", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-primary"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-primary"), - }); - - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && thread.session?.activeTurnId === "turn-primary", - ); - - harness.emit({ - type: "turn.completed", - eventId: asEventId("evt-turn-completed-aux"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-aux"), - status: "completed", - }); - - await harness.drain(); - const midReadModel = await harness.readModel(); - const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); - expect(midThread?.session?.status).toBe("running"); - expect(midThread?.session?.activeTurnId).toBe("turn-primary"); - - harness.emit({ - type: "turn.completed", - eventId: asEventId("evt-turn-completed-primary"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-primary"), - status: "completed", - }); - - await waitForThread( - harness.readModel, - (thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null, - ); - }); - - it("rejects an untargeted turn.completed when no turn is active", async () => { - const harness = await createHarness(); - const seededAt = "2026-01-01T00:00:00.000Z"; - - // A turn start is pending: the session reads "starting" with no active - // turn tracked yet. This is the window the Claude resume handshake's - // phantom (turn.completed with no turnId) used to slip through, stomping - // "starting" back to "ready" for a turn that never existed. - await harness.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-seed-untargeted-completion"), - threadId: ThreadId.make("thread-1"), - session: { - threadId: ThreadId.make("thread-1"), - status: "starting", - providerName: "claudeAgent", - runtimeMode: "approval-required", - activeTurnId: null, - updatedAt: seededAt, - lastError: null, - }, - createdAt: seededAt, - }); - - harness.emit({ - type: "turn.completed", - eventId: asEventId("evt-turn-completed-untargeted"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: seededAt, - threadId: asThreadId("thread-1"), - status: "completed", - }); - - await harness.drain(); - const readModel = await harness.readModel(); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); - expect(thread?.session?.status).toBe("starting"); - expect(thread?.session?.activeTurnId).toBeNull(); - }); - - it("accepts a targeted turn.completed when no turn is active", async () => { - const harness = await createHarness(); - const seededAt = "2026-01-01T00:00:00.000Z"; - - // A completion that names its turn still lands even when no active turn - // is tracked (e.g. its turn.started was lost). Only untargeted - // completions are rejected. - await harness.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-seed-targeted-completion"), - threadId: ThreadId.make("thread-1"), - session: { - threadId: ThreadId.make("thread-1"), - status: "starting", - providerName: "claudeAgent", - runtimeMode: "approval-required", - activeTurnId: null, - updatedAt: seededAt, - lastError: null, - }, - createdAt: seededAt, - }); - - harness.emit({ - type: "turn.completed", - eventId: asEventId("evt-turn-completed-targeted-late"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: seededAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-late"), - status: "completed", - }); - - await waitForThread(harness.readModel, (thread) => thread.session?.status === "ready"); - }); - - it("ignores non-active turn completion when runtime omits thread id", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-guarded"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-guarded-main"), - }); - - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-guarded-main", - ); - - harness.emit({ - type: "turn.completed", - eventId: asEventId("evt-turn-completed-guarded-other"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-guarded-other"), - status: "completed", - }); - - await harness.drain(); - const midReadModel = await harness.readModel(); - const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); - expect(midThread?.session?.status).toBe("running"); - expect(midThread?.session?.activeTurnId).toBe("turn-guarded-main"); - - harness.emit({ - type: "turn.completed", - eventId: asEventId("evt-turn-completed-guarded-main"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-guarded-main"), - status: "completed", - }); - - await waitForThread( - harness.readModel, - (thread) => thread.session?.status === "ready" && thread.session?.activeTurnId === null, - ); - }); - - it("maps canonical content delta/item completed into finalized assistant messages", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-1"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-2"), - itemId: asItemId("item-1"), - payload: { - streamKind: "assistant_text", - delta: "hello", - }, - }); - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-2"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-2"), - itemId: asItemId("item-1"), - payload: { - streamKind: "assistant_text", - delta: " world", - }, - }); - harness.emit({ - type: "item.completed", - eventId: asEventId("evt-message-completed"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-2"), - itemId: asItemId("item-1"), - payload: { - itemType: "assistant_message", - status: "completed", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-1" && !message.streaming, - ), - ); - const message = thread.messages.find( - (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-1", - ); - expect(message?.text).toBe("hello world"); - expect(message?.streaming).toBe(false); - }); - - it("uses assistant item completion detail when no assistant deltas were streamed", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "item.completed", - eventId: asEventId("evt-assistant-item-completed-no-delta"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-no-delta"), - itemId: asItemId("item-no-delta"), - payload: { - itemType: "assistant_message", - status: "completed", - detail: "assistant-only final text", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-no-delta" && !message.streaming, - ), - ); - const message = thread.messages.find( - (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-no-delta", - ); - expect(message?.text).toBe("assistant-only final text"); - expect(message?.streaming).toBe(false); - }); - - it("preserves completed tool metadata on projected tool activities", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "item.completed", - eventId: asEventId("evt-tool-completed-with-data"), - provider: ProviderDriverKind.make("cursor"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-tool-completed"), - itemId: asItemId("item-tool-completed"), - payload: { - itemType: "dynamic_tool_call", - status: "completed", - title: "Read file", - data: { - toolCallId: "tool-read-1", - kind: "read", - rawOutput: { - content: 'import * as Effect from "effect/Effect"\n', - }, - }, - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-tool-completed-with-data", - ), - ); - const activity = thread.activities.find( - (entry: ProviderRuntimeTestActivity) => entry.id === "evt-tool-completed-with-data", - ); - const payload = - activity?.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : undefined; - const data = - payload?.data && typeof payload.data === "object" - ? (payload.data as Record) - : undefined; - const rawOutput = - data?.rawOutput && typeof data.rawOutput === "object" - ? (data.rawOutput as Record) - : undefined; - - expect(activity?.kind).toBe("tool.completed"); - expect(activity?.summary).toBe("Read file"); - expect(payload?.itemType).toBe("dynamic_tool_call"); - expect(payload?.detail).toBeUndefined(); - expect(data?.toolCallId).toBe("tool-read-1"); - expect(data?.kind).toBe("read"); - expect(rawOutput?.content).toBe('import * as Effect from "effect/Effect"\n'); - }); - - it("normalizes command execution activities to ran-command summaries", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "item.completed", - eventId: asEventId("evt-command-completed"), - provider: ProviderDriverKind.make("cursor"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-command-completed"), - itemId: asItemId("item-command-completed"), - payload: { - itemType: "command_execution", - status: "completed", - title: "Ran command", - detail: "bun run lint", - data: { - toolCallId: "tool-command-1", - kind: "execute", - command: "bun run lint", - }, - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-command-completed", - ), - ); - const activity = thread.activities.find( - (entry: ProviderRuntimeTestActivity) => entry.id === "evt-command-completed", - ); - const payload = - activity?.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : undefined; - - expect(activity?.summary).toBe("Ran command"); - expect(payload?.detail).toBe("bun run lint"); - }); - - it("uses structured read-file paths when available", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "item.completed", - eventId: asEventId("evt-read-path-completed"), - provider: ProviderDriverKind.make("cursor"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-read-path"), - itemId: asItemId("item-read-path"), - payload: { - itemType: "dynamic_tool_call", - status: "completed", - title: "Read file", - detail: "/tmp/app.ts", - data: { - toolCallId: "tool-read-path-1", - kind: "read", - locations: [{ path: "/tmp/app.ts" }], - }, - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-read-path-completed", - ), - ); - const activity = thread.activities.find( - (entry: ProviderRuntimeTestActivity) => entry.id === "evt-read-path-completed", - ); - const payload = - activity?.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : undefined; - - expect(activity?.summary).toBe("Read file"); - expect(payload?.detail).toBe("/tmp/app.ts"); - }); - - it("projects completed plan items into first-class proposed plans", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.proposed.completed", - eventId: asEventId("evt-plan-item-completed"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-plan-final"), - payload: { - planMarkdown: "## Ship plan\n\n- wire projection\n- render follow-up", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.proposedPlans.some( - (proposedPlan: ProviderRuntimeTestProposedPlan) => - proposedPlan.id === "plan:thread-1:turn:turn-plan-final", - ), - ); - const proposedPlan = thread.proposedPlans.find( - (entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-plan-final", - ); - expect(proposedPlan?.planMarkdown).toBe( - "## Ship plan\n\n- wire projection\n- render follow-up", - ); - }); - - it("marks the source proposed plan implemented only after the target turn starts", async () => { - const harness = await createHarness(); - const sourceThreadId = asThreadId("thread-plan"); - const targetThreadId = asThreadId("thread-implement"); - const sourceTurnId = asTurnId("turn-plan-source"); - const targetTurnId = asTurnId("turn-plan-implement"); - const createdAt = "2026-01-01T00:00:00.000Z"; - - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.create", - commandId: CommandId.make("cmd-thread-create-plan-source"), - threadId: sourceThreadId, - projectId: asProjectId("project-1"), - title: "Plan Source", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: "plan", - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt, - }), - ); - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-set-plan-source"), - threadId: sourceThreadId, - session: { - threadId: sourceThreadId, - status: "ready", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: null, - updatedAt: createdAt, - lastError: null, - }, - createdAt, - }), - ); - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.create", - commandId: CommandId.make("cmd-thread-create-plan-target"), - threadId: targetThreadId, - projectId: asProjectId("project-1"), - title: "Plan Target", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt, - }), - ); - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-set-plan-target"), - threadId: targetThreadId, - session: { - threadId: targetThreadId, - status: "ready", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: null, - updatedAt: createdAt, - lastError: null, - }, - createdAt, - }), - ); - harness.setProviderSession({ - provider: ProviderDriverKind.make("codex"), - status: "ready", - runtimeMode: "approval-required", - threadId: targetThreadId, - createdAt, - updatedAt: createdAt, - activeTurnId: targetTurnId, - }); - - harness.emit({ - type: "turn.proposed.completed", - eventId: asEventId("evt-plan-source-completed"), - provider: ProviderDriverKind.make("codex"), - createdAt, - threadId: sourceThreadId, - turnId: sourceTurnId, - payload: { - planMarkdown: "# Source plan", - }, - }); - - const sourceThreadWithPlan = await waitForThread( - harness.readModel, - (thread) => - thread.proposedPlans.some( - (proposedPlan: ProviderRuntimeTestProposedPlan) => - proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" && - proposedPlan.implementedAt === null, - ), - 2_000, - sourceThreadId, - ); - const sourcePlan = sourceThreadWithPlan.proposedPlans.find( - (entry: ProviderRuntimeTestProposedPlan) => - entry.id === "plan:thread-plan:turn:turn-plan-source", - ); - expect(sourcePlan).toBeDefined(); - if (!sourcePlan) { - throw new Error("Expected source plan to exist."); - } - - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-turn-start-plan-target"), - threadId: targetThreadId, - message: { - messageId: asMessageId("msg-plan-target"), - role: "user", - text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan", - attachments: [], - }, - sourceProposedPlan: { - threadId: sourceThreadId, - planId: sourcePlan.id, - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - createdAt: "2026-01-01T00:00:00.000Z", - }), - ); - - const sourceThreadBeforeStart = await waitForThread( - harness.readModel, - (thread) => - thread.proposedPlans.some( - (proposedPlan: ProviderRuntimeTestProposedPlan) => - proposedPlan.id === sourcePlan.id && proposedPlan.implementedAt === null, - ), - 2_000, - sourceThreadId, - ); - expect( - sourceThreadBeforeStart.proposedPlans.find((entry) => entry.id === sourcePlan.id), - ).toMatchObject({ - implementedAt: null, - implementationThreadId: null, - }); - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-plan-target-started"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: targetThreadId, - turnId: targetTurnId, - }); - - const sourceThreadAfterStart = await waitForThread( - harness.readModel, - (thread) => - thread.proposedPlans.some( - (proposedPlan: ProviderRuntimeTestProposedPlan) => - proposedPlan.id === sourcePlan.id && - proposedPlan.implementedAt !== null && - proposedPlan.implementationThreadId === targetThreadId, - ), - 2_000, - sourceThreadId, - ); - expect( - sourceThreadAfterStart.proposedPlans.find((entry) => entry.id === sourcePlan.id), - ).toMatchObject({ - implementationThreadId: "thread-implement", - }); - }); - - it("does not mark the source proposed plan implemented for a rejected turn.started event", async () => { - const harness = await createHarness(); - const sourceThreadId = asThreadId("thread-plan"); - const targetThreadId = asThreadId("thread-1"); - const sourceTurnId = asTurnId("turn-plan-source"); - const activeTurnId = asTurnId("turn-already-running"); - const staleTurnId = asTurnId("turn-stale-start"); - const createdAt = "2026-01-01T00:00:00.000Z"; - - await Effect.runPromise( - Effect.andThen( - harness.engine.dispatch({ - type: "thread.create", - commandId: CommandId.make("cmd-thread-create-plan-source-guarded"), - threadId: sourceThreadId, - projectId: asProjectId("project-1"), - title: "Plan Source", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: "plan", - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt, - }), - harness.engine.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-set-plan-source-guarded"), - threadId: sourceThreadId, - session: { - threadId: sourceThreadId, - status: "ready", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: null, - updatedAt: createdAt, - lastError: null, - }, - createdAt, - }), - ), - ); - harness.setProviderSession({ - provider: ProviderDriverKind.make("codex"), - status: "running", - runtimeMode: "approval-required", - threadId: targetThreadId, - createdAt, - updatedAt: createdAt, - activeTurnId, - }); - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-already-running"), - provider: ProviderDriverKind.make("codex"), - createdAt, - threadId: targetThreadId, - turnId: activeTurnId, - }); - - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && thread.session?.activeTurnId === activeTurnId, - 2_000, - targetThreadId, - ); - - harness.emit({ - type: "turn.proposed.completed", - eventId: asEventId("evt-plan-source-completed-guarded"), - provider: ProviderDriverKind.make("codex"), - createdAt, - threadId: sourceThreadId, - turnId: sourceTurnId, - payload: { - planMarkdown: "# Source plan", - }, - }); - - const sourceThreadWithPlan = await waitForThread( - harness.readModel, - (thread) => - thread.proposedPlans.some( - (proposedPlan: ProviderRuntimeTestProposedPlan) => - proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" && - proposedPlan.implementedAt === null, - ), - 2_000, - sourceThreadId, - ); - const sourcePlan = sourceThreadWithPlan.proposedPlans.find( - (entry: ProviderRuntimeTestProposedPlan) => - entry.id === "plan:thread-plan:turn:turn-plan-source", - ); - expect(sourcePlan).toBeDefined(); - if (!sourcePlan) { - throw new Error("Expected source plan to exist."); - } - - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-turn-start-plan-target-guarded"), - threadId: targetThreadId, - message: { - messageId: asMessageId("msg-plan-target-guarded"), - role: "user", - text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan", - attachments: [], - }, - sourceProposedPlan: { - threadId: sourceThreadId, - planId: sourcePlan.id, - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - createdAt: "2026-01-01T00:00:00.000Z", - }), - ); - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-stale-plan-implementation"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: targetThreadId, - turnId: staleTurnId, - }); - - await harness.drain(); - - const readModel = await harness.readModel(); - const sourceThreadAfterRejectedStart = readModel.threads.find( - (entry) => entry.id === sourceThreadId, - ); - expect( - sourceThreadAfterRejectedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id), - ).toMatchObject({ - implementedAt: null, - implementationThreadId: null, - }); - - const targetThreadAfterRejectedStart = readModel.threads.find( - (entry) => entry.id === targetThreadId, - ); - expect(targetThreadAfterRejectedStart?.session?.status).toBe("running"); - expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId); - }); - - it("accepts a conflicting turn.started for a pending turn start when the provider expects that turn", async () => { - // Steering a running turn: the server requests a new turn while the old - // one is still active, and providers like opencode open the new turn - // without ever completing the superseded one. The new turn.started must - // replace the active turn instead of being rejected as stale. - const harness = await createHarness(); - const threadId = asThreadId("thread-1"); - const oldTurnId = asTurnId("turn-steered-over"); - const newTurnId = asTurnId("turn-from-steer"); - const createdAt = "2026-01-01T00:00:00.000Z"; - - harness.setProviderSession({ - provider: ProviderDriverKind.make("codex"), - status: "running", - runtimeMode: "approval-required", - threadId, - createdAt, - updatedAt: createdAt, - activeTurnId: oldTurnId, - }); - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-steered-over"), - provider: ProviderDriverKind.make("codex"), - createdAt, - threadId, - turnId: oldTurnId, - }); - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && thread.session?.activeTurnId === oldTurnId, - 2_000, - threadId, - ); - - // The steer: a user-requested turn start while the old turn still runs. - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-turn-start-steer"), - threadId, - message: { - messageId: asMessageId("msg-steer"), - role: "user", - text: "actually, do 15 instead", - attachments: [], - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - createdAt, - }), - ); - - // The provider session tracks the new turn before emitting turn.started - // (sendTurn updates the session first). - harness.setProviderSession({ - provider: ProviderDriverKind.make("codex"), - status: "running", - runtimeMode: "approval-required", - threadId, - createdAt, - updatedAt: createdAt, - activeTurnId: newTurnId, - }); - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-from-steer"), - provider: ProviderDriverKind.make("codex"), - createdAt, - threadId, - turnId: newTurnId, - }); - - const threadAfterSteer = await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && thread.session?.activeTurnId === newTurnId, - 2_000, - threadId, - ); - expect(threadAfterSteer.session?.activeTurnId).toBe(newTurnId); - expect(threadAfterSteer.latestTurn?.turnId).toBe(newTurnId); - expect(threadAfterSteer.latestTurn?.state).toBe("running"); - }); - - it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => { - const harness = await createHarness(); - const sourceThreadId = asThreadId("thread-plan"); - const targetThreadId = asThreadId("thread-implement"); - const sourceTurnId = asTurnId("turn-plan-source"); - const expectedTurnId = asTurnId("turn-plan-implement"); - const replayedTurnId = asTurnId("turn-replayed"); - const createdAt = "2026-01-01T00:00:00.000Z"; - - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.create", - commandId: CommandId.make("cmd-thread-create-plan-source-unrelated"), - threadId: sourceThreadId, - projectId: asProjectId("project-1"), - title: "Plan Source", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: "plan", - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt, - }), - ); - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-set-plan-source-unrelated"), - threadId: sourceThreadId, - session: { - threadId: sourceThreadId, - status: "ready", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: null, - updatedAt: createdAt, - lastError: null, - }, - createdAt, - }), - ); - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.create", - commandId: CommandId.make("cmd-thread-create-plan-target-unrelated"), - threadId: targetThreadId, - projectId: asProjectId("project-1"), - title: "Plan Target", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - branch: null, - worktreePath: null, - createdAt, - }), - ); - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.session.set", - commandId: CommandId.make("cmd-session-set-plan-target-unrelated"), - threadId: targetThreadId, - session: { - threadId: targetThreadId, - status: "ready", - providerName: "codex", - runtimeMode: "approval-required", - activeTurnId: null, - updatedAt: createdAt, - lastError: null, - }, - createdAt, - }), - ); - - harness.emit({ - type: "turn.proposed.completed", - eventId: asEventId("evt-plan-source-completed-unrelated"), - provider: ProviderDriverKind.make("codex"), - createdAt, - threadId: sourceThreadId, - turnId: sourceTurnId, - payload: { - planMarkdown: "# Source plan", - }, - }); - - const sourceThreadWithPlan = await waitForThread( - harness.readModel, - (thread) => - thread.proposedPlans.some( - (proposedPlan: ProviderRuntimeTestProposedPlan) => - proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" && - proposedPlan.implementedAt === null, - ), - 2_000, - sourceThreadId, - ); - const sourcePlan = sourceThreadWithPlan.proposedPlans.find( - (entry: ProviderRuntimeTestProposedPlan) => - entry.id === "plan:thread-plan:turn:turn-plan-source", - ); - expect(sourcePlan).toBeDefined(); - if (!sourcePlan) { - throw new Error("Expected source plan to exist."); - } - - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-turn-start-plan-target-unrelated"), - threadId: targetThreadId, - message: { - messageId: asMessageId("msg-plan-target-unrelated"), - role: "user", - text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan", - attachments: [], - }, - sourceProposedPlan: { - threadId: sourceThreadId, - planId: sourcePlan.id, - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - createdAt: "2026-01-01T00:00:00.000Z", - }), - ); - - harness.setProviderSession({ - provider: ProviderDriverKind.make("codex"), - status: "running", - runtimeMode: "approval-required", - threadId: targetThreadId, - createdAt, - updatedAt: createdAt, - activeTurnId: expectedTurnId, - }); - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-unrelated-plan-implementation"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: targetThreadId, - turnId: replayedTurnId, - }); - - await harness.drain(); - - const readModel = await harness.readModel(); - const sourceThreadAfterUnrelatedStart = readModel.threads.find( - (entry) => entry.id === sourceThreadId, - ); - expect( - sourceThreadAfterUnrelatedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id), - ).toMatchObject({ - implementedAt: null, - implementationThreadId: null, - }); - }); - - it("finalizes buffered proposed-plan deltas into a first-class proposed plan on turn completion", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-plan-buffer"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-plan-buffer"), - }); - - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && thread.session?.activeTurnId === "turn-plan-buffer", - ); - - harness.emit({ - type: "turn.proposed.delta", - eventId: asEventId("evt-plan-delta-1"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-plan-buffer"), - payload: { - delta: "## Buffered plan\n\n- first", - }, - }); - harness.emit({ - type: "turn.proposed.delta", - eventId: asEventId("evt-plan-delta-2"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-plan-buffer"), - payload: { - delta: "\n- second", - }, - }); - harness.emit({ - type: "turn.completed", - eventId: asEventId("evt-turn-completed-plan-buffer"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-plan-buffer"), - payload: { - state: "completed", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.proposedPlans.some( - (proposedPlan: ProviderRuntimeTestProposedPlan) => - proposedPlan.id === "plan:thread-1:turn:turn-plan-buffer", - ), - ); - const proposedPlan = thread.proposedPlans.find( - (entry: ProviderRuntimeTestProposedPlan) => - entry.id === "plan:thread-1:turn:turn-plan-buffer", - ); - expect(proposedPlan?.planMarkdown).toBe("## Buffered plan\n\n- first\n- second"); - }); - - it("buffers assistant deltas by default until completion", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-buffered"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered"), - }); - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && thread.session?.activeTurnId === "turn-buffered", - ); - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-buffered"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered"), - itemId: asItemId("item-buffered"), - payload: { - streamKind: "assistant_text", - delta: "buffer me", - }, - }); - - await harness.drain(); - const midReadModel = await harness.readModel(); - const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); - expect( - midThread?.messages.some( - (message: ProviderRuntimeTestMessage) => message.id === "assistant:item-buffered", - ), - ).toBe(false); - - harness.emit({ - type: "item.completed", - eventId: asEventId("evt-message-completed-buffered"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered"), - itemId: asItemId("item-buffered"), - payload: { - itemType: "assistant_message", - status: "completed", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-buffered" && !message.streaming, - ), - ); - const message = thread.messages.find( - (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered", - ); - expect(message?.text).toBe("buffer me"); - expect(message?.streaming).toBe(false); - }); - - it("flushes and completes buffered assistant text when an approval request opens", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-buffered-request-flush"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-request-flush"), - }); - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-buffered-request-flush", - ); - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-buffered-request-flush"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-request-flush"), - itemId: asItemId("item-buffered-request-flush"), - payload: { - streamKind: "assistant_text", - delta: "visible before approval", - }, - }); - harness.emit({ - type: "request.opened", - eventId: asEventId("evt-request-opened-buffered-request-flush"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-request-flush"), - requestId: ApprovalRequestId.make("req-buffered-request-flush"), - payload: { - requestType: "command_execution_approval", - detail: "pwd", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-buffered-request-flush" && - !message.streaming && - message.text === "visible before approval", - ), - ); - const message = thread.messages.find( - (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered-request-flush", - ); - expect(message?.streaming).toBe(false); - }); - - it("flushes and completes buffered assistant text when user input is requested", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-buffered-user-input-flush"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-user-input-flush"), - }); - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-buffered-user-input-flush", - ); - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-buffered-user-input-flush"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-user-input-flush"), - itemId: asItemId("item-buffered-user-input-flush"), - payload: { - streamKind: "assistant_text", - delta: "visible before user input", - }, - }); - harness.emit({ - type: "user-input.requested", - eventId: asEventId("evt-user-input-requested-buffered-user-input-flush"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-user-input-flush"), - requestId: ApprovalRequestId.make("req-buffered-user-input-flush"), - payload: { - questions: [ - { - id: "choice", - header: "Choice", - question: "Pick one", - options: [{ label: "A", description: "Option A" }], - }, - ], - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-buffered-user-input-flush" && - !message.streaming && - message.text === "visible before user input", - ), - ); - const message = thread.messages.find( - (entry: ProviderRuntimeTestMessage) => - entry.id === "assistant:item-buffered-user-input-flush", - ); - expect(message?.streaming).toBe(false); - }); - - it("does not create assistant segments for whitespace-only buffered text at approval boundaries", async () => { - const harness = await createHarness(); - const startedAt = "2026-03-28T06:28:00.000Z"; - const pausedAt = "2026-03-28T06:28:01.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-buffered-whitespace-request"), - provider: ProviderDriverKind.make("codex"), - createdAt: startedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-whitespace-request"), - }); - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-buffered-whitespace-request", - ); - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-buffered-whitespace-request"), - provider: ProviderDriverKind.make("codex"), - createdAt: startedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-whitespace-request"), - itemId: asItemId("item-buffered-whitespace-request"), - payload: { - streamKind: "assistant_text", - delta: "\n\n\n", - }, - }); - harness.emit({ - type: "request.opened", - eventId: asEventId("evt-request-opened-buffered-whitespace-request"), - provider: ProviderDriverKind.make("codex"), - createdAt: pausedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-whitespace-request"), - requestId: ApprovalRequestId.make("req-buffered-whitespace-request"), - payload: { - requestType: "command_execution_approval", - detail: "pwd", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested", - ), - ); - expect( - thread.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-buffered-whitespace-request", - ), - ).toBe(false); - }); - - it("starts a new buffered assistant message segment after approval and completes without duplication", async () => { - const harness = await createHarness(); - const startedAt = "2026-03-28T06:07:00.000Z"; - const pausedAt = "2026-03-28T06:07:01.000Z"; - const resumedAt = "2026-03-28T06:07:02.000Z"; - const completedAt = "2026-03-28T06:07:03.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-buffered-request-append"), - provider: ProviderDriverKind.make("codex"), - createdAt: startedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-request-append"), - }); - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-buffered-request-append", - ); - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-buffered-request-append-initial"), - provider: ProviderDriverKind.make("codex"), - createdAt: startedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-request-append"), - itemId: asItemId("item-buffered-request-append"), - payload: { - streamKind: "assistant_text", - delta: "first half", - }, - }); - harness.emit({ - type: "request.opened", - eventId: asEventId("evt-request-opened-buffered-request-append"), - provider: ProviderDriverKind.make("codex"), - createdAt: pausedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-request-append"), - requestId: ApprovalRequestId.make("req-buffered-request-append"), - payload: { - requestType: "command_execution_approval", - detail: "pwd", - }, - }); - - await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-buffered-request-append" && - !message.streaming && - message.text === "first half", - ), - ); - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-buffered-request-append-followup"), - provider: ProviderDriverKind.make("codex"), - createdAt: resumedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-request-append"), - itemId: asItemId("item-buffered-request-append"), - payload: { - streamKind: "assistant_text", - delta: " second half", - }, - }); - harness.emit({ - type: "item.completed", - eventId: asEventId("evt-message-completed-buffered-request-append"), - provider: ProviderDriverKind.make("codex"), - createdAt: completedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffered-request-append"), - itemId: asItemId("item-buffered-request-append"), - payload: { - itemType: "assistant_message", - status: "completed", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-buffered-request-append:segment:1" && - !message.streaming && - message.text === " second half", - ), - ); - const firstMessage = thread.messages.find( - (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered-request-append", - ); - const resumedMessage = thread.messages.find( - (entry: ProviderRuntimeTestMessage) => - entry.id === "assistant:item-buffered-request-append:segment:1", - ); - expect(firstMessage?.text).toBe("first half"); - expect(firstMessage?.streaming).toBe(false); - expect(resumedMessage?.text).toBe(" second half"); - expect(resumedMessage?.streaming).toBe(false); - - const events = await Effect.runPromise( - Stream.runCollect(harness.engine.readEvents(0)).pipe( - Effect.map((chunk) => Array.from(chunk)), - ), - ); - const assistantEvents = events.filter( - (event): event is Extract<(typeof events)[number], { type: "thread.message-sent" }> => - event.type === "thread.message-sent" && - event.payload.messageId.startsWith("assistant:item-buffered-request-append"), - ); - expect(assistantEvents).toHaveLength(4); - expect(assistantEvents[0]?.payload.streaming).toBe(true); - expect(assistantEvents[0]?.payload.text).toBe("first half"); - expect(assistantEvents[1]?.payload.streaming).toBe(false); - expect(assistantEvents[1]?.payload.text).toBe(""); - expect(assistantEvents[2]?.payload.messageId).toBe( - "assistant:item-buffered-request-append:segment:1", - ); - expect(assistantEvents[2]?.payload.streaming).toBe(true); - expect(assistantEvents[2]?.payload.text).toBe(" second half"); - expect(assistantEvents[3]?.payload.messageId).toBe( - "assistant:item-buffered-request-append:segment:1", - ); - expect(assistantEvents[3]?.payload.streaming).toBe(false); - expect(assistantEvents[3]?.payload.text).toBe(""); - }); - - it("starts a new streaming assistant message segment after approval", async () => { - const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } }); - const startedAt = "2026-03-28T07:00:00.000Z"; - const pausedAt = "2026-03-28T07:00:01.000Z"; - const resumedAt = "2026-03-28T07:00:02.000Z"; - const completedAt = "2026-03-28T07:00:03.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-streaming-request-segment"), - provider: ProviderDriverKind.make("codex"), - createdAt: startedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-streaming-request-segment"), - }); - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-streaming-request-segment", - ); - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-streaming-request-segment-initial"), - provider: ProviderDriverKind.make("codex"), - createdAt: startedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-streaming-request-segment"), - itemId: asItemId("item-streaming-request-segment"), - payload: { - streamKind: "assistant_text", - delta: "before approval", - }, - }); - harness.emit({ - type: "request.opened", - eventId: asEventId("evt-request-opened-streaming-request-segment"), - provider: ProviderDriverKind.make("codex"), - createdAt: pausedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-streaming-request-segment"), - requestId: ApprovalRequestId.make("req-streaming-request-segment"), - payload: { - requestType: "command_execution_approval", - detail: "pwd", - }, - }); - - await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-streaming-request-segment" && - !message.streaming && - message.text === "before approval", - ), - ); - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-streaming-request-segment-followup"), - provider: ProviderDriverKind.make("codex"), - createdAt: resumedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-streaming-request-segment"), - itemId: asItemId("item-streaming-request-segment"), - payload: { - streamKind: "assistant_text", - delta: " after approval", - }, - }); - harness.emit({ - type: "item.completed", - eventId: asEventId("evt-message-completed-streaming-request-segment"), - provider: ProviderDriverKind.make("codex"), - createdAt: completedAt, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-streaming-request-segment"), - itemId: asItemId("item-streaming-request-segment"), - payload: { - itemType: "assistant_message", - status: "completed", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-streaming-request-segment:segment:1" && - !message.streaming && - message.text === " after approval", - ), - ); - expect( - thread.messages.find( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-streaming-request-segment", - )?.text, - ).toBe("before approval"); - expect( - thread.messages.find( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-streaming-request-segment:segment:1", - )?.text, - ).toBe(" after approval"); - }); - - it("streams assistant deltas when thread.turn.start requests streaming mode", async () => { - const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } }); - const now = "2026-01-01T00:00:00.000Z"; - - await Effect.runPromise( - harness.engine.dispatch({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-turn-start-streaming-mode"), - threadId: ThreadId.make("thread-1"), - message: { - messageId: asMessageId("message-streaming-mode"), - role: "user", - text: "stream please", - attachments: [], - }, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: "approval-required", - createdAt: now, - }), - ); - await harness.drain(); - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-streaming-mode"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-streaming-mode"), - }); - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-streaming-mode", - ); - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-streaming-mode"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-streaming-mode"), - itemId: asItemId("item-streaming-mode"), - payload: { - streamKind: "assistant_text", - delta: "hello live", - }, - }); - - const liveThread = await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-streaming-mode" && - message.streaming && - message.text === "hello live", - ), - ); - const liveMessage = liveThread.messages.find( - (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-streaming-mode", - ); - expect(liveMessage?.streaming).toBe(true); - - harness.emit({ - type: "item.completed", - eventId: asEventId("evt-message-completed-streaming-mode"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-streaming-mode"), - itemId: asItemId("item-streaming-mode"), - payload: { - itemType: "assistant_message", - status: "completed", - detail: "hello live", - }, - }); - - const finalThread = await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-streaming-mode" && !message.streaming, - ), - ); - const finalMessage = finalThread.messages.find( - (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-streaming-mode", - ); - expect(finalMessage?.text).toBe("hello live"); - expect(finalMessage?.streaming).toBe(false); - }); - - it("spills oversized buffered deltas and still finalizes full assistant text", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - const oversizedText = "x".repeat(40_000); - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-buffer-spill"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffer-spill"), - }); - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-buffer-spill", - ); - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-buffer-spill"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffer-spill"), - itemId: asItemId("item-buffer-spill"), - payload: { - streamKind: "assistant_text", - delta: oversizedText, - }, - }); - harness.emit({ - type: "item.completed", - eventId: asEventId("evt-message-completed-buffer-spill"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-buffer-spill"), - itemId: asItemId("item-buffer-spill"), - payload: { - itemType: "assistant_message", - status: "completed", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-buffer-spill" && !message.streaming, - ), - ); - const message = thread.messages.find( - (entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffer-spill", - ); - expect(message?.text.length).toBe(oversizedText.length); - expect(message?.text).toBe(oversizedText); - expect(message?.streaming).toBe(false); - }); - - it("does not duplicate assistant completion when item.completed is followed by turn.completed", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-turn-started-for-complete-dedup"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-complete-dedup"), - }); - - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "running" && - thread.session?.activeTurnId === "turn-complete-dedup", - ); - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-message-delta-for-complete-dedup"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-complete-dedup"), - itemId: asItemId("item-complete-dedup"), - payload: { - streamKind: "assistant_text", - delta: "done", - }, - }); - harness.emit({ - type: "item.completed", - eventId: asEventId("evt-message-completed-for-complete-dedup"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-complete-dedup"), - itemId: asItemId("item-complete-dedup"), - payload: { - itemType: "assistant_message", - status: "completed", - }, - }); - harness.emit({ - type: "turn.completed", - eventId: asEventId("evt-turn-completed-for-complete-dedup"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-complete-dedup"), - payload: { - state: "completed", - }, - }); - - await waitForThread( - harness.readModel, - (thread) => - thread.session?.status === "ready" && - thread.session?.activeTurnId === null && - thread.messages.some( - (message: ProviderRuntimeTestMessage) => - message.id === "assistant:item-complete-dedup" && !message.streaming, - ), - ); - - const events = await Effect.runPromise( - Stream.runCollect(harness.engine.readEvents(0)).pipe( - Effect.map((chunk) => Array.from(chunk)), - ), - ); - const completionEvents = events.filter((event) => { - if (event.type !== "thread.message-sent") { - return false; - } - return ( - event.payload.messageId === "assistant:item-complete-dedup" && - event.payload.streaming === false - ); - }); - expect(completionEvents).toHaveLength(1); - }); - - it("maps canonical request events into approval activities with requestKind", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "request.opened", - eventId: asEventId("evt-request-opened"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - requestId: ApprovalRequestId.make("req-open"), - payload: { - requestType: "command_execution_approval", - detail: "pwd", - }, - }); - - harness.emit({ - type: "request.resolved", - eventId: asEventId("evt-request-resolved"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - requestId: ApprovalRequestId.make("req-open"), - payload: { - requestType: "command_execution_approval", - decision: "accept", - }, - }); - - await waitForThread( - harness.readModel, - (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested", - ) && - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "approval.resolved", - ), - ); - - const readModel = await harness.readModel(); - const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); - expect(thread).toBeDefined(); - - const requested = thread?.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-request-opened", - ); - const requestedPayload = - requested?.payload && typeof requested.payload === "object" - ? (requested.payload as Record) - : undefined; - expect(requestedPayload?.requestKind).toBe("command"); - expect(requestedPayload?.requestType).toBe("command_execution_approval"); - - const resolved = thread?.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-request-resolved", - ); - const resolvedPayload = - resolved?.payload && typeof resolved.payload === "object" - ? (resolved.payload as Record) - : undefined; - expect(resolvedPayload?.requestKind).toBe("command"); - expect(resolvedPayload?.requestType).toBe("command_execution_approval"); - }); - - it("maps runtime.error into errored session state", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "runtime.error", - eventId: asEventId("evt-runtime-error"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-3"), - payload: { - message: "runtime exploded", - }, - }); - - const thread = await waitForThread( - harness.readModel, - (entry) => - entry.session?.status === "error" && - entry.session?.activeTurnId === "turn-3" && - entry.session?.lastError === "runtime exploded", - ); - expect(thread.session?.status).toBe("error"); - expect(thread.session?.lastError).toBe("runtime exploded"); - }); - - it("records runtime.error activities from the typed payload message", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "runtime.error", - eventId: asEventId("evt-runtime-error-activity"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-runtime-error-activity"), - payload: { - message: "runtime activity exploded", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some((activity) => activity.id === "evt-runtime-error-activity"), - ); - const activity = thread.activities.find( - (entry: ProviderRuntimeTestActivity) => entry.id === "evt-runtime-error-activity", - ); - const activityPayload = - activity?.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : undefined; - - expect(activity?.kind).toBe("runtime.error"); - expect(activityPayload?.message).toBe("runtime activity exploded"); - }); - - it("keeps the session running when a runtime.warning arrives during an active turn", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "turn.started", - eventId: asEventId("evt-warning-turn-started"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-warning"), - payload: {}, - }); - - harness.emit({ - type: "runtime.warning", - eventId: asEventId("evt-warning-runtime"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-warning"), - payload: { - message: "Reconnecting... 2/5", - detail: { - willRetry: true, - }, - }, - }); - - const thread = await waitForThread( - harness.readModel, - (entry) => - entry.session?.status === "running" && - entry.session?.activeTurnId === "turn-warning" && - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => - activity.id === "evt-warning-runtime" && activity.kind === "runtime.warning", - ), - ); - expect(thread.session?.status).toBe("running"); - expect(thread.session?.activeTurnId).toBe("turn-warning"); - expect(thread.session?.lastError).toBeNull(); - }); - - it("maps session/thread lifecycle and item.started into session/activity projections", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "session.started", - eventId: asEventId("evt-session-started"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - message: "session started", - }); - harness.emit({ - type: "thread.started", - eventId: asEventId("evt-thread-started"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - }); - harness.emit({ - type: "item.started", - eventId: asEventId("evt-tool-started"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-9"), - payload: { - itemType: "command_execution", - status: "in_progress", - title: "Read file", - detail: "/tmp/file.ts", - }, - }); - - const thread = await waitForThread( - harness.readModel, - (entry) => - entry.session?.status === "ready" && - entry.session?.activeTurnId === null && - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "tool.started", - ), - ); - - expect(thread.session?.status).toBe("ready"); - expect( - thread.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "tool.started", - ), - ).toBe(true); - }); - - it("consumes P1 runtime events into thread metadata, diff checkpoints, and activities", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "thread.metadata.updated", - eventId: asEventId("evt-thread-metadata-updated"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - payload: { - name: "Renamed by provider", - metadata: { source: "provider" }, - }, - }); - - harness.emit({ - type: "turn.plan.updated", - eventId: asEventId("evt-turn-plan-updated"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-p1"), - payload: { - explanation: "Working through the plan", - plan: [ - { step: "Inspect files", status: "completed" }, - { step: "Apply patch", status: "in_progress" }, - ], - }, - }); - - harness.emit({ - type: "item.updated", - eventId: asEventId("evt-item-updated"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-p1"), - itemId: asItemId("item-p1-tool"), - payload: { - itemType: "command_execution", - status: "in_progress", - title: "Run tests", - detail: "bun test", - data: { pid: 123 }, - }, - }); - - harness.emit({ - type: "runtime.warning", - eventId: asEventId("evt-runtime-warning"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-p1"), - payload: { - message: "Provider got slow", - detail: { latencyMs: 1500 }, - }, - }); - - harness.emit({ - type: "turn.diff.updated", - eventId: asEventId("evt-turn-diff-updated"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-p1"), - itemId: asItemId("item-p1-assistant"), - payload: { - unifiedDiff: "diff --git a/file.txt b/file.txt\n+hello\n", - }, - }); - - const thread = await waitForThread( - harness.readModel, - (entry) => - entry.title === "Renamed by provider" && - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "turn.plan.updated", - ) && - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "tool.updated", - ) && - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "runtime.warning", - ) && - entry.checkpoints.some( - (checkpoint: ProviderRuntimeTestCheckpoint) => checkpoint.turnId === "turn-p1", - ), - ); - - expect(thread.title).toBe("Renamed by provider"); - - const planActivity = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-turn-plan-updated", - ); - const planPayload = - planActivity?.payload && typeof planActivity.payload === "object" - ? (planActivity.payload as Record) - : undefined; - expect(planActivity?.kind).toBe("turn.plan.updated"); - expect(Array.isArray(planPayload?.plan)).toBe(true); - - const toolUpdate = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-item-updated", - ); - const toolUpdatePayload = - toolUpdate?.payload && typeof toolUpdate.payload === "object" - ? (toolUpdate.payload as Record) - : undefined; - expect(toolUpdate?.kind).toBe("tool.updated"); - expect(toolUpdatePayload?.itemType).toBe("command_execution"); - expect(toolUpdatePayload?.status).toBe("in_progress"); - - const warning = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-runtime-warning", - ); - const warningPayload = - warning?.payload && typeof warning.payload === "object" - ? (warning.payload as Record) - : undefined; - expect(warning?.kind).toBe("runtime.warning"); - expect(warningPayload?.message).toBe("Provider got slow"); - - const checkpoint = thread.checkpoints.find( - (entry: ProviderRuntimeTestCheckpoint) => entry.turnId === "turn-p1", - ); - expect(checkpoint?.status).toBe("missing"); - expect(checkpoint?.assistantMessageId).toBe("assistant:item-p1-assistant"); - expect(checkpoint?.checkpointRef).toBe("provider-diff:evt-turn-diff-updated"); - }); - - it("projects context window updates into normalized thread activities", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "thread.token-usage.updated", - eventId: asEventId("evt-thread-token-usage-updated"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - payload: { - usage: { - usedTokens: 1075, - totalProcessedTokens: 10_200, - maxTokens: 128_000, - inputTokens: 1000, - cachedInputTokens: 500, - outputTokens: 50, - reasoningOutputTokens: 25, - lastUsedTokens: 1075, - lastInputTokens: 1000, - lastCachedInputTokens: 500, - lastOutputTokens: 50, - lastReasoningOutputTokens: 25, - compactsAutomatically: true, - }, - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", - ), - ); - - const usageActivity = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", - ); - expect(usageActivity).toBeDefined(); - expect(usageActivity?.payload).toMatchObject({ - usedTokens: 1075, - totalProcessedTokens: 10_200, - maxTokens: 128_000, - inputTokens: 1000, - cachedInputTokens: 500, - outputTokens: 50, - reasoningOutputTokens: 25, - lastUsedTokens: 1075, - compactsAutomatically: true, - }); - }); - - it("projects Codex camelCase token usage payloads into normalized thread activities", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "thread.token-usage.updated", - eventId: asEventId("evt-thread-token-usage-updated-camel"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - payload: { - usage: { - usedTokens: 126, - totalProcessedTokens: 11_839, - maxTokens: 258_400, - inputTokens: 120, - cachedInputTokens: 0, - outputTokens: 6, - reasoningOutputTokens: 0, - lastUsedTokens: 126, - lastInputTokens: 120, - lastCachedInputTokens: 0, - lastOutputTokens: 6, - lastReasoningOutputTokens: 0, - compactsAutomatically: true, - }, - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", - ), - ); - - const usageActivity = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", - ); - expect(usageActivity?.payload).toMatchObject({ - usedTokens: 126, - totalProcessedTokens: 11_839, - maxTokens: 258_400, - inputTokens: 120, - cachedInputTokens: 0, - outputTokens: 6, - reasoningOutputTokens: 0, - lastUsedTokens: 126, - lastInputTokens: 120, - lastOutputTokens: 6, - compactsAutomatically: true, - }); - }); - - it("projects Claude usage snapshots with context window into normalized thread activities", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "thread.token-usage.updated", - eventId: asEventId("evt-thread-token-usage-updated-claude-window"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: now, - threadId: asThreadId("thread-1"), - payload: { - usage: { - usedTokens: 31_251, - lastUsedTokens: 31_251, - maxTokens: 200_000, - toolUses: 25, - durationMs: 43_567, - }, - }, - raw: { - source: "claude.sdk.message", - method: "claude/result/success", - payload: {}, - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", - ), - ); - - const usageActivity = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated", - ); - expect(usageActivity?.payload).toMatchObject({ - usedTokens: 31_251, - lastUsedTokens: 31_251, - maxTokens: 200_000, - toolUses: 25, - durationMs: 43_567, - }); - }); - - it("projects compacted thread state into context compaction activities", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "thread.state.changed", - eventId: asEventId("evt-thread-compacted"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-1"), - payload: { - state: "compacted", - detail: { source: "provider" }, - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "context-compaction", - ), - ); - - const activity = thread.activities.find( - (candidate: ProviderRuntimeTestActivity) => candidate.kind === "context-compaction", - ); - expect(activity?.summary).toBe("Context compacted"); - expect(activity?.tone).toBe("info"); - }); - - it("projects Codex task lifecycle chunks into thread activities", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "task.started", - eventId: asEventId("evt-task-started"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-task-1"), - payload: { - taskId: "turn-task-1", - taskType: "plan", - }, - }); - - harness.emit({ - type: "task.progress", - eventId: asEventId("evt-task-progress"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-task-1"), - payload: { - taskId: "turn-task-1", - description: "Comparing the desktop rollout chunks to the app-server stream.", - summary: "Code reviewer is validating the desktop rollout chunks.", - }, - }); - - harness.emit({ - type: "task.completed", - eventId: asEventId("evt-task-completed"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-task-1"), - payload: { - taskId: "turn-task-1", - status: "completed", - summary: "\n# Plan title\n", - }, - }); - harness.emit({ - type: "turn.proposed.completed", - eventId: asEventId("evt-task-proposed-plan-completed"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-task-1"), - payload: { - planMarkdown: "# Plan title", - }, - }); - - const thread = await waitForThread( - harness.readModel, - (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "task.completed", - ) && - entry.proposedPlans.some( - (proposedPlan: ProviderRuntimeTestProposedPlan) => - proposedPlan.id === "plan:thread-1:turn:turn-task-1", - ), - ); - - const started = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-started", - ); - const progress = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => - activity.id === "task-progress:thread-1:turn-task-1", - ); - const completed = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-completed", - ); - - const progressPayload = - progress?.payload && typeof progress.payload === "object" - ? (progress.payload as Record) - : undefined; - const completedPayload = - completed?.payload && typeof completed.payload === "object" - ? (completed.payload as Record) - : undefined; - - expect(started?.kind).toBe("task.started"); - expect(started?.summary).toBe("Plan task started"); - expect(progress?.kind).toBe("task.progress"); - expect(progressPayload?.detail).toBe("Code reviewer is validating the desktop rollout chunks."); - expect(progressPayload?.summary).toBe( - "Code reviewer is validating the desktop rollout chunks.", - ); - expect(completed?.kind).toBe("task.completed"); - expect(completedPayload?.detail).toBe("\n# Plan title\n"); - expect( - thread.proposedPlans.find( - (entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-task-1", - )?.planMarkdown, - ).toBe("# Plan title"); - }); - - it("titles task activities with the task description, including on completion", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "task.started", - eventId: asEventId("evt-named-task-started"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-named-task"), - payload: { - taskId: "named-task-1", - description: "Typecheck mobile app", - taskType: "local_bash", - }, - }); - - harness.emit({ - type: "task.progress", - eventId: asEventId("evt-named-task-progress"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-named-task"), - payload: { - taskId: "named-task-1", - description: "Typecheck mobile app", - summary: "Running tsc across the mobile workspace.", - }, - }); - - harness.emit({ - type: "task.completed", - eventId: asEventId("evt-named-task-completed"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-named-task"), - payload: { - taskId: "named-task-1", - status: "completed", - summary: "Typecheck finished without errors.", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-named-task-completed", - ), - ); - - const progress = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => - activity.id === "task-progress:thread-1:named-task-1", - ); - const completed = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-named-task-completed", - ); - - const progressPayload = - progress?.payload && typeof progress.payload === "object" - ? (progress.payload as Record) - : undefined; - const completedPayload = - completed?.payload && typeof completed.payload === "object" - ? (completed.payload as Record) - : undefined; - - expect(progress?.summary).toBe("Typecheck mobile app"); - expect(progressPayload?.title).toBe("Typecheck mobile app"); - expect(completed?.summary).toBe("Task completed"); - expect(completedPayload?.title).toBe("Typecheck mobile app"); - expect(completedPayload?.summary).toBe("Typecheck finished without errors."); - expect(completedPayload?.detail).toBe("Typecheck finished without errors."); - }); - - it("titles task completion from task.started when no progress event carried the name", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "task.started", - eventId: asEventId("evt-fast-task-started"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-fast-task"), - payload: { - taskId: "fast-task-1", - description: "wait for codex review to finish", - taskType: "local_bash", - }, - }); - - harness.emit({ - type: "task.completed", - eventId: asEventId("evt-fast-task-completed"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-fast-task"), - payload: { - taskId: "fast-task-1", - status: "completed", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-fast-task-completed", - ), - ); - - const completed = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-fast-task-completed", - ); - const completedPayload = - completed?.payload && typeof completed.payload === "object" - ? (completed.payload as Record) - : undefined; - - expect(completedPayload?.title).toBe("wait for codex review to finish"); - }); - - it("titles task completion from persisted activities after the description cache is swept", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "task.progress", - eventId: asEventId("evt-swept-task-progress"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-swept-task"), - payload: { - taskId: "swept-task-1", - description: "Watch round-3 CI and bots", - summary: "Polling CI checks.", - }, - }); - - await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => - activity.id === "task-progress:thread-1:swept-task-1", - ), - ); - - // session.exited sweeps the in-memory description cache; the completion - // that follows must recover the name from persisted activities. - harness.emit({ - type: "session.exited", - eventId: asEventId("evt-swept-task-session-exited"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: now, - threadId: asThreadId("thread-1"), - payload: {}, - }); - - harness.emit({ - type: "task.completed", - eventId: asEventId("evt-swept-task-completed"), - provider: ProviderDriverKind.make("claudeAgent"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-swept-task"), - payload: { - taskId: "swept-task-1", - status: "completed", - summary: "CI is green.", - }, - }); - - const thread = await waitForThread(harness.readModel, (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-swept-task-completed", - ), - ); - - const completed = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-swept-task-completed", - ); - const completedPayload = - completed?.payload && typeof completed.payload === "object" - ? (completed.payload as Record) - : undefined; - - expect(completedPayload?.title).toBe("Watch round-3 CI and bots"); - }); - - it("projects structured user input request and resolution as thread activities", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "user-input.requested", - eventId: asEventId("evt-user-input-requested"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-user-input"), - requestId: ApprovalRequestId.make("req-user-input-1"), - payload: { - questions: [ - { - id: "sandbox_mode", - header: "Sandbox", - question: "Which mode should be used?", - options: [ - { - label: "workspace-write", - description: "Allow workspace writes only", - }, - ], - }, - ], - }, - }); - - harness.emit({ - type: "user-input.resolved", - eventId: asEventId("evt-user-input-resolved"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-user-input"), - requestId: ApprovalRequestId.make("req-user-input-1"), - payload: { - answers: { - sandbox_mode: "workspace-write", - }, - }, - }); - - const thread = await waitForThread( - harness.readModel, - (entry) => - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "user-input.requested", - ) && - entry.activities.some( - (activity: ProviderRuntimeTestActivity) => activity.kind === "user-input.resolved", - ), - ); - - const requested = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-user-input-requested", - ); - expect(requested?.kind).toBe("user-input.requested"); - - const resolved = thread.activities.find( - (activity: ProviderRuntimeTestActivity) => activity.id === "evt-user-input-resolved", - ); - const resolvedPayload = - resolved?.payload && typeof resolved.payload === "object" - ? (resolved.payload as Record) - : undefined; - expect(resolved?.kind).toBe("user-input.resolved"); - expect(resolvedPayload?.answers).toEqual({ - sandbox_mode: "workspace-write", - }); - }); - - it("continues processing runtime events after a single event handler failure", async () => { - const harness = await createHarness(); - const now = "2026-01-01T00:00:00.000Z"; - - harness.emit({ - type: "content.delta", - eventId: asEventId("evt-invalid-delta"), - provider: ProviderDriverKind.make("codex"), - createdAt: now, - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-invalid"), - itemId: asItemId("item-invalid"), - payload: { - streamKind: "assistant_text", - delta: undefined, - }, - } as unknown as ProviderRuntimeEvent); - - harness.emit({ - type: "runtime.error", - eventId: asEventId("evt-runtime-error-after-failure"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: asThreadId("thread-1"), - turnId: asTurnId("turn-after-failure"), - payload: { - message: "runtime still processed", - }, - }); - - const thread = await waitForThread( - harness.readModel, - (entry) => - entry.session?.status === "error" && - entry.session?.activeTurnId === "turn-after-failure" && - entry.session?.lastError === "runtime still processed", - ); - expect(thread.session?.status).toBe("error"); - expect(thread.session?.lastError).toBe("runtime still processed"); - }); -}); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts deleted file mode 100644 index 0325379724..0000000000 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ /dev/null @@ -1,2071 +0,0 @@ -import { - ApprovalRequestId, - type AssistantDeliveryMode, - CommandId, - MessageId, - type OrchestrationEvent, - type OrchestrationMessage, - type OrchestrationProposedPlanId, - CheckpointRef, - classifyTaskAgentKind, - EventId, - isToolLifecycleItemType, - ThreadId, - type ThreadTokenUsageSnapshot, - TurnId, - type OrchestrationCheckpointSummary, - type OrchestrationProposedPlan, - type OrchestrationThread, - type OrchestrationThreadActivity, - type ProviderRuntimeEvent, -} from "@t3tools/contracts"; -import * as Cache from "effect/Cache"; -import * as Cause from "effect/Cause"; -import * as Crypto from "effect/Crypto"; -import * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Stream from "effect/Stream"; -import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker"; - -import { ProviderService } from "../../provider/Services/ProviderService.ts"; -import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts"; -import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts"; -import { isGitRepository } from "../../git/Utils.ts"; -import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts"; -import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts"; -import { ThreadPlanProgressService } from "../ThreadPlanProgress.ts"; -import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"; -import { - ProviderRuntimeIngestionService, - type ProviderRuntimeIngestionShape, -} from "../Services/ProviderRuntimeIngestion.ts"; -import { forkParked } from "../../serverActivation.ts"; -import { ServerSettingsService } from "../../serverSettings.ts"; - -const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`; -const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`; - -// Fallback when the in-memory description cache no longer has the task name -// (server restart, session-exit sweep, TTL/capacity eviction): earlier -// task.started/task.progress activities for the task are persisted with it. -function findTaskTitleInActivities( - activities: ReadonlyArray | undefined, - taskId: string, -): string | undefined { - if (!activities) { - return undefined; - } - for (let index = activities.length - 1; index >= 0; index -= 1) { - const activity = activities[index]; - if (!activity || (activity.kind !== "task.started" && activity.kind !== "task.progress")) { - continue; - } - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as { taskId?: unknown; title?: unknown; detail?: unknown }) - : undefined; - if (payload?.taskId !== taskId) { - continue; - } - const title = - typeof payload.title === "string" - ? payload.title - : activity.kind === "task.started" && typeof payload.detail === "string" - ? payload.detail - : undefined; - if (title && title.trim().length > 0) { - return title; - } - } - return undefined; -} - -interface AssistantSegmentState { - baseKey: string; - nextSegmentIndex: number; - activeMessageId: MessageId | null; -} - -const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000; -const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120); -const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000; -const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120); -const BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY = 10_000; -const BUFFERED_PROPOSED_PLAN_BY_ID_TTL = Duration.minutes(120); -const TASK_DESCRIPTION_BY_TASK_CACHE_CAPACITY = 10_000; -const TASK_DESCRIPTION_BY_TASK_TTL = Duration.minutes(120); -const MAX_BUFFERED_ASSISTANT_CHARS = 24_000; -const STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== "0"; - -type TurnStartRequestedDomainEvent = Extract< - OrchestrationEvent, - { type: "thread.turn-start-requested" } ->; - -type RuntimeIngestionInput = - | { - source: "runtime"; - event: ProviderRuntimeEvent; - } - | { - source: "domain"; - event: TurnStartRequestedDomainEvent; - }; - -function toTurnId(value: TurnId | string | undefined): TurnId | undefined { - return value === undefined ? undefined : TurnId.make(String(value)); -} - -function toApprovalRequestId(value: string | undefined): ApprovalRequestId | undefined { - return value === undefined ? undefined : ApprovalRequestId.make(value); -} - -function sameId(left: string | null | undefined, right: string | null | undefined): boolean { - if (left === null || left === undefined || right === null || right === undefined) { - return false; - } - return left === right; -} - -function hasAssistantMessageForTurn( - messages: ReadonlyArray, - turnId: TurnId, - options?: { readonly streamingOnly?: boolean }, -): boolean { - for (let index = 0; index < messages.length; index += 1) { - const message = messages[index]; - if (!message) { - continue; - } - if (message.role !== "assistant" || message.turnId !== turnId) { - continue; - } - if (options?.streamingOnly === true && !message.streaming) { - continue; - } - return true; - } - return false; -} - -function findMessageById( - messages: ReadonlyArray, - messageId: MessageId, -): OrchestrationMessage | undefined { - for (let index = 0; index < messages.length; index += 1) { - const message = messages[index]; - if (message?.id === messageId) { - return message; - } - } - return undefined; -} - -function findProposedPlanById( - proposedPlans: ReadonlyArray< - Pick - >, - planId: string, -): - | Pick - | undefined { - for (let index = 0; index < proposedPlans.length; index += 1) { - const proposedPlan = proposedPlans[index]; - if (proposedPlan?.id === planId) { - return proposedPlan; - } - } - return undefined; -} - -function hasCheckpointForTurn( - checkpoints: ReadonlyArray, - turnId: TurnId, -): boolean { - for (let index = 0; index < checkpoints.length; index += 1) { - if (checkpoints[index]?.turnId === turnId) { - return true; - } - } - return false; -} - -function maxCheckpointTurnCount( - checkpoints: ReadonlyArray, -): number { - let maxTurnCount = 0; - for (let index = 0; index < checkpoints.length; index += 1) { - const checkpoint = checkpoints[index]; - if (checkpoint && checkpoint.checkpointTurnCount > maxTurnCount) { - maxTurnCount = checkpoint.checkpointTurnCount; - } - } - return maxTurnCount; -} - -function truncateDetail(value: string, limit = 180): string { - return value.length > limit ? `${value.slice(0, limit - 3)}...` : value; -} - -function normalizeProposedPlanMarkdown(planMarkdown: string | undefined): string | undefined { - const trimmed = planMarkdown?.trim(); - if (!trimmed) { - return undefined; - } - return trimmed; -} - -function hasRenderableAssistantText(text: string | undefined): boolean { - return (text?.trim().length ?? 0) > 0; -} - -function proposedPlanIdForTurn(threadId: ThreadId, turnId: TurnId): string { - return `plan:${threadId}:turn:${turnId}`; -} - -function proposedPlanIdFromEvent(event: ProviderRuntimeEvent, threadId: ThreadId): string { - const turnId = toTurnId(event.turnId); - if (turnId) { - return proposedPlanIdForTurn(threadId, turnId); - } - if (event.itemId) { - return `plan:${threadId}:item:${event.itemId}`; - } - return `plan:${threadId}:event:${event.eventId}`; -} - -function assistantSegmentBaseKeyFromEvent(event: ProviderRuntimeEvent): string { - return String(event.itemId ?? event.turnId ?? event.eventId); -} - -function assistantSegmentMessageId(baseKey: string, segmentIndex: number): MessageId { - return MessageId.make( - segmentIndex === 0 ? `assistant:${baseKey}` : `assistant:${baseKey}:segment:${segmentIndex}`, - ); -} -function buildContextWindowActivityPayload( - event: ProviderRuntimeEvent, -): ThreadTokenUsageSnapshot | undefined { - if (event.type !== "thread.token-usage.updated" || event.payload.usage.usedTokens <= 0) { - return undefined; - } - return event.payload.usage; -} - -function normalizeRuntimeTurnState( - value: string | undefined, -): "completed" | "failed" | "interrupted" | "cancelled" { - switch (value) { - case "failed": - case "interrupted": - case "cancelled": - case "completed": - return value; - default: - return "completed"; - } -} - -function orchestrationSessionStatusFromRuntimeState( - state: "starting" | "running" | "waiting" | "ready" | "interrupted" | "stopped" | "error", -): "starting" | "running" | "ready" | "interrupted" | "stopped" | "error" { - switch (state) { - case "starting": - return "starting"; - case "running": - case "waiting": - return "running"; - case "ready": - return "ready"; - case "interrupted": - return "interrupted"; - case "stopped": - return "stopped"; - case "error": - return "error"; - } -} - -function sessionStatusAllowsActiveTurn( - status: ReturnType, -): boolean { - return status === "starting" || status === "running"; -} - -function requestKindFromCanonicalRequestType( - requestType: string | undefined, -): "command" | "file-read" | "file-change" | undefined { - switch (requestType) { - case "command_execution_approval": - case "exec_command_approval": - return "command"; - case "file_read_approval": - return "file-read"; - case "file_change_approval": - case "apply_patch_approval": - return "file-change"; - default: - return undefined; - } -} - -/** - * Copies the optional TaskAgentLinkage bundle from a task.* runtime payload - * into the persisted activity payload. Identity fields ride on every row so - * client folds survive activity retention; absent fields stay absent. - */ -function taskLinkageActivityFields(payload: Record): Record { - const fields: Record = { - // Server-stamped classification: persisted rows are self-describing, so - // clients trust the stamp instead of re-deriving agent-vs-background - // from taskType denylists and marker heuristics (legacy rows without a - // stamp keep the client fallback). - agentKind: classifyTaskAgentKind({ - taskType: typeof payload.taskType === "string" ? payload.taskType : undefined, - agentId: typeof payload.agentId === "string" ? payload.agentId : undefined, - }), - }; - for (const key of [ - "taskType", - "agentId", - "title", - "role", - "model", - "effort", - "toolUseId", - "parentAgentId", - "workflowName", - "agentIndex", - "phaseIndex", - "phaseTitle", - "phases", - "attempt", - "runHandles", - "outputFile", - "agentPath", - "timelineBypass", - "typedUsage", - "status", - "error", - ] as const) { - if (payload[key] !== undefined) { - fields[key] = payload[key]; - } - } - return fields; -} - -export function runtimeEventToActivities( - event: ProviderRuntimeEvent, - taskTitle?: string, -): ReadonlyArray { - const maybeSequence = (() => { - const eventWithSequence = event as ProviderRuntimeEvent & { sessionSequence?: number }; - return eventWithSequence.sessionSequence !== undefined - ? { sequence: eventWithSequence.sessionSequence } - : {}; - })(); - switch (event.type) { - case "request.opened": { - if (event.payload.requestType === "tool_user_input") { - return []; - } - const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType); - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "approval", - kind: "approval.requested", - summary: - requestKind === "command" - ? "Command approval requested" - : requestKind === "file-read" - ? "File-read approval requested" - : requestKind === "file-change" - ? "File-change approval requested" - : "Approval requested", - payload: { - requestId: toApprovalRequestId(event.requestId), - ...(requestKind ? { requestKind } : {}), - requestType: event.payload.requestType, - ...(event.payload.detail ? { detail: event.payload.detail } : {}), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "request.resolved": { - if (event.payload.requestType === "tool_user_input") { - return []; - } - const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType); - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "approval", - kind: "approval.resolved", - summary: "Approval resolved", - payload: { - requestId: toApprovalRequestId(event.requestId), - ...(requestKind ? { requestKind } : {}), - requestType: event.payload.requestType, - ...(event.payload.decision ? { decision: event.payload.decision } : {}), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "runtime.error": { - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "error", - kind: "runtime.error", - summary: "Runtime error", - payload: { - message: truncateDetail(event.payload.message), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "tool.denied": { - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "error", - kind: "tool.denied", - summary: `Tool denied: ${event.payload.toolName}`, - payload: { - toolName: event.payload.toolName, - ...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}), - ...(event.payload.reason ? { detail: truncateDetail(event.payload.reason) } : {}), - ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "runtime.warning": { - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "info", - kind: "runtime.warning", - // Use the adapter-supplied message as the row label so the work log - // shows what the warning was about, not a generic "Runtime warning". - summary: truncateDetail(event.payload.message, 120), - payload: { - message: truncateDetail(event.payload.message), - ...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "turn.plan.updated": { - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "info", - kind: "turn.plan.updated", - summary: "Plan updated", - payload: { - plan: event.payload.plan, - ...(event.payload.explanation !== undefined - ? { explanation: event.payload.explanation } - : {}), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "user-input.requested": { - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "info", - kind: "user-input.requested", - summary: "User input requested", - payload: { - ...(event.requestId ? { requestId: event.requestId } : {}), - questions: event.payload.questions, - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "user-input.resolved": { - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "info", - kind: "user-input.resolved", - summary: "User input submitted", - payload: { - ...(event.requestId ? { requestId: event.requestId } : {}), - answers: event.payload.answers, - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "task.started": { - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "info", - kind: "task.started", - summary: - event.payload.taskType === "plan" - ? "Plan task started" - : event.payload.taskType - ? `${event.payload.taskType} task started` - : "Task started", - payload: { - taskId: event.payload.taskId, - ...(event.payload.taskType ? { taskType: event.payload.taskType } : {}), - ...(event.payload.description - ? { detail: truncateDetail(event.payload.description) } - : {}), - ...taskLinkageActivityFields(event.payload as Record), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "task.progress": { - const linkage = taskLinkageActivityFields(event.payload as Record); - // Usage and activity are independent latest-state streams. Keeping them - // under separate stable ids prevents a command/reasoning update from - // replacing the last known token count (and prevents a usage-only tick - // from blanking the last meaningful activity). - const identityLinkage = { ...linkage }; - delete identityLinkage.typedUsage; - delete identityLinkage.status; - delete identityLinkage.error; - const title = - event.payload.description.trim().length > 0 - ? { title: truncateDetail(event.payload.description, 120) } - : {}; - const hasProgressState = - event.payload.typedUsage === undefined || - event.payload.summary !== undefined || - event.payload.lastToolName !== undefined || - event.payload.status !== undefined || - event.payload.error !== undefined; - return [ - ...(hasProgressState - ? [ - { - // Stable per-task id: activity is "latest state", not - // history, so each meaningful tick replaces the last. This - // bounds a large fleet to one activity row per task. - id: EventId.make(`task-progress:${event.threadId}:${event.payload.taskId}`), - createdAt: event.createdAt, - tone: "info" as const, - kind: "task.progress" as const, - summary: - event.payload.description.trim().length > 0 - ? truncateDetail(event.payload.description, 120) - : "Reasoning update", - payload: { - taskId: event.payload.taskId, - ...title, - detail: truncateDetail(event.payload.summary ?? event.payload.description), - ...(event.payload.summary - ? { summary: truncateDetail(event.payload.summary) } - : {}), - ...(event.payload.lastToolName - ? { lastToolName: event.payload.lastToolName } - : {}), - ...(event.payload.status ? { status: event.payload.status } : {}), - ...(event.payload.error ? { error: event.payload.error } : {}), - ...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}), - ...identityLinkage, - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ] - : []), - ...(event.payload.typedUsage !== undefined - ? [ - { - id: EventId.make(`task-usage:${event.threadId}:${event.payload.taskId}`), - createdAt: event.createdAt, - tone: "info" as const, - kind: "task.progress" as const, - summary: "Task usage updated", - payload: { - taskId: event.payload.taskId, - ...title, - ...identityLinkage, - usageSnapshot: true, - typedUsage: event.payload.typedUsage, - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ] - : []), - ]; - } - - case "task.updated": { - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: event.payload.status === "failed" ? "error" : "info", - kind: "task.updated", - summary: - event.payload.status === "failed" - ? "Task failed" - : event.payload.status - ? `Task ${event.payload.status}` - : "Task updated", - payload: { - taskId: event.payload.taskId, - ...(event.payload.description - ? { detail: truncateDetail(event.payload.description) } - : {}), - ...(event.payload.endedAt ? { endedAt: event.payload.endedAt } : {}), - ...(event.payload.isBackgrounded !== undefined - ? { isBackgrounded: event.payload.isBackgrounded } - : {}), - ...taskLinkageActivityFields(event.payload as Record), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "tool.progress": { - // Only agent-owned heartbeats are persisted: they feed the owning - // agent's activity line. Parent-conversation tool progress stays - // ephemeral (item lifecycle already covers it). - if (event.payload.taskId === undefined) { - return []; - } - return [ - { - // Same stable-id treatment as task.progress: a heartbeat is - // "what is this agent doing right now", so one row per task - // (thread-scoped for the same global-PK collision reason). - id: EventId.make(`tool-progress:${event.threadId}:${event.payload.taskId}`), - createdAt: event.createdAt, - tone: "info", - kind: "tool.progress", - summary: event.payload.toolName ?? "Tool progress", - payload: { - taskId: event.payload.taskId, - ...(event.payload.toolName ? { toolName: event.payload.toolName } : {}), - ...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}), - ...(event.payload.elapsedSeconds !== undefined - ? { elapsedSeconds: event.payload.elapsedSeconds } - : {}), - ...(event.payload.parentToolUseId - ? { parentToolUseId: event.payload.parentToolUseId } - : {}), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "task.completed": { - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: event.payload.status === "failed" ? "error" : "info", - kind: "task.completed", - summary: - event.payload.status === "failed" - ? "Task failed" - : event.payload.status === "stopped" - ? "Task stopped" - : "Task completed", - payload: { - taskId: event.payload.taskId, - status: event.payload.status, - ...(taskTitle ? { title: truncateDetail(taskTitle, 120) } : {}), - // summary + detail mirror task.progress: clients label the row from - // summary and keep detail for the preview/expanded body. - ...(event.payload.summary - ? { - summary: truncateDetail(event.payload.summary), - detail: truncateDetail(event.payload.summary), - } - : {}), - ...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}), - ...taskLinkageActivityFields(event.payload as Record), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "thread.state.changed": { - if (event.payload.state !== "compacted") { - return []; - } - - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "info", - kind: "context-compaction", - summary: "Context compacted", - payload: { - state: event.payload.state, - ...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "thread.token-usage.updated": { - const payload = buildContextWindowActivityPayload(event); - if (!payload) { - return []; - } - - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "info", - kind: "context-window.updated", - summary: "Context window updated", - payload, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "item.updated": { - if (!isToolLifecycleItemType(event.payload.itemType)) { - return []; - } - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "tool", - kind: "tool.updated", - summary: event.payload.title ?? "Tool updated", - payload: { - itemType: event.payload.itemType, - ...(event.payload.status ? { status: event.payload.status } : {}), - ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}), - ...(event.payload.data !== undefined ? { data: event.payload.data } : {}), - ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}), - ...(event.payload.parentToolUseId - ? { parentToolUseId: event.payload.parentToolUseId } - : {}), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "item.completed": { - if (!isToolLifecycleItemType(event.payload.itemType)) { - return []; - } - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "tool", - kind: "tool.completed", - summary: event.payload.title ?? "Tool", - payload: { - itemType: event.payload.itemType, - ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}), - ...(event.payload.data !== undefined ? { data: event.payload.data } : {}), - ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}), - ...(event.payload.parentToolUseId - ? { parentToolUseId: event.payload.parentToolUseId } - : {}), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - case "item.started": { - if (!isToolLifecycleItemType(event.payload.itemType)) { - return []; - } - return [ - { - id: event.eventId, - createdAt: event.createdAt, - tone: "tool", - kind: "tool.started", - summary: `${event.payload.title ?? "Tool"} started`, - payload: { - itemType: event.payload.itemType, - ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}), - ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}), - ...(event.payload.parentToolUseId - ? { parentToolUseId: event.payload.parentToolUseId } - : {}), - }, - turnId: toTurnId(event.turnId) ?? null, - ...maybeSequence, - }, - ]; - } - - default: - break; - } - - return []; -} - -const make = Effect.gen(function* () { - const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService; - const threadPlanProgress = yield* ThreadPlanProgressService; - const crypto = yield* Crypto.Crypto; - const orchestrationEngine = yield* OrchestrationEngineService; - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - const providerService = yield* ProviderService; - const projectionTurnRepository = yield* ProjectionTurnRepository; - const serverSettingsService = yield* ServerSettingsService; - const providerCommandId = (event: ProviderRuntimeEvent, tag: string) => - crypto.randomUUIDv4.pipe( - Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)), - ); - - const turnMessageIdsByTurnKey = yield* Cache.make>({ - capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY, - timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL, - lookup: () => Effect.succeed(new Set()), - }); - - const bufferedAssistantTextByMessageId = yield* Cache.make({ - capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY, - timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL, - lookup: () => Effect.succeed(""), - }); - - const assistantSegmentStateByTurnKey = yield* Cache.make({ - capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY, - timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL, - lookup: () => - Effect.die( - new Error("assistant segment state should be read through getOption before initialization"), - ), - }); - - const bufferedProposedPlanById = yield* Cache.make({ - capacity: BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY, - timeToLive: BUFFERED_PROPOSED_PLAN_BY_ID_TTL, - lookup: () => Effect.succeed({ text: "", createdAt: "" }), - }); - - // Task names arrive on task.started/task.progress but not on task.completed, - // so remember them per task to title the completion activity. - const taskDescriptionByTaskKey = yield* Cache.make({ - capacity: TASK_DESCRIPTION_BY_TASK_CACHE_CAPACITY, - timeToLive: TASK_DESCRIPTION_BY_TASK_TTL, - lookup: () => Effect.succeed(""), - }); - - const rememberTaskDescription = (threadId: ThreadId, taskId: string, description: string) => - Cache.set(taskDescriptionByTaskKey, providerTaskKey(threadId, taskId), description); - - // Entries are left in place after completion so replayed or duplicate - // terminal events stay titled; TTL, capacity, and the session-exit sweep - // bound the cache. - const lookupTaskDescription = (threadId: ThreadId, taskId: string) => - Cache.getOption(taskDescriptionByTaskKey, providerTaskKey(threadId, taskId)).pipe( - Effect.map((description) => - Option.filter(description, (value) => value.length > 0).pipe(Option.getOrUndefined), - ), - ); - - const resolveThreadDetail = Effect.fn("resolveThreadDetail")(function* (threadId: ThreadId) { - return yield* projectionSnapshotQuery - .getThreadDetailById(threadId) - .pipe(Effect.map(Option.getOrUndefined)); - }); - - const resolveThreadShell = Effect.fn("resolveThreadShell")(function* (threadId: ThreadId) { - return yield* projectionSnapshotQuery - .getThreadShellById(threadId) - .pipe(Effect.map(Option.getOrUndefined)); - }); - - const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) => - Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe( - Effect.flatMap((existingIds) => - Cache.set( - turnMessageIdsByTurnKey, - providerTurnKey(threadId, turnId), - Option.match(existingIds, { - onNone: () => new Set([messageId]), - onSome: (ids) => { - const nextIds = new Set(ids); - nextIds.add(messageId); - return nextIds; - }, - }), - ), - ), - ); - - const forgetAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) => - Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe( - Effect.flatMap((existingIds) => - Option.match(existingIds, { - onNone: () => Effect.void, - onSome: (ids) => { - const nextIds = new Set(ids); - nextIds.delete(messageId); - if (nextIds.size === 0) { - return Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)); - } - return Cache.set(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId), nextIds); - }, - }), - ), - ); - - const getAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) => - Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe( - Effect.map((existingIds) => - Option.getOrElse(existingIds, (): Set => new Set()), - ), - ); - - const clearAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) => - Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)); - - const getAssistantSegmentStateForTurn = (threadId: ThreadId, turnId: TurnId) => - Cache.getOption(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId)); - - const setAssistantSegmentStateForTurn = ( - threadId: ThreadId, - turnId: TurnId, - state: AssistantSegmentState, - ) => Cache.set(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId), state); - - const clearAssistantSegmentStateForTurn = (threadId: ThreadId, turnId: TurnId) => - Cache.invalidate(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId)); - - const getActiveAssistantMessageIdForTurn = (threadId: ThreadId, turnId: TurnId) => - getAssistantSegmentStateForTurn(threadId, turnId).pipe( - Effect.map((state) => - Option.flatMap(state, (entry) => - entry.activeMessageId ? Option.some(entry.activeMessageId) : Option.none(), - ), - ), - ); - - const startAssistantSegmentForTurn = (input: { - threadId: ThreadId; - turnId: TurnId; - baseKey: string; - }) => - getAssistantSegmentStateForTurn(input.threadId, input.turnId).pipe( - Effect.flatMap((existingState) => - Effect.gen(function* () { - const nextState = Option.match(existingState, { - onNone: () => ({ - baseKey: input.baseKey, - nextSegmentIndex: 1, - activeMessageId: assistantSegmentMessageId(input.baseKey, 0), - }), - onSome: (state) => { - const segmentIndex = state.baseKey === input.baseKey ? state.nextSegmentIndex : 0; - const messageId = assistantSegmentMessageId(input.baseKey, segmentIndex); - return { - baseKey: input.baseKey, - nextSegmentIndex: state.baseKey === input.baseKey ? state.nextSegmentIndex + 1 : 1, - activeMessageId: messageId, - } satisfies AssistantSegmentState; - }, - }); - yield* setAssistantSegmentStateForTurn(input.threadId, input.turnId, nextState); - return nextState.activeMessageId!; - }), - ), - ); - - const getOrCreateAssistantMessageId = (input: { - threadId: ThreadId; - event: ProviderRuntimeEvent; - turnId?: TurnId; - }) => - Effect.gen(function* () { - if (!input.turnId) { - return assistantSegmentMessageId(assistantSegmentBaseKeyFromEvent(input.event), 0); - } - - const activeMessageId = yield* getActiveAssistantMessageIdForTurn( - input.threadId, - input.turnId, - ); - if (Option.isSome(activeMessageId)) { - return activeMessageId.value; - } - - return yield* startAssistantSegmentForTurn({ - threadId: input.threadId, - turnId: input.turnId, - baseKey: assistantSegmentBaseKeyFromEvent(input.event), - }); - }); - - const appendBufferedAssistantText = (messageId: MessageId, delta: string) => - Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe( - Effect.flatMap((existingText) => - Effect.gen(function* () { - const nextText = Option.match(existingText, { - onNone: () => delta, - onSome: (text) => `${text}${delta}`, - }); - if (nextText.length <= MAX_BUFFERED_ASSISTANT_CHARS) { - yield* Cache.set(bufferedAssistantTextByMessageId, messageId, nextText); - return ""; - } - - // Safety valve: flush full buffered text as an assistant delta to cap memory. - yield* Cache.invalidate(bufferedAssistantTextByMessageId, messageId); - return nextText; - }), - ), - ); - - const takeBufferedAssistantText = (messageId: MessageId) => - Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe( - Effect.flatMap((existingText) => - Cache.invalidate(bufferedAssistantTextByMessageId, messageId).pipe( - Effect.as(Option.getOrElse(existingText, () => "")), - ), - ), - ); - - const clearBufferedAssistantText = (messageId: MessageId) => - Cache.invalidate(bufferedAssistantTextByMessageId, messageId); - - const appendBufferedProposedPlan = (planId: string, delta: string, createdAt: string) => - Cache.getOption(bufferedProposedPlanById, planId).pipe( - Effect.flatMap((existingEntry) => { - const existing = Option.getOrUndefined(existingEntry); - return Cache.set(bufferedProposedPlanById, planId, { - text: `${existing?.text ?? ""}${delta}`, - createdAt: - existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt, - }); - }), - ); - - const takeBufferedProposedPlan = (planId: string) => - Cache.getOption(bufferedProposedPlanById, planId).pipe( - Effect.flatMap((existingEntry) => - Cache.invalidate(bufferedProposedPlanById, planId).pipe( - Effect.as(Option.getOrUndefined(existingEntry)), - ), - ), - ); - - const clearBufferedProposedPlan = (planId: string) => - Cache.invalidate(bufferedProposedPlanById, planId); - - const clearAssistantMessageState = (messageId: MessageId) => - clearBufferedAssistantText(messageId); - - const flushBufferedAssistantMessage = (input: { - event: ProviderRuntimeEvent; - threadId: ThreadId; - messageId: MessageId; - turnId?: TurnId; - createdAt: string; - commandTag: string; - }) => - Effect.gen(function* () { - const bufferedText = yield* takeBufferedAssistantText(input.messageId); - if (!hasRenderableAssistantText(bufferedText)) { - return false; - } - - yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.delta", - commandId: yield* providerCommandId(input.event, input.commandTag), - threadId: input.threadId, - messageId: input.messageId, - delta: bufferedText, - ...(input.turnId ? { turnId: input.turnId } : {}), - createdAt: input.createdAt, - }); - return true; - }); - - const flushBufferedAssistantMessagesForTurn = (input: { - event: ProviderRuntimeEvent; - threadId: ThreadId; - turnId: TurnId; - createdAt: string; - commandTag: string; - }) => - Effect.gen(function* () { - const assistantMessageIds = yield* getAssistantMessageIdsForTurn( - input.threadId, - input.turnId, - ); - const flushedMessageIds = new Set(); - yield* Effect.forEach( - assistantMessageIds, - (messageId) => - flushBufferedAssistantMessage({ - event: input.event, - threadId: input.threadId, - messageId, - turnId: input.turnId, - createdAt: input.createdAt, - commandTag: input.commandTag, - }).pipe( - Effect.tap((flushed) => - flushed ? Effect.sync(() => flushedMessageIds.add(messageId)) : Effect.void, - ), - ), - { concurrency: 1 }, - ).pipe(Effect.asVoid); - return flushedMessageIds; - }); - - const finalizeAssistantMessage = (input: { - event: ProviderRuntimeEvent; - threadId: ThreadId; - messageId: MessageId; - turnId?: TurnId; - createdAt: string; - commandTag: string; - finalDeltaCommandTag: string; - fallbackText?: string; - hasProjectedMessage?: boolean; - }) => - Effect.gen(function* () { - const bufferedText = yield* takeBufferedAssistantText(input.messageId); - const text = - bufferedText.length > 0 - ? bufferedText - : (input.fallbackText?.trim().length ?? 0) > 0 - ? input.fallbackText! - : ""; - const hasRenderableText = hasRenderableAssistantText(text); - - if (hasRenderableText) { - yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.delta", - commandId: yield* providerCommandId(input.event, input.finalDeltaCommandTag), - threadId: input.threadId, - messageId: input.messageId, - delta: text, - ...(input.turnId ? { turnId: input.turnId } : {}), - createdAt: input.createdAt, - }); - } - - if (input.hasProjectedMessage || hasRenderableText) { - yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.complete", - commandId: yield* providerCommandId(input.event, input.commandTag), - threadId: input.threadId, - messageId: input.messageId, - ...(input.turnId ? { turnId: input.turnId } : {}), - createdAt: input.createdAt, - }); - } - yield* clearAssistantMessageState(input.messageId); - }); - - const finalizeActiveAssistantSegmentForTurn = (input: { - event: ProviderRuntimeEvent; - threadId: ThreadId; - turnId: TurnId; - createdAt: string; - commandTag: string; - finalDeltaCommandTag: string; - hasProjectedMessage: boolean; - flushedMessageIds?: ReadonlySet; - }) => - Effect.gen(function* () { - const activeMessageId = yield* getActiveAssistantMessageIdForTurn( - input.threadId, - input.turnId, - ); - if (Option.isNone(activeMessageId)) { - return; - } - - yield* finalizeAssistantMessage({ - event: input.event, - threadId: input.threadId, - messageId: activeMessageId.value, - turnId: input.turnId, - createdAt: input.createdAt, - commandTag: input.commandTag, - finalDeltaCommandTag: input.finalDeltaCommandTag, - hasProjectedMessage: - input.hasProjectedMessage || - (input.flushedMessageIds?.has(activeMessageId.value) ?? false), - }); - yield* forgetAssistantMessageId(input.threadId, input.turnId, activeMessageId.value); - - const state = yield* getAssistantSegmentStateForTurn(input.threadId, input.turnId); - if (Option.isSome(state)) { - yield* setAssistantSegmentStateForTurn(input.threadId, input.turnId, { - ...state.value, - activeMessageId: null, - }); - } - }); - - const upsertProposedPlan = (input: { - event: ProviderRuntimeEvent; - threadId: ThreadId; - threadProposedPlans: ReadonlyArray<{ - id: string; - createdAt: string; - implementedAt: string | null; - implementationThreadId: ThreadId | null; - }>; - planId: string; - turnId?: TurnId; - planMarkdown: string | undefined; - createdAt: string; - updatedAt: string; - }) => - Effect.gen(function* () { - const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown); - if (!planMarkdown) { - return; - } - - const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId); - yield* orchestrationEngine.dispatch({ - type: "thread.proposed-plan.upsert", - commandId: yield* providerCommandId(input.event, "proposed-plan-upsert"), - threadId: input.threadId, - proposedPlan: { - id: input.planId, - turnId: input.turnId ?? null, - planMarkdown, - implementedAt: existingPlan?.implementedAt ?? null, - implementationThreadId: existingPlan?.implementationThreadId ?? null, - createdAt: existingPlan?.createdAt ?? input.createdAt, - updatedAt: input.updatedAt, - }, - createdAt: input.updatedAt, - }); - }); - - const finalizeBufferedProposedPlan = (input: { - event: ProviderRuntimeEvent; - threadId: ThreadId; - threadProposedPlans: ReadonlyArray<{ - id: string; - createdAt: string; - implementedAt: string | null; - implementationThreadId: ThreadId | null; - }>; - planId: string; - turnId?: TurnId; - fallbackMarkdown?: string; - updatedAt: string; - }) => - Effect.gen(function* () { - const bufferedPlan = yield* takeBufferedProposedPlan(input.planId); - const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text); - const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown); - const planMarkdown = bufferedMarkdown ?? fallbackMarkdown; - if (!planMarkdown) { - return; - } - - yield* upsertProposedPlan({ - event: input.event, - threadId: input.threadId, - threadProposedPlans: input.threadProposedPlans, - planId: input.planId, - ...(input.turnId ? { turnId: input.turnId } : {}), - planMarkdown, - createdAt: - bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0 - ? bufferedPlan.createdAt - : input.updatedAt, - updatedAt: input.updatedAt, - }); - yield* clearBufferedProposedPlan(input.planId); - }); - - const clearTurnStateForSession = (threadId: ThreadId) => - Effect.gen(function* () { - const prefix = `${threadId}:`; - const proposedPlanPrefix = `plan:${threadId}:`; - const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey)); - const assistantSegmentKeys = Array.from(yield* Cache.keys(assistantSegmentStateByTurnKey)); - const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById)); - const taskDescriptionKeys = Array.from(yield* Cache.keys(taskDescriptionByTaskKey)); - yield* Effect.forEach( - turnKeys, - (key) => - Effect.gen(function* () { - if (!key.startsWith(prefix)) { - return; - } - - const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key); - if (Option.isSome(messageIds)) { - yield* Effect.forEach(messageIds.value, clearAssistantMessageState, { - concurrency: 1, - }).pipe(Effect.asVoid); - } - - yield* Cache.invalidate(turnMessageIdsByTurnKey, key); - }), - { concurrency: 1 }, - ).pipe(Effect.asVoid); - yield* Effect.forEach( - assistantSegmentKeys, - (key) => - key.startsWith(prefix) - ? Cache.invalidate(assistantSegmentStateByTurnKey, key) - : Effect.void, - { concurrency: 1 }, - ).pipe(Effect.asVoid); - yield* Effect.forEach( - proposedPlanKeys, - (key) => - key.startsWith(proposedPlanPrefix) - ? Cache.invalidate(bufferedProposedPlanById, key) - : Effect.void, - { concurrency: 1 }, - ).pipe(Effect.asVoid); - yield* Effect.forEach( - taskDescriptionKeys, - (key) => - key.startsWith(prefix) ? Cache.invalidate(taskDescriptionByTaskKey, key) : Effect.void, - { concurrency: 1 }, - ).pipe(Effect.asVoid); - }); - - const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn( - "getSourceProposedPlanReferenceForPendingTurnStart", - )(function* (threadId: ThreadId) { - const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ - threadId, - }); - if (Option.isNone(pendingTurnStart)) { - return null; - } - - const sourceThreadId = pendingTurnStart.value.sourceProposedPlanThreadId; - const sourcePlanId = pendingTurnStart.value.sourceProposedPlanId; - if (sourceThreadId === null || sourcePlanId === null) { - return null; - } - - return { - sourceThreadId, - sourcePlanId, - } as const; - }); - - const getExpectedProviderTurnIdForThread = Effect.fn("getExpectedProviderTurnIdForThread")( - function* (threadId: ThreadId) { - const sessions = yield* providerService.listSessions(); - const session = sessions.find((entry) => entry.threadId === threadId); - return session?.activeTurnId; - }, - ); - - const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fn( - "getSourceProposedPlanReferenceForAcceptedTurnStart", - )(function* (threadId: ThreadId, eventTurnId: TurnId | undefined) { - if (eventTurnId === undefined) { - return null; - } - - const expectedTurnId = yield* getExpectedProviderTurnIdForThread(threadId); - if (!sameId(expectedTurnId, eventTurnId)) { - return null; - } - - return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId); - }); - - const markSourceProposedPlanImplemented = Effect.fn("markSourceProposedPlanImplemented")( - function* ( - sourceThreadId: ThreadId, - sourcePlanId: OrchestrationProposedPlanId, - implementationThreadId: ThreadId, - implementedAt: string, - ) { - const sourceThread = yield* resolveThreadDetail(sourceThreadId); - const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId); - if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) { - return; - } - - const commandUuid = yield* crypto.randomUUIDv4; - yield* orchestrationEngine.dispatch({ - type: "thread.proposed-plan.upsert", - commandId: CommandId.make( - `provider:source-proposed-plan-implemented:${implementationThreadId}:${commandUuid}`, - ), - threadId: sourceThread.id, - proposedPlan: { - ...sourcePlan, - implementedAt, - implementationThreadId, - updatedAt: implementedAt, - }, - createdAt: implementedAt, - }); - }, - ); - - const processRuntimeEvent = (event: ProviderRuntimeEvent) => - Effect.gen(function* () { - const thread = yield* resolveThreadShell(event.threadId); - if (!thread) return; - - let loadedThreadDetail: OrchestrationThread | null | undefined; - const getLoadedThreadDetail = () => - Effect.gen(function* () { - if (loadedThreadDetail !== undefined) { - return loadedThreadDetail; - } - loadedThreadDetail = (yield* resolveThreadDetail(thread.id)) ?? null; - return loadedThreadDetail; - }); - - const now = event.createdAt; - const eventTurnId = toTurnId(event.turnId); - const activeTurnId = thread.session?.activeTurnId ?? null; - const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ - threadId: thread.id, - }); - const hasPendingTurnStart = - Option.isSome(pendingTurnStart) && thread.session?.status === "starting"; - - const conflictsWithActiveTurn = - activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId); - const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined; - - // A turn.started that conflicts with the active turn is legitimate when - // the server itself has a turn start pending for this thread AND the - // provider session already tracks the event's turn as its active turn: - // steering a running turn makes some providers (e.g. opencode) open a - // new turn without ever completing the superseded one. A stale - // turn.started for some other turn id still gets rejected. - const conflictingTurnStartIsPendingTurnStart = - event.type === "turn.started" && conflictsWithActiveTurn - ? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) && - Option.isSome(pendingTurnStart) - : false; - - const shouldApplyThreadLifecycle = (() => { - if (!STRICT_PROVIDER_LIFECYCLE_GUARD) { - return true; - } - switch (event.type) { - case "session.exited": - return true; - case "session.started": - case "thread.started": - return true; - case "turn.started": - return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart; - case "turn.completed": - if (conflictsWithActiveTurn || missingTurnForActiveTurn) { - return false; - } - // Only the active turn may close the lifecycle state. - if (activeTurnId !== null && eventTurnId !== undefined) { - return sameId(activeTurnId, eventTurnId); - } - // No active turn tracked: accept only completions that name their - // turn (covers a real completion whose turn.started was lost). An - // untargeted completion cannot prove it belongs to any turn this - // thread ran — the known emitter was the Claude resume handshake - // (system/init + result(num_turns: 0)), which is not a turn at - // all — and applying it here stomps the "starting" lifecycle - // state while a turn start is pending. - return eventTurnId !== undefined; - default: - return true; - } - })(); - const acceptedTurnStartedSourcePlan = - event.type === "turn.started" && shouldApplyThreadLifecycle - ? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId) - : null; - - if ( - event.type === "session.started" || - event.type === "session.state.changed" || - event.type === "session.exited" || - event.type === "thread.started" || - event.type === "turn.started" || - event.type === "turn.completed" - ) { - const status = (() => { - switch (event.type) { - case "session.state.changed": { - const runtimeStatus = orchestrationSessionStatusFromRuntimeState(event.payload.state); - return hasPendingTurnStart && runtimeStatus === "ready" ? "starting" : runtimeStatus; - } - case "turn.started": - return "running"; - case "session.exited": - return "stopped"; - case "turn.completed": - return normalizeRuntimeTurnState(event.payload.state) === "failed" - ? "error" - : "ready"; - case "session.started": - case "thread.started": - // Provider thread/session start notifications can arrive during an - // active or pending turn; preserve that lifecycle state. - return activeTurnId !== null ? "running" : hasPendingTurnStart ? "starting" : "ready"; - } - })(); - const nextActiveTurnId = - event.type === "turn.started" - ? (eventTurnId ?? null) - : event.type === "turn.completed" || event.type === "session.exited" - ? null - : event.type === "session.state.changed" && - !sessionStatusAllowsActiveTurn( - orchestrationSessionStatusFromRuntimeState(event.payload.state), - ) - ? null - : activeTurnId; - const lastError = - event.type === "session.state.changed" && event.payload.state === "error" - ? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error") - : event.type === "turn.completed" && - normalizeRuntimeTurnState(event.payload.state) === "failed" - ? (event.payload.errorMessage ?? thread.session?.lastError ?? "Turn failed") - : status === "ready" - ? null - : (thread.session?.lastError ?? null); - - if (shouldApplyThreadLifecycle) { - if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) { - yield* markSourceProposedPlanImplemented( - acceptedTurnStartedSourcePlan.sourceThreadId, - acceptedTurnStartedSourcePlan.sourcePlanId, - thread.id, - now, - ).pipe( - Effect.catchCause((cause) => - Effect.logWarning( - "provider runtime ingestion failed to mark source proposed plan", - { - eventId: event.eventId, - eventType: event.type, - cause: Cause.pretty(cause), - }, - ), - ), - ); - } - - yield* orchestrationEngine.dispatch({ - type: "thread.session.set", - commandId: yield* providerCommandId(event, "thread-session-set"), - threadId: thread.id, - session: { - threadId: thread.id, - status, - providerName: event.provider, - ...(event.providerInstanceId !== undefined - ? { providerInstanceId: event.providerInstanceId } - : {}), - runtimeMode: thread.session?.runtimeMode ?? "full-access", - activeTurnId: nextActiveTurnId, - lastError, - updatedAt: now, - }, - createdAt: now, - }); - } - } - - const assistantDelta = - event.type === "content.delta" && event.payload.streamKind === "assistant_text" - ? event.payload.delta - : undefined; - const proposedPlanDelta = - event.type === "turn.proposed.delta" ? event.payload.delta : undefined; - - if (assistantDelta && assistantDelta.length > 0) { - const turnId = toTurnId(event.turnId); - const assistantMessageId = yield* getOrCreateAssistantMessageId({ - threadId: thread.id, - event, - ...(turnId ? { turnId } : {}), - }); - if (turnId) { - yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); - } - - const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map( - serverSettingsService.getSettings, - (settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"), - ); - if (assistantDeliveryMode === "buffered") { - const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta); - if (spillChunk.length > 0) { - yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.delta", - commandId: yield* providerCommandId(event, "assistant-delta-buffer-spill"), - threadId: thread.id, - messageId: assistantMessageId, - delta: spillChunk, - ...(turnId ? { turnId } : {}), - createdAt: now, - }); - } - } else { - yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.delta", - commandId: yield* providerCommandId(event, "assistant-delta"), - threadId: thread.id, - messageId: assistantMessageId, - delta: assistantDelta, - ...(turnId ? { turnId } : {}), - createdAt: now, - }); - } - } - - const pauseForUserTurnId = - event.type === "request.opened" || event.type === "user-input.requested" - ? toTurnId(event.turnId) - : undefined; - if (pauseForUserTurnId) { - const detailedThread = yield* getLoadedThreadDetail(); - const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map( - serverSettingsService.getSettings, - (settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"), - ); - const flushedMessageIds = - assistantDeliveryMode === "buffered" - ? yield* flushBufferedAssistantMessagesForTurn({ - event, - threadId: thread.id, - turnId: pauseForUserTurnId, - createdAt: now, - commandTag: - event.type === "request.opened" - ? "assistant-delta-flush-on-request-opened" - : "assistant-delta-flush-on-user-input-requested", - }) - : new Set(); - yield* finalizeActiveAssistantSegmentForTurn({ - event, - threadId: thread.id, - turnId: pauseForUserTurnId, - createdAt: now, - commandTag: - event.type === "request.opened" - ? "assistant-complete-on-request-opened" - : "assistant-complete-on-user-input-requested", - finalDeltaCommandTag: - event.type === "request.opened" - ? "assistant-delta-finalize-on-request-opened" - : "assistant-delta-finalize-on-user-input-requested", - hasProjectedMessage: - detailedThread !== null && - hasAssistantMessageForTurn(detailedThread.messages, pauseForUserTurnId, { - streamingOnly: true, - }), - flushedMessageIds, - }); - } - - if (proposedPlanDelta && proposedPlanDelta.length > 0) { - const planId = proposedPlanIdFromEvent(event, thread.id); - yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now); - } - - const assistantCompletion = - event.type === "item.completed" && event.payload.itemType === "assistant_message" - ? { - messageId: MessageId.make( - `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, - ), - fallbackText: event.payload.detail, - } - : undefined; - const proposedPlanCompletion = - event.type === "turn.proposed.completed" - ? { - planId: proposedPlanIdFromEvent(event, thread.id), - turnId: toTurnId(event.turnId), - planMarkdown: event.payload.planMarkdown, - } - : undefined; - - if (assistantCompletion) { - const detailedThread = yield* getLoadedThreadDetail(); - const messages = detailedThread?.messages ?? []; - const turnId = toTurnId(event.turnId); - const activeAssistantMessageId = turnId - ? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId) - : Option.none(); - const hasAssistantMessagesForTurn = - turnId !== undefined ? hasAssistantMessageForTurn(messages, turnId) : false; - const assistantMessageId = Option.getOrElse( - activeAssistantMessageId, - () => assistantCompletion.messageId, - ); - const existingAssistantMessage = findMessageById(messages, assistantMessageId); - const shouldApplyFallbackCompletionText = - !existingAssistantMessage || existingAssistantMessage.text.length === 0; - - const shouldSkipRedundantCompletion = - Option.isNone(activeAssistantMessageId) && - turnId !== undefined && - hasAssistantMessagesForTurn && - (assistantCompletion.fallbackText?.trim().length ?? 0) === 0; - - if (!shouldSkipRedundantCompletion) { - if (turnId && Option.isNone(activeAssistantMessageId)) { - yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); - } - - yield* finalizeAssistantMessage({ - event, - threadId: thread.id, - messageId: assistantMessageId, - ...(turnId ? { turnId } : {}), - createdAt: now, - commandTag: "assistant-complete", - finalDeltaCommandTag: "assistant-delta-finalize", - hasProjectedMessage: existingAssistantMessage !== undefined, - ...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText - ? { fallbackText: assistantCompletion.fallbackText } - : {}), - }); - - if (turnId) { - yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId); - } - } - - if (turnId) { - yield* clearAssistantSegmentStateForTurn(thread.id, turnId); - } - } - - if (proposedPlanCompletion) { - const detailedThread = yield* getLoadedThreadDetail(); - yield* finalizeBufferedProposedPlan({ - event, - threadId: thread.id, - threadProposedPlans: detailedThread?.proposedPlans ?? [], - planId: proposedPlanCompletion.planId, - ...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}), - fallbackMarkdown: proposedPlanCompletion.planMarkdown, - updatedAt: now, - }); - } - - if (event.type === "turn.completed") { - const detailedThread = yield* getLoadedThreadDetail(); - const messages = detailedThread?.messages ?? []; - const proposedPlans = detailedThread?.proposedPlans ?? []; - const turnId = toTurnId(event.turnId); - if (turnId) { - const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId); - yield* Effect.forEach( - assistantMessageIds, - (assistantMessageId) => - finalizeAssistantMessage({ - event, - threadId: thread.id, - messageId: assistantMessageId, - turnId, - createdAt: now, - commandTag: "assistant-complete-finalize", - finalDeltaCommandTag: "assistant-delta-finalize-fallback", - hasProjectedMessage: findMessageById(messages, assistantMessageId) !== undefined, - }), - { concurrency: 1 }, - ).pipe(Effect.asVoid); - yield* clearAssistantMessageIdsForTurn(thread.id, turnId); - yield* clearAssistantSegmentStateForTurn(thread.id, turnId); - - yield* finalizeBufferedProposedPlan({ - event, - threadId: thread.id, - threadProposedPlans: proposedPlans, - planId: proposedPlanIdForTurn(thread.id, turnId), - turnId, - updatedAt: now, - }); - } - } - - if (event.type === "session.exited") { - yield* clearTurnStateForSession(thread.id); - } - - if (event.type === "runtime.error") { - const runtimeErrorMessage = event.payload.message; - - const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD - ? true - : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId); - - if (shouldApplyRuntimeError) { - yield* orchestrationEngine.dispatch({ - type: "thread.session.set", - commandId: yield* providerCommandId(event, "runtime-error-session-set"), - threadId: thread.id, - session: { - threadId: thread.id, - status: "error", - providerName: event.provider, - ...(event.providerInstanceId !== undefined - ? { providerInstanceId: event.providerInstanceId } - : {}), - runtimeMode: thread.session?.runtimeMode ?? "full-access", - activeTurnId: eventTurnId ?? null, - lastError: runtimeErrorMessage, - updatedAt: now, - }, - createdAt: now, - }); - } - } - - if (event.type === "thread.metadata.updated" && event.payload.name) { - yield* orchestrationEngine.dispatch({ - type: "thread.meta.update", - commandId: yield* providerCommandId(event, "thread-meta-update"), - threadId: thread.id, - title: event.payload.name, - }); - } - - if (event.type === "turn.diff.updated") { - const turnId = toTurnId(event.turnId); - const checkpointContext = turnId - ? yield* projectionSnapshotQuery - .getThreadCheckpointContext(thread.id) - .pipe(Effect.map(Option.getOrUndefined)) - : undefined; - const workspaceCwd = - checkpointContext?.worktreePath ?? checkpointContext?.workspaceRoot ?? undefined; - if (turnId && checkpointContext && workspaceCwd && isGitRepository(workspaceCwd)) { - // Skip if a checkpoint already exists for this turn. A real - // (non-placeholder) capture from CheckpointReactor should not - // be clobbered, and dispatching a duplicate placeholder for the - // same turnId would produce an unstable checkpointTurnCount. - if (hasCheckpointForTurn(checkpointContext.checkpoints, turnId)) { - // Already tracked; no-op. - } else { - const assistantMessageId = MessageId.make( - `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, - ); - yield* orchestrationEngine.dispatch({ - type: "thread.turn.diff.complete", - commandId: yield* providerCommandId(event, "thread-turn-diff-complete"), - threadId: thread.id, - turnId, - completedAt: now, - checkpointRef: CheckpointRef.make(`provider-diff:${event.eventId}`), - status: "missing", - files: [], - assistantMessageId, - checkpointTurnCount: maxCheckpointTurnCount(checkpointContext.checkpoints) + 1, - createdAt: now, - }); - } - } - } - - if (event.type === "task.started" || event.type === "task.progress") { - const description = event.payload.description?.trim(); - if (description) { - yield* rememberTaskDescription(thread.id, event.payload.taskId, description); - } - } - // Working-indicator plan progress: current step while the turn runs, - // cleared on settle so a finished plan never lingers as stale UI. - // Events carrying a turn id that conflicts with the active turn are - // stale (superseded turn) and must neither overwrite nor clear the - // active turn's progress; session.exited always clears. - if (event.type === "session.exited") { - threadPlanProgress.clearThreadPlanProgress(thread.id); - } else if (!conflictsWithActiveTurn) { - if (event.type === "turn.plan.updated") { - threadPlanProgress.recordPlanProgress(thread.id, event.payload.plan); - } else if (event.type === "turn.completed" || event.type === "turn.aborted") { - threadPlanProgress.clearThreadPlanProgress(thread.id); - } - } - - // Sidebar background liveness: fed from the same lifecycle stream, - // read by the shell query at mapping time (no persistence). - switch (event.type) { - case "task.started": - case "task.progress": - case "task.updated": - case "task.completed": { - const payload = event.payload as { - taskId: string; - taskType?: string; - status?: string; - agentId?: string; - }; - threadBackgroundLiveness.recordTaskLiveness({ - threadId: thread.id, - taskId: payload.taskId, - taskType: payload.taskType, - status: payload.status, - agentId: payload.agentId, - kind: - event.type === "task.started" - ? "started" - : event.type === "task.progress" - ? "progress" - : event.type === "task.updated" - ? "updated" - : "completed", - }); - break; - } - case "session.exited": - threadBackgroundLiveness.clearThreadLiveness(thread.id); - break; - default: - break; - } - - let taskTitle: string | undefined; - if (event.type === "task.completed") { - taskTitle = yield* lookupTaskDescription(thread.id, event.payload.taskId); - if (!taskTitle) { - const threadDetail = yield* getLoadedThreadDetail(); - taskTitle = findTaskTitleInActivities(threadDetail?.activities, event.payload.taskId); - } - } - - const activities = runtimeEventToActivities(event, taskTitle); - yield* Effect.forEach(activities, (activity) => - providerCommandId(event, "thread-activity-append").pipe( - Effect.flatMap((commandId) => - orchestrationEngine.dispatch({ - type: "thread.activity.append", - commandId, - threadId: thread.id, - activity, - createdAt: activity.createdAt, - }), - ), - ), - ).pipe(Effect.asVoid); - }); - - const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void; - - const processInput = (input: RuntimeIngestionInput) => - input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event); - - const processInputSafely = (input: RuntimeIngestionInput) => - processInput(input).pipe( - Effect.catchCause((cause) => { - if (Cause.hasInterruptsOnly(cause)) { - return Effect.failCause(cause); - } - return Effect.logWarning("provider runtime ingestion failed to process event", { - source: input.source, - eventId: input.event.eventId, - eventType: input.event.type, - cause: Cause.pretty(cause), - }); - }), - ); - - const worker = yield* makeDrainableWorker(processInputSafely); - - const start: ProviderRuntimeIngestionShape["start"] = () => - Effect.gen(function* () { - yield* forkParked( - Stream.runForEach(providerService.streamEvents, (event) => - worker.enqueue({ source: "runtime", event }), - ), - ); - yield* forkParked( - Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { - if (event.type !== "thread.turn-start-requested") { - return Effect.void; - } - return worker.enqueue({ source: "domain", event }); - }), - ); - }); - - return { - start, - drain: worker.drain, - } satisfies ProviderRuntimeIngestionShape; -}); - -export const ProviderRuntimeIngestionLive = Layer.effect( - ProviderRuntimeIngestionService, - make, -).pipe(Layer.provide(ProjectionTurnRepositoryLive)); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index ebabc2c05c..56646ae7d3 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -250,12 +250,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" title: command.title, workspaceRoot: command.workspaceRoot, defaultModelSelection: command.defaultModelSelection ?? null, -<<<<<<< HEAD faviconPath: null, - scripts: [], -======= scripts: command.scripts ?? [], ->>>>>>> f38dbfd84c (Integrate orchestration v2 with the application runtime) createdAt: command.createdAt, updatedAt: command.createdAt, }, diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts deleted file mode 100644 index 7334cd0197..0000000000 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ /dev/null @@ -1,1959 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; - -import type { - ProviderApprovalDecision, - ProviderRuntimeEvent, - ProviderSendTurnInput, - ProviderSession, - ProviderTurnStartResult, -} from "@t3tools/contracts"; -import { - ApprovalRequestId, - EventId, - ProviderDriverKind, - ProviderInstanceId, - ProviderSessionStartInput, - ThreadId, - TurnId, -} from "@t3tools/contracts"; -import { createModelSelection } from "@t3tools/shared/model"; -import { it, assert, vi } from "@effect/vitest"; - -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; -import * as Layer from "effect/Layer"; -import * as Metric from "effect/Metric"; -import * as Option from "effect/Option"; -import * as PubSub from "effect/PubSub"; -import * as Ref from "effect/Ref"; -import * as Scope from "effect/Scope"; -import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; -import * as SqlClient from "effect/unstable/sql/SqlClient"; - -import { - ProviderAdapterRequestError, - ProviderAdapterSessionNotFoundError, - ProviderUnsupportedError, - ProviderValidationError, - type ProviderAdapterError, -} from "../Errors.ts"; -import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; -import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts"; -import * as ProviderService from "../Services/ProviderService.ts"; -import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts"; -import { makeProviderServiceLive } from "./ProviderService.ts"; -import * as ProviderEventLoggers from "./ProviderEventLoggers.ts"; -import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts"; -import { - makeSqlitePersistenceLive, - SqlitePersistenceMemory, -} from "../../persistence/Layers/Sqlite.ts"; -import * as ServerConfig from "../../config.ts"; -import * as ServerSettings from "../../serverSettings.ts"; -import * as AnalyticsService from "../../telemetry/AnalyticsService.ts"; -import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts"; - -const defaultServerSettingsLayer = ServerSettings.ServerSettingsService.layerTest(); -const serverConfigTestLayer = ServerConfig.layerTest(process.cwd(), process.cwd()).pipe( - Layer.provide(NodeServices.layer), -); - -const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value); -const asEventId = (value: string): EventId => EventId.make(value); -const asThreadId = (value: string): ThreadId => ThreadId.make(value); -const asTurnId = (value: string): TurnId => TurnId.make(value); -const codexInstanceId = ProviderInstanceId.make("codex"); -const claudeAgentInstanceId = ProviderInstanceId.make("claudeAgent"); -const CODEX_DRIVER = ProviderDriverKind.make("codex"); -const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent"); -const CURSOR_DRIVER = ProviderDriverKind.make("cursor"); - -type LegacyProviderRuntimeEvent = { - readonly type: string; - readonly eventId: EventId; - readonly provider: ProviderDriverKind; - readonly createdAt: string; - readonly threadId: ThreadId; - readonly turnId?: string | undefined; - readonly itemId?: string | undefined; - readonly requestId?: string | undefined; - readonly payload?: unknown | undefined; - readonly [key: string]: unknown; -}; - -function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) { - const sessions = new Map(); - const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); - - const startSession = vi.fn((input: ProviderSessionStartInput) => - Effect.sync(() => { - const now = "2026-01-01T00:00:00.000Z"; - const session: ProviderSession = { - provider, - ...(input.providerInstanceId !== undefined - ? { providerInstanceId: input.providerInstanceId } - : {}), - status: "ready", - runtimeMode: input.runtimeMode, - threadId: input.threadId, - resumeCursor: input.resumeCursor ?? { - opaque: `resume-${String(input.threadId)}`, - }, - cwd: input.cwd ?? process.cwd(), - createdAt: now, - updatedAt: now, - }; - sessions.set(session.threadId, session); - return session; - }), - ); - - const sendTurn = vi.fn( - ( - input: ProviderSendTurnInput, - ): Effect.Effect => { - if (!sessions.has(input.threadId)) { - return Effect.fail( - new ProviderAdapterSessionNotFoundError({ - provider, - threadId: input.threadId, - }), - ); - } - - return Effect.succeed({ - threadId: input.threadId, - turnId: TurnId.make(`turn-${String(input.threadId)}`), - }); - }, - ); - - const interruptTurn = vi.fn( - (_threadId: ThreadId, _turnId?: TurnId): Effect.Effect => - Effect.void, - ); - - const respondToRequest = vi.fn( - ( - _threadId: ThreadId, - _requestId: string, - _decision: ProviderApprovalDecision, - ): Effect.Effect => Effect.void, - ); - - const respondToUserInput = vi.fn( - ( - _threadId: ThreadId, - _requestId: string, - _answers: Record, - ): Effect.Effect => Effect.void, - ); - - const stopSession = vi.fn( - (threadId: ThreadId): Effect.Effect => - Effect.sync(() => { - sessions.delete(threadId); - }), - ); - - const listSessions = vi.fn( - (): Effect.Effect> => - Effect.sync(() => Array.from(sessions.values())), - ); - - const hasSession = vi.fn( - (threadId: ThreadId): Effect.Effect => Effect.succeed(sessions.has(threadId)), - ); - - const readThread = vi.fn( - ( - threadId: ThreadId, - ): Effect.Effect< - { - threadId: ThreadId; - turns: ReadonlyArray<{ id: TurnId; items: readonly [] }>; - }, - ProviderAdapterError - > => - Effect.succeed({ - threadId, - turns: [{ id: asTurnId("turn-1"), items: [] }], - }), - ); - - const rollbackThread = vi.fn( - ( - threadId: ThreadId, - _numTurns: number, - ): Effect.Effect<{ threadId: ThreadId; turns: readonly [] }, ProviderAdapterError> => - Effect.succeed({ threadId, turns: [] }), - ); - - const stopAll = vi.fn( - (): Effect.Effect => - Effect.sync(() => { - sessions.clear(); - }), - ); - - const adapter: ProviderAdapterShape = { - provider, - capabilities: { - sessionModelSwitch: "in-session", - }, - startSession, - sendTurn, - interruptTurn, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - hasSession, - readThread, - rollbackThread, - stopAll, - get streamEvents() { - return Stream.fromPubSub(runtimeEventPubSub); - }, - }; - - const emit = (event: LegacyProviderRuntimeEvent): void => { - Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent)); - }; - - const updateSession = ( - threadId: ThreadId, - update: (session: ProviderSession) => ProviderSession, - ): void => { - const existing = sessions.get(threadId); - if (!existing) { - return; - } - sessions.set(threadId, update(existing)); - }; - - return { - adapter, - emit, - updateSession, - startSession, - sendTurn, - interruptTurn, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - hasSession, - readThread, - rollbackThread, - stopAll, - }; -} - -const advanceTestClock = (ms: number) => - TestClock.adjust(`${ms} millis`).pipe(Effect.andThen(Effect.yieldNow)); - -const hasMetricSnapshot = ( - snapshots: ReadonlyArray, - id: string, - attributes: Readonly>, -) => - snapshots.some( - (snapshot) => - snapshot.id === id && - Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), - ); - -function makeProviderServiceLayer() { - const codex = makeFakeCodexAdapter(); - const claude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const cursor = makeFakeCodexAdapter(CURSOR_DRIVER); - const registry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("codex")]: codex.adapter, - [ProviderDriverKind.make("claudeAgent")]: claude.adapter, - [ProviderDriverKind.make("cursor")]: cursor.adapter, - }); - - const providerAdapterLayer = Layer.succeed( - ProviderAdapterRegistry.ProviderAdapterRegistry, - registry, - ); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - - const layer = it.layer( - Layer.mergeAll( - makeProviderServiceLive().pipe( - Layer.provide(providerAdapterLayer), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provideMerge(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ), - directoryLayer, - - runtimeRepositoryLayer, - NodeServices.layer, - ), - ); - - return { - codex, - claude, - cursor, - layer, - }; -} - -it.effect("ProviderServiceLive catches stopAll failures during shutdown", () => - Effect.gen(function* () { - const codex = makeFakeCodexAdapter(); - codex.stopAll.mockImplementation(() => - Effect.fail( - new ProviderAdapterRequestError({ - provider: String(CODEX_DRIVER), - method: "stopAll", - detail: "simulated stopAll failure", - }), - ), - ); - const registry = makeAdapterRegistryMock({ - [CODEX_DRIVER]: codex.adapter, - }); - const providerAdapterLayer = Layer.succeed( - ProviderAdapterRegistry.ProviderAdapterRegistry, - registry, - ); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - const providerLayer = Layer.mergeAll( - makeProviderServiceLive().pipe( - Layer.provide(providerAdapterLayer), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provideMerge(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ), - directoryLayer, - runtimeRepositoryLayer, - NodeServices.layer, - ); - const scope = yield* Scope.make(); - const runtimeServices = yield* Layer.build(providerLayer).pipe(Scope.provide(scope)); - - yield* ProviderService.ProviderService.pipe(Effect.provide(runtimeServices)); - const closeExit = yield* Scope.close(scope, Exit.void).pipe(Effect.exit); - - assert.equal(Exit.isSuccess(closeExit), true); - assert.equal(codex.stopAll.mock.calls.length, 1); - }), -); - -it.effect("ProviderServiceLive rejects new sessions for disabled providers", () => - Effect.gen(function* () { - const codex = makeFakeCodexAdapter(); - const claude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const registryBase = makeAdapterRegistryMock({ - [CODEX_DRIVER]: codex.adapter, - [CLAUDE_AGENT_DRIVER]: claude.adapter, - }); - const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = { - ...registryBase, - getInstanceInfo: (instanceId) => - instanceId === claudeAgentInstanceId - ? Effect.succeed({ - instanceId, - driverKind: CLAUDE_AGENT_DRIVER, - displayName: undefined, - enabled: false, - continuationIdentity: { - driverKind: CLAUDE_AGENT_DRIVER, - continuationKey: "claudeAgent:instance:claudeAgent", - }, - }) - : registryBase.getInstanceInfo(instanceId), - }; - const providerAdapterLayer = Layer.succeed( - ProviderAdapterRegistry.ProviderAdapterRegistry, - registry, - ); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - const providerLayer = makeProviderServiceLive().pipe( - Layer.provide(providerAdapterLayer), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - const failure = yield* Effect.flip( - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - return yield* provider.startSession(asThreadId("thread-disabled"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-disabled"), - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(providerLayer)), - ); - - assert.instanceOf(failure, ProviderValidationError); - assert.include(failure.issue, "Provider instance 'claudeAgent' is disabled"); - assert.equal(claude.startSession.mock.calls.length, 0); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.effect( - "ProviderServiceLive allows enabled custom instances when legacy driver is disabled", - () => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("codex_personal"); - const driverKind = CODEX_DRIVER; - const codex = makeFakeCodexAdapter(); - const unsupported = () => - new ProviderUnsupportedError({ - provider: driverKind, - }); - const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = { - getByInstance: (requestedInstanceId) => - requestedInstanceId === instanceId - ? Effect.succeed(codex.adapter) - : Effect.fail(unsupported()), - getInstanceInfo: (requestedInstanceId) => - requestedInstanceId === instanceId - ? Effect.succeed({ - instanceId, - driverKind, - displayName: "Codex Personal", - enabled: true, - continuationIdentity: { - driverKind, - continuationKey: "codex:/Users/example/.codex", - }, - }) - : Effect.fail(unsupported()), - listInstances: () => Effect.succeed([instanceId]), - listProviders: () => Effect.succeed([driverKind] as const), - streamChanges: Stream.empty, - subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => - PubSub.subscribe(pubsub), - ), - }; - const providerAdapterLayer = Layer.succeed( - ProviderAdapterRegistry.ProviderAdapterRegistry, - registry, - ); - const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest({ - providers: { - codex: { - enabled: false, - }, - }, - }); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const providerLayer = makeProviderServiceLive().pipe( - Layer.provide(providerAdapterLayer), - Layer.provide(directoryLayer), - Layer.provide(serverSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - const session = yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - return yield* provider.startSession(asThreadId("thread-enabled-custom"), { - provider: driverKind, - providerInstanceId: instanceId, - threadId: asThreadId("thread-enabled-custom"), - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(providerLayer)); - - assert.equal(session.providerInstanceId, instanceId); - assert.equal(codex.startSession.mock.calls.length, 1); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.effect("ProviderServiceLive rejects new sessions for disabled custom instances", () => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("codex_personal"); - const driverKind = ProviderDriverKind.make("codex"); - const codex = makeFakeCodexAdapter(); - const unsupported = () => - new ProviderUnsupportedError({ - provider: ProviderDriverKind.make("codex"), - }); - const registry: ProviderAdapterRegistry.ProviderAdapterRegistry["Service"] = { - getByInstance: (requestedInstanceId) => - requestedInstanceId === instanceId - ? Effect.succeed(codex.adapter) - : Effect.fail(unsupported()), - getInstanceInfo: (requestedInstanceId) => - requestedInstanceId === instanceId - ? Effect.succeed({ - instanceId, - driverKind, - displayName: "Codex Personal", - enabled: false, - continuationIdentity: { - driverKind, - continuationKey: "codex:/Users/example/.codex", - }, - }) - : Effect.fail(unsupported()), - listInstances: () => Effect.succeed([instanceId]), - listProviders: () => Effect.succeed([CODEX_DRIVER] as const), - streamChanges: Stream.empty, - subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => - PubSub.subscribe(pubsub), - ), - }; - const providerAdapterLayer = Layer.succeed( - ProviderAdapterRegistry.ProviderAdapterRegistry, - registry, - ); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - const providerLayer = makeProviderServiceLive().pipe( - Layer.provide(providerAdapterLayer), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - const failure = yield* Effect.flip( - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - return yield* provider.startSession(asThreadId("thread-disabled-instance"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: instanceId, - threadId: asThreadId("thread-disabled-instance"), - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(providerLayer)), - ); - - assert.instanceOf(failure, ProviderValidationError); - assert.include(failure.issue, "Provider instance 'codex_personal' is disabled"); - assert.equal(codex.startSession.mock.calls.length, 0); - }).pipe(Effect.provide(NodeServices.layer)), -); - -const routing = makeProviderServiceLayer(); - -it.effect("ProviderServiceLive writes canonical events to the emitting thread segment", () => - Effect.gen(function* () { - const codex = makeFakeCodexAdapter(); - const canonicalEvents: ProviderRuntimeEvent[] = []; - const canonicalThreadIds: Array = []; - const registry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("codex")]: codex.adapter, - }); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - const providerLayer = makeProviderServiceLive({ - canonicalEventLogger: { - filePath: "memory://provider-canonical-events", - write: (event, threadId) => { - canonicalEvents.push(event as ProviderRuntimeEvent); - canonicalThreadIds.push(threadId ?? null); - return Effect.void; - }, - close: () => Effect.void, - }, - }).pipe( - Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - yield* Effect.gen(function* () { - yield* ProviderService.ProviderService; - yield* advanceTestClock(10); - codex.emit({ - eventId: asEventId("evt-canonical-thread-segment"), - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-canonical-thread-segment"), - createdAt: "2026-01-01T00:00:00.000Z", - type: "turn.completed", - payload: { - state: "completed", - }, - }); - yield* advanceTestClock(20); - }).pipe(Effect.provide(providerLayer)); - - assert.equal(canonicalEvents.length, 1); - assert.equal(canonicalEvents[0]?.threadId, "thread-canonical-thread-segment"); - assert.deepEqual(canonicalThreadIds, ["thread-canonical-thread-segment"]); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-service-")); - const dbPath = NodePath.join(tempDir, "orchestration.sqlite"); - - const codex = makeFakeCodexAdapter(); - const registry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("codex")]: codex.adapter, - }); - - const persistenceLayer = makeSqlitePersistenceLive(dbPath); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(persistenceLayer), - ); - const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); - - yield* Effect.gen(function* () { - const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory; - yield* directory.upsert({ - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: ThreadId.make("thread-stale"), - }); - }).pipe(Effect.provide(directoryLayer)); - - const providerLayer = makeProviderServiceLive().pipe( - Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)), - Layer.provide(directoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - yield* ProviderService.ProviderService.pipe(Effect.provide(providerLayer)); - - const persistedProvider = yield* Effect.gen(function* () { - const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory; - return yield* directory.getProvider(asThreadId("thread-stale")); - }).pipe(Effect.provide(directoryLayer)); - assert.equal(persistedProvider, "codex"); - - const runtime = yield* Effect.gen(function* () { - const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - return yield* repository.getByThreadId({ - threadId: asThreadId("thread-stale"), - }); - }).pipe(Effect.provide(runtimeRepositoryLayer)); - assert.equal(Option.isSome(runtime), true); - - const legacyTableRows = yield* Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - return yield* sql<{ readonly name: string }>` - SELECT name - FROM sqlite_master - WHERE type = 'table' AND name = 'provider_sessions' - `; - }).pipe(Effect.provide(persistenceLayer)); - assert.equal(legacyTableRows.length, 0); - - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - }).pipe(Effect.provide(NodeServices.layer)), -); - -it.effect( - "ProviderServiceLive restores rollback routing after restart using persisted thread mapping", - () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-provider-service-restart-"), - ); - const dbPath = NodePath.join(tempDir, "orchestration.sqlite"); - const persistenceLayer = makeSqlitePersistenceLive(dbPath); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(persistenceLayer), - ); - - const firstCodex = makeFakeCodexAdapter(); - const firstRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("codex")]: firstCodex.adapter, - }); - - const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const firstProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry), - ), - Layer.provide(firstDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - const updatedResumeCursor = { - threadId: asThreadId("thread-1"), - resume: "resume-session-1", - resumeSessionAt: "assistant-message-1", - turnCount: 1, - }; - - const startedSession = yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const threadId = asThreadId("thread-1"); - const session = yield* provider.startSession(threadId, { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - cwd: "/tmp/project", - runtimeMode: "full-access", - threadId, - }); - firstCodex.updateSession(threadId, (existing) => ({ - ...existing, - status: "ready", - resumeCursor: updatedResumeCursor, - updatedAt: "2026-01-01T00:00:01.000Z", - })); - return session; - }).pipe(Effect.provide(firstProviderLayer)); - - const persistedAfterStopAll = yield* Effect.gen(function* () { - const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - return yield* repository.getByThreadId({ - threadId: startedSession.threadId, - }); - }).pipe(Effect.provide(runtimeRepositoryLayer)); - assert.equal(Option.isSome(persistedAfterStopAll), true); - if (Option.isSome(persistedAfterStopAll)) { - assert.equal(persistedAfterStopAll.value.status, "stopped"); - assert.deepEqual(persistedAfterStopAll.value.resumeCursor, updatedResumeCursor); - } - - const secondCodex = makeFakeCodexAdapter(); - const secondRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("codex")]: secondCodex.adapter, - }); - const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const secondProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry), - ), - Layer.provide(secondDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - secondCodex.startSession.mockClear(); - secondCodex.rollbackThread.mockClear(); - - yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - yield* provider.rollbackConversation({ - threadId: startedSession.threadId, - numTurns: 1, - }); - }).pipe(Effect.provide(secondProviderLayer)); - - assert.equal(secondCodex.startSession.mock.calls.length, 1); - const resumedStartInput = secondCodex.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "codex"); - assert.equal(startPayload.cwd, "/tmp/project"); - assert.deepEqual(startPayload.resumeCursor, updatedResumeCursor); - assert.equal(startPayload.threadId, startedSession.threadId); - } - assert.equal(secondCodex.rollbackThread.mock.calls.length, 1); - const rollbackCall = secondCodex.rollbackThread.mock.calls[0]; - assert.equal(typeof rollbackCall?.[0], "string"); - assert.equal(rollbackCall?.[1], 1); - - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - }).pipe(Effect.provide(NodeServices.layer)), -); - -routing.layer("ProviderServiceLive routing", (it) => { - it.effect("routes provider operations and rollback conversation", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const session = yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - cwd: "/tmp/project", - runtimeMode: "full-access", - }); - assert.equal(session.provider, "codex"); - - const sessions = yield* provider.listSessions(); - assert.equal(sessions.length, 1); - - yield* provider.sendTurn({ - threadId: session.threadId, - input: "hello", - attachments: [], - }); - assert.equal(routing.codex.sendTurn.mock.calls.length, 1); - - yield* provider.interruptTurn({ threadId: session.threadId }); - assert.deepEqual(routing.codex.interruptTurn.mock.calls, [[session.threadId, undefined]]); - - yield* provider.respondToRequest({ - threadId: session.threadId, - requestId: asRequestId("req-1"), - decision: "accept", - }); - assert.deepEqual(routing.codex.respondToRequest.mock.calls, [ - [session.threadId, asRequestId("req-1"), "accept"], - ]); - - yield* provider.respondToUserInput({ - threadId: session.threadId, - requestId: asRequestId("req-user-input-1"), - answers: { - sandbox_mode: "workspace-write", - }, - }); - assert.deepEqual(routing.codex.respondToUserInput.mock.calls, [ - [ - session.threadId, - asRequestId("req-user-input-1"), - { - sandbox_mode: "workspace-write", - }, - ], - ]); - - yield* provider.rollbackConversation({ - threadId: session.threadId, - numTurns: 0, - }); - - yield* provider.stopSession({ threadId: session.threadId }); - routing.codex.startSession.mockClear(); - routing.codex.sendTurn.mockClear(); - - yield* provider.sendTurn({ - threadId: session.threadId, - input: "after-stop", - attachments: [], - }); - - assert.equal(routing.codex.startSession.mock.calls.length, 1); - const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "codex"); - assert.equal(startPayload.cwd, "/tmp/project"); - assert.deepEqual(startPayload.resumeCursor, session.resumeCursor); - assert.equal(startPayload.threadId, session.threadId); - } - assert.equal(routing.codex.sendTurn.mock.calls.length, 1); - }), - ); - - it.effect("appends attachment file paths to the turn input text", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const session = yield* provider.startSession(asThreadId("thread-attach"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-attach"), - cwd: "/tmp/project", - runtimeMode: "full-access", - }); - - const attachment = { - type: "image" as const, - id: "thread-attach-12345678-1234-1234-1234-123456789abc", - name: "screenshot.png", - mimeType: "image/png", - sizeBytes: 123, - }; - - routing.codex.sendTurn.mockClear(); - yield* provider.sendTurn({ - threadId: session.threadId, - input: "use this screenshot", - attachments: [attachment], - }); - - const turnInput = routing.codex.sendTurn.mock.calls[0]?.[0] as ProviderSendTurnInput; - assert.equal(typeof turnInput.input, "string"); - const turnText = turnInput.input ?? ""; - assert.equal(turnText.startsWith("use this screenshot"), true); - assert.include(turnText, '[Attached image "screenshot.png" is saved at: '); - assert.equal(turnText.endsWith(`${attachment.id}.png]`), true); - - // An attachment-only turn stays valid and the injected line becomes the - // whole input text, so the agent still learns the path. - routing.codex.sendTurn.mockClear(); - yield* provider.sendTurn({ - threadId: session.threadId, - attachments: [attachment], - }); - const imageOnlyInput = routing.codex.sendTurn.mock.calls[0]?.[0] as ProviderSendTurnInput; - assert.equal(imageOnlyInput.input?.startsWith('[Attached image "screenshot.png"'), true); - - yield* provider.stopSession({ threadId: session.threadId }); - }), - ); - - it.effect("recovers stale persisted sessions for rollback by resuming thread identity", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const initial = yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - cwd: "/tmp/project", - runtimeMode: "full-access", - }); - yield* routing.codex.stopSession(initial.threadId); - routing.codex.startSession.mockClear(); - routing.codex.rollbackThread.mockClear(); - - yield* provider.rollbackConversation({ - threadId: initial.threadId, - numTurns: 1, - }); - - assert.equal(routing.codex.startSession.mock.calls.length, 1); - const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "codex"); - assert.equal(startPayload.cwd, "/tmp/project"); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - assert.equal(routing.codex.rollbackThread.mock.calls.length, 1); - const rollbackCall = routing.codex.rollbackThread.mock.calls[0]; - assert.equal(rollbackCall?.[1], 1); - }), - ); - - it.effect("preserves the persisted binding when stopping a session", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - - const initial = yield* provider.startSession(asThreadId("thread-reap-preserve"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-reap-preserve"), - cwd: "/tmp/project-reap-preserve", - runtimeMode: "full-access", - }); - - yield* provider.stopSession({ threadId: initial.threadId }); - - const persistedAfterStop = yield* runtimeRepository.getByThreadId({ - threadId: initial.threadId, - }); - assert.equal(Option.isSome(persistedAfterStop), true); - if (Option.isSome(persistedAfterStop)) { - assert.equal(persistedAfterStop.value.status, "stopped"); - assert.deepEqual(persistedAfterStop.value.resumeCursor, initial.resumeCursor); - } - - routing.codex.startSession.mockClear(); - routing.codex.sendTurn.mockClear(); - - yield* provider.sendTurn({ - threadId: initial.threadId, - input: "resume after reap", - attachments: [], - }); - - assert.equal(routing.codex.startSession.mock.calls.length, 1); - const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "codex"); - assert.equal(startPayload.cwd, "/tmp/project-reap-preserve"); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - assert.equal(routing.codex.sendTurn.mock.calls.length, 1); - }), - ); - - it.effect("routes explicit claudeAgent provider session starts to the claude adapter", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const session = yield* provider.startSession(asThreadId("thread-claude"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-claude"), - cwd: "/tmp/project-claude", - runtimeMode: "full-access", - }); - - assert.equal(session.provider, "claudeAgent"); - assert.equal(routing.claude.startSession.mock.calls.length, 1); - const startInput = routing.claude.startSession.mock.calls[0]?.[0]; - assert.equal(typeof startInput === "object" && startInput !== null, true); - if (startInput && typeof startInput === "object") { - const startPayload = startInput as { - provider?: string; - providerInstanceId?: ProviderInstanceId; - cwd?: string; - }; - assert.equal(startPayload.provider, "claudeAgent"); - assert.equal(startPayload.providerInstanceId, claudeAgentInstanceId); - assert.equal(startPayload.cwd, "/tmp/project-claude"); - } - }), - ); - - it.effect("dies when an active session conflicts with its persisted binding", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory; - const threadId = asThreadId("thread-binding-mismatch"); - - yield* provider.startSession(threadId, { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId, - cwd: "/tmp/project-binding-mismatch", - runtimeMode: "full-access", - }); - yield* directory.upsert({ - threadId, - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - runtimeMode: "full-access", - }); - - const exit = yield* Effect.exit(provider.listSessions()); - assert.equal(Exit.hasDies(exit), true); - yield* directory.upsert({ - threadId, - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - runtimeMode: "full-access", - }); - }), - ); - - it.effect("stops stale sessions in other providers after a successful replacement start", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const threadId = asThreadId("thread-provider-replacement"); - - const codexSession = yield* provider.startSession(threadId, { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId, - cwd: "/tmp/project-provider-replacement", - runtimeMode: "full-access", - }); - - routing.codex.stopSession.mockClear(); - routing.claude.stopSession.mockClear(); - - const claudeSession = yield* provider.startSession(threadId, { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId, - cwd: "/tmp/project-provider-replacement", - runtimeMode: "full-access", - }); - - assert.equal(codexSession.provider, "codex"); - assert.equal(claudeSession.provider, "claudeAgent"); - assert.deepEqual(routing.codex.stopSession.mock.calls, [[threadId]]); - assert.equal(routing.claude.stopSession.mock.calls.length, 0); - - const sessions = yield* provider.listSessions(); - assert.deepEqual( - sessions - .filter((session) => session.threadId === threadId) - .map((session) => session.provider), - ["claudeAgent"], - ); - }), - ); - - it.effect("recovers stale sessions for sendTurn using persisted cwd", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const initial = yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - cwd: "/tmp/project-send-turn", - runtimeMode: "full-access", - }); - - yield* routing.codex.stopAll(); - routing.codex.startSession.mockClear(); - routing.codex.sendTurn.mockClear(); - - yield* provider.sendTurn({ - threadId: initial.threadId, - input: "resume", - attachments: [], - }); - - assert.equal(routing.codex.startSession.mock.calls.length, 1); - const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "codex"); - assert.equal(startPayload.cwd, "/tmp/project-send-turn"); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - assert.equal(routing.codex.sendTurn.mock.calls.length, 1); - }), - ); - - it.effect("recovers stale claudeAgent sessions for sendTurn using persisted cwd", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const initial = yield* provider.startSession(asThreadId("thread-claude-send-turn"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-claude-send-turn"), - cwd: "/tmp/project-claude-send-turn", - modelSelection: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - "claude-opus-4-6", - [{ id: "effort", value: "max" }], - ), - runtimeMode: "full-access", - }); - - yield* routing.claude.stopAll(); - routing.claude.startSession.mockClear(); - routing.claude.sendTurn.mockClear(); - - yield* provider.sendTurn({ - threadId: initial.threadId, - input: "resume with claude", - attachments: [], - }); - - assert.equal(routing.claude.startSession.mock.calls.length, 1); - const resumedStartInput = routing.claude.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - modelSelection?: unknown; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "claudeAgent"); - assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn"); - assert.deepEqual( - startPayload.modelSelection, - createModelSelection(ProviderInstanceId.make("claudeAgent"), "claude-opus-4-6", [ - { id: "effort", value: "max" }, - ]), - ); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - assert.equal(routing.claude.sendTurn.mock.calls.length, 1); - }), - ); - - it.effect("lists no sessions after adapter runtime clears", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - runtimeMode: "full-access", - }); - yield* provider.startSession(asThreadId("thread-2"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-2"), - runtimeMode: "full-access", - }); - - yield* routing.codex.stopAll(); - yield* routing.claude.stopAll(); - - const remaining = yield* provider.listSessions(); - assert.equal(remaining.length, 0); - }), - ); - - it.effect("persists runtime status transitions in provider_session_runtime", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - - const threadId = asThreadId("thread-runtime-status"); - const session = yield* provider.startSession(threadId, { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId, - runtimeMode: "full-access", - }); - yield* provider.sendTurn({ - threadId: session.threadId, - input: "hello", - attachments: [], - }); - - const runningRuntime = yield* runtimeRepository.getByThreadId({ - threadId: session.threadId, - }); - assert.equal(Option.isSome(runningRuntime), true); - if (Option.isSome(runningRuntime)) { - assert.equal(runningRuntime.value.status, "running"); - assert.deepEqual(runningRuntime.value.resumeCursor, session.resumeCursor); - const payload = runningRuntime.value.runtimePayload; - assert.equal(payload !== null && typeof payload === "object", true); - if (payload !== null && typeof payload === "object" && !Array.isArray(payload)) { - const runtimePayload = payload as { - cwd: string; - model: string | null; - activeTurnId: string | null; - lastError: string | null; - lastRuntimeEvent: string | null; - }; - assert.equal(runtimePayload.cwd, session.cwd); - assert.equal(runtimePayload.model, null); - assert.equal(runtimePayload.activeTurnId, `turn-${String(session.threadId)}`); - assert.equal(runtimePayload.lastError, null); - assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn"); - } - } - }), - ); - - it.effect("reuses persisted resume cursor when startSession is called after a restart", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-provider-service-start-"), - ); - const dbPath = NodePath.join(tempDir, "orchestration.sqlite"); - const persistenceLayer = makeSqlitePersistenceLive(dbPath); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(persistenceLayer), - ); - - const firstClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const firstRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter, - }); - const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const firstProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry), - ), - Layer.provide(firstDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - const initial = yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - return yield* provider.startSession(asThreadId("thread-claude-start"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-claude-start"), - cwd: "/tmp/project-claude-start", - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(firstProviderLayer)); - - yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - yield* provider.listSessions(); - }).pipe(Effect.provide(firstProviderLayer)); - - const secondClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const secondRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter, - }); - const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const secondProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry), - ), - Layer.provide(secondDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - secondClaude.startSession.mockClear(); - - yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - yield* provider.startSession(initial.threadId, { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: initial.threadId, - cwd: "/tmp/project-claude-start", - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(secondProviderLayer)); - - assert.equal(secondClaude.startSession.mock.calls.length, 1); - const resumedStartInput = secondClaude.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "claudeAgent"); - assert.equal(startPayload.cwd, "/tmp/project-claude-start"); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect( - "reuses persisted cwd when startSession resumes a claude session without cwd input", - () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-provider-service-cwd-"), - ); - const dbPath = NodePath.join(tempDir, "orchestration.sqlite"); - const persistenceLayer = makeSqlitePersistenceLive(dbPath); - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(persistenceLayer), - ); - - const firstClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const firstRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("claudeAgent")]: firstClaude.adapter, - }); - const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const firstProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, firstRegistry), - ), - Layer.provide(firstDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - const initial = yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - return yield* provider.startSession(asThreadId("thread-claude-cwd"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-claude-cwd"), - cwd: "/tmp/project-claude-cwd", - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(firstProviderLayer)); - - const secondClaude = makeFakeCodexAdapter(CLAUDE_AGENT_DRIVER); - const secondRegistry = makeAdapterRegistryMock({ - [ProviderDriverKind.make("claudeAgent")]: secondClaude.adapter, - }); - const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const secondProviderLayer = makeProviderServiceLive().pipe( - Layer.provide( - Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, secondRegistry), - ), - Layer.provide(secondDirectoryLayer), - Layer.provide(defaultServerSettingsLayer), - Layer.provide(serverConfigTestLayer), - Layer.provide(AnalyticsService.layerTest), - Layer.provide( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - ); - - secondClaude.startSession.mockClear(); - - yield* Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - yield* provider.startSession(initial.threadId, { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: initial.threadId, - runtimeMode: "full-access", - }); - }).pipe(Effect.provide(secondProviderLayer)); - - assert.equal(secondClaude.startSession.mock.calls.length, 1); - const resumedStartInput = secondClaude.startSession.mock.calls[0]?.[0]; - assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true); - if (resumedStartInput && typeof resumedStartInput === "object") { - const startPayload = resumedStartInput as { - provider?: string; - cwd?: string; - resumeCursor?: unknown; - threadId?: string; - }; - assert.equal(startPayload.provider, "claudeAgent"); - assert.equal(startPayload.cwd, "/tmp/project-claude-cwd"); - assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor); - assert.equal(startPayload.threadId, initial.threadId); - } - - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - }).pipe(Effect.provide(NodeServices.layer)), - ); -}); - -const fanout = makeProviderServiceLayer(); -fanout.layer("ProviderServiceLive fanout", (it) => { - it.effect("fans out adapter turn completion events", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const session = yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - runtimeMode: "full-access", - }); - - const eventsRef = yield* Ref.make>([]); - const consumer = yield* Stream.runForEach(provider.streamEvents, (event) => - Ref.update(eventsRef, (current) => [...current, event]), - ).pipe(Effect.forkChild); - yield* advanceTestClock(50); - - const completedEvent: LegacyProviderRuntimeEvent = { - type: "turn.completed", - eventId: asEventId("evt-1"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - status: "completed", - }; - - fanout.codex.emit(completedEvent); - yield* advanceTestClock(50); - - const events = yield* Ref.get(eventsRef); - yield* Fiber.interrupt(consumer); - - assert.equal( - events.some((entry) => entry.type === "turn.completed"), - true, - ); - assert.equal( - events.some( - (entry) => - entry.type === "turn.completed" && entry.providerInstanceId === codexInstanceId, - ), - true, - ); - }), - ); - - it.effect("fans out canonical runtime events in emission order", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const session = yield* provider.startSession(asThreadId("thread-seq"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-seq"), - runtimeMode: "full-access", - }); - - const receivedRef = yield* Ref.make>([]); - const consumer = yield* Stream.take(provider.streamEvents, 3).pipe( - Stream.runForEach((event) => Ref.update(receivedRef, (current) => [...current, event])), - Effect.forkChild, - ); - yield* advanceTestClock(50); - - fanout.codex.emit({ - type: "tool.started", - eventId: asEventId("evt-seq-1"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - toolKind: "command", - title: "Ran command", - }); - fanout.codex.emit({ - type: "tool.completed", - eventId: asEventId("evt-seq-2"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - toolKind: "command", - title: "Ran command", - }); - fanout.codex.emit({ - type: "turn.completed", - eventId: asEventId("evt-seq-3"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - status: "completed", - }); - - yield* Fiber.join(consumer); - const received = yield* Ref.get(receivedRef); - assert.deepEqual( - received.map((event) => event.eventId), - [asEventId("evt-seq-1"), asEventId("evt-seq-2"), asEventId("evt-seq-3")], - ); - }), - ); - - it.effect("keeps subscriber delivery ordered and isolates failing subscribers", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const session = yield* provider.startSession(asThreadId("thread-1"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-1"), - runtimeMode: "full-access", - }); - - const receivedByHealthy: string[] = []; - const expectedEventIds = new Set(["evt-ordered-1", "evt-ordered-2", "evt-ordered-3"]); - const healthyFiber = yield* Stream.take(provider.streamEvents, 3).pipe( - Stream.runForEach((event) => - Effect.sync(() => { - receivedByHealthy.push(event.eventId); - }), - ), - Effect.forkChild, - ); - const failingFiber = yield* Stream.take(provider.streamEvents, 1).pipe( - Stream.runForEach(() => Effect.fail("listener crash")), - Effect.forkChild, - ); - yield* advanceTestClock(50); - - const events: ReadonlyArray = [ - { - type: "tool.completed", - eventId: asEventId("evt-ordered-1"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - toolKind: "command", - title: "Ran command", - detail: "echo one", - }, - { - type: "message.delta", - eventId: asEventId("evt-ordered-2"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - delta: "hello", - }, - { - type: "turn.completed", - eventId: asEventId("evt-ordered-3"), - provider: ProviderDriverKind.make("codex"), - createdAt: "2026-01-01T00:00:00.000Z", - threadId: session.threadId, - turnId: asTurnId("turn-1"), - status: "completed", - }, - ]; - - for (const event of events) { - fanout.codex.emit(event); - } - const failingResult = yield* Effect.result(Fiber.join(failingFiber)); - assert.equal(failingResult._tag, "Failure"); - yield* Fiber.join(healthyFiber); - - assert.deepEqual( - receivedByHealthy.filter((eventId) => expectedEventIds.has(eventId)).slice(0, 3), - ["evt-ordered-1", "evt-ordered-2", "evt-ordered-3"], - ); - }), - ); - - it.effect("records provider metrics with the routed provider label", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const session = yield* provider.startSession(asThreadId("thread-metrics"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-metrics"), - cwd: "/tmp/project", - runtimeMode: "full-access", - }); - - yield* provider.interruptTurn({ threadId: session.threadId }); - yield* provider.respondToRequest({ - threadId: session.threadId, - requestId: asRequestId("req-metrics-1"), - decision: "accept", - }); - yield* provider.respondToUserInput({ - threadId: session.threadId, - requestId: asRequestId("req-metrics-2"), - answers: { - sandbox_mode: "workspace-write", - }, - }); - yield* provider.rollbackConversation({ - threadId: session.threadId, - numTurns: 1, - }); - yield* provider.stopSession({ threadId: session.threadId }); - - const snapshots = yield* Metric.snapshot; - - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "interrupt", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "approval-response", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "user-input-response", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "rollback", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_sessions_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "stop", - outcome: "success", - }), - true, - ); - }), - ); - - it.effect( - "records sendTurn metrics with the resolved provider when modelSelection is omitted", - () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const session = yield* provider.startSession(asThreadId("thread-send-metrics"), { - provider: ProviderDriverKind.make("claudeAgent"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-send-metrics"), - cwd: "/tmp/project-send-metrics", - runtimeMode: "full-access", - }); - - yield* provider.sendTurn({ - threadId: session.threadId, - input: "hello", - attachments: [], - }); - - const snapshots = yield* Metric.snapshot; - - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turns_total", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "send", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "t3_provider_turn_duration", { - provider: ProviderDriverKind.make("claudeAgent"), - operation: "send", - }), - true, - ); - }), - ); -}); - -const validation = makeProviderServiceLayer(); -validation.layer("ProviderServiceLive validation", (it) => { - it.effect("rejects session starts without an explicit provider instance id", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - validation.codex.startSession.mockClear(); - const failure = yield* Effect.flip( - provider.startSession(asThreadId("thread-missing-instance-id"), { - provider: ProviderDriverKind.make("codex"), - threadId: asThreadId("thread-missing-instance-id"), - runtimeMode: "full-access", - }), - ); - - assert.instanceOf(failure, ProviderValidationError); - assert.include(failure.issue, "Provider instance id is required for provider 'codex'."); - assert.equal(validation.codex.startSession.mock.calls.length, 0); - }), - ); - - it.effect("rejects mismatched provider kind and provider instance id", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - validation.codex.startSession.mockClear(); - validation.claude.startSession.mockClear(); - const failure = yield* Effect.flip( - provider.startSession(asThreadId("thread-instance-mismatch"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: claudeAgentInstanceId, - threadId: asThreadId("thread-instance-mismatch"), - runtimeMode: "full-access", - }), - ); - - assert.instanceOf(failure, ProviderValidationError); - assert.include( - failure.issue, - "Provider instance 'claudeAgent' belongs to driver 'claudeAgent', not 'codex'.", - ); - assert.equal(validation.codex.startSession.mock.calls.length, 0); - assert.equal(validation.claude.startSession.mock.calls.length, 0); - }), - ); - - it.effect("returns ProviderValidationError for invalid input payloads", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - - const failure = yield* Effect.result( - provider.startSession(asThreadId("thread-validation"), { - threadId: asThreadId("thread-validation"), - provider: "invalid-provider", - runtimeMode: "full-access", - } as never), - ); - - assert.equal(failure._tag, "Failure"); - if (failure._tag !== "Failure") { - return; - } - assert.equal(failure.failure._tag, "ProviderValidationError"); - if (failure.failure._tag !== "ProviderValidationError") { - return; - } - assert.equal(failure.failure.operation, "ProviderService.startSession"); - assert.equal(failure.failure.issue.includes("invalid-provider"), true); - }), - ); - - it.effect("accepts startSession when adapter has not emitted provider thread id yet", () => - Effect.gen(function* () { - const provider = yield* ProviderService.ProviderService; - const runtimeRepository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - - validation.codex.startSession.mockImplementationOnce((input: ProviderSessionStartInput) => - Effect.sync(() => { - const now = "2026-01-01T00:00:00.000Z"; - return { - provider: ProviderDriverKind.make("codex"), - status: "ready", - threadId: input.threadId, - runtimeMode: input.runtimeMode, - cwd: input.cwd ?? process.cwd(), - createdAt: now, - updatedAt: now, - } satisfies ProviderSession; - }), - ); - - const session = yield* provider.startSession(asThreadId("thread-missing"), { - provider: ProviderDriverKind.make("codex"), - providerInstanceId: codexInstanceId, - threadId: asThreadId("thread-missing"), - cwd: "/tmp/project", - runtimeMode: "full-access", - }); - - assert.equal(session.threadId, asThreadId("thread-missing")); - - const runtime = yield* runtimeRepository.getByThreadId({ - threadId: session.threadId, - }); - assert.equal(Option.isSome(runtime), true); - if (Option.isSome(runtime)) { - assert.equal(runtime.value.threadId, session.threadId); - } - }), - ); -}); diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts deleted file mode 100644 index 2ac00873df..0000000000 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ /dev/null @@ -1,1155 +0,0 @@ -/** - * ProviderServiceLive - Cross-provider orchestration layer. - * - * Routes validated transport/API calls to provider adapters through - * `ProviderAdapterRegistry` and `ProviderSessionDirectory`, and exposes a - * unified provider event stream for subscribers. - * - * It does not implement provider protocol details (adapter concern). - * - * @module ProviderServiceLive - */ -import { - ModelSelection, - NonNegativeInt, - ThreadId, - ProviderInterruptTurnInput, - ProviderRespondToRequestInput, - ProviderRespondToUserInputInput, - ProviderSendTurnInput, - ProviderSessionStartInput, - ProviderStopSessionInput, - type ProviderInstanceId, - type ProviderDriverKind, - type ProviderRuntimeEvent, - type ProviderSession, -} from "@t3tools/contracts"; -import { causeErrorTag } from "@t3tools/shared/observability"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as PubSub from "effect/PubSub"; -import * as Ref from "effect/Ref"; -import * as Schema from "effect/Schema"; -import * as SchemaIssue from "effect/SchemaIssue"; -import * as Stream from "effect/Stream"; - -import { resolveAttachmentPath } from "../../attachmentStore.ts"; -import * as ServerConfig from "../../config.ts"; -import { - increment, - providerMetricAttributes, - providerRuntimeEventsTotal, - providerSessionsTotal, - providerTurnDuration, - providerTurnsTotal, - providerTurnMetricAttributes, - withMetrics, -} from "../../observability/Metrics.ts"; -import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts"; -import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; -import * as ProviderAdapterRegistry from "../Services/ProviderAdapterRegistry.ts"; -import * as ProviderService from "../Services/ProviderService.ts"; -import * as ProviderSessionDirectory from "../Services/ProviderSessionDirectory.ts"; -import { type EventNdjsonLogger } from "./EventNdjsonLogger.ts"; -import * as ProviderEventLoggers from "./ProviderEventLoggers.ts"; -import * as AnalyticsService from "../../telemetry/AnalyticsService.ts"; -import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; -import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts"; -const isModelSelection = Schema.is(ModelSelection); - -/** - * Hook for tests that want to override the canonical event logger pulled - * from `ProviderEventLoggers`. Production wiring leaves this undefined and - * reads the logger off the tag. - */ -export interface ProviderServiceLiveOptions { - readonly canonicalEventLogger?: EventNdjsonLogger; -} - -type ProviderServiceMethod = - ProviderService.ProviderService["Service"][Name]; - -const ProviderRollbackConversationInput = Schema.Struct({ - threadId: ThreadId, - numTurns: NonNegativeInt, -}); - -function toValidationError( - operation: string, - issue: string, - cause?: unknown, -): ProviderValidationError { - return new ProviderValidationError({ - operation, - issue, - ...(cause !== undefined ? { cause } : {}), - }); -} - -const decodeInputOrValidationError = (input: { - readonly operation: string; - readonly schema: S; - readonly payload: unknown; -}) => { - const decodeProviderRequestInput = Schema.decodeUnknownEffect(input.schema); - return decodeProviderRequestInput(input.payload).pipe( - Effect.mapError( - (schemaError) => - new ProviderValidationError({ - operation: input.operation, - issue: SchemaIssue.makeFormatterDefault()(schemaError.issue), - cause: schemaError, - }), - ), - ); -}; - -function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "stopped" | "error" { - switch (session.status) { - case "connecting": - return "starting"; - case "error": - return "error"; - case "closed": - return "stopped"; - case "ready": - case "running": - default: - return "running"; - } -} - -function toRuntimePayloadFromSession( - session: ProviderSession, - extra?: { - readonly modelSelection?: unknown; - readonly lastRuntimeEvent?: string; - readonly lastRuntimeEventAt?: string; - }, -): Record { - return { - cwd: session.cwd ?? null, - model: session.model ?? null, - activeTurnId: session.activeTurnId ?? null, - lastError: session.lastError ?? null, - ...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}), - ...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}), - ...(extra?.lastRuntimeEventAt !== undefined - ? { lastRuntimeEventAt: extra.lastRuntimeEventAt } - : {}), - }; -} - -function readPersistedModelSelection( - runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"], -): ModelSelection | undefined { - if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) { - return undefined; - } - const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined; - return isModelSelection(raw) ? raw : undefined; -} - -function readPersistedCwd( - runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding["runtimePayload"], -): string | undefined { - if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) { - return undefined; - } - const rawCwd = "cwd" in runtimePayload ? runtimePayload.cwd : undefined; - if (typeof rawCwd !== "string") return undefined; - const trimmed = rawCwd.trim(); - return trimmed.length > 0 ? trimmed : undefined; -} - -const dieOnMissingBindingInstanceId = ( - operation: string, - payload: { - readonly providerInstanceId?: ProviderInstanceId | undefined; - readonly provider?: ProviderDriverKind | undefined; - }, -): ProviderInstanceId => { - if (payload.providerInstanceId !== undefined) { - return payload.providerInstanceId; - } - throw new Error( - payload.provider - ? `${operation}: provider instance id is required for provider '${payload.provider}'.` - : `${operation}: provider instance id is required.`, - ); -}; - -const correlateRuntimeEventWithInstance = ( - source: { - readonly instanceId: ProviderInstanceId; - readonly provider: ProviderDriverKind; - }, - event: ProviderRuntimeEvent, -): ProviderRuntimeEvent => { - if (event.provider !== source.provider) { - throw new Error( - `ProviderService.streamEvents: provider instance '${source.instanceId}' is backed by driver '${source.provider}' but emitted driver '${event.provider}'.`, - ); - } - if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) { - throw new Error( - `ProviderService.streamEvents: provider instance '${source.instanceId}' emitted event for instance '${event.providerInstanceId}'.`, - ); - } - return { ...event, providerInstanceId: source.instanceId }; -}; - -const makeProviderService = Effect.fn("makeProviderService")(function* ( - options?: ProviderServiceLiveOptions, -) { - const analytics = yield* Effect.service(AnalyticsService.AnalyticsService); - const serverConfig = yield* ServerConfig.ServerConfig; - const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers; - // Options-provided logger wins (test overrides); otherwise we take whatever - // the `ProviderEventLoggers` tag exposes — `undefined` means "no canonical - // log writer is attached", which downstream code already handles as a - // no-op. - const canonicalEventLogger = options?.canonicalEventLogger ?? eventLoggers.canonical; - - const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry; - const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory; - const runtimeEventPubSub = yield* PubSub.unbounded(); - const nowIso = Effect.map(DateTime.now, DateTime.formatIso); - const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => - McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe( - Effect.tap((credential) => - credential - ? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config)) - : Effect.void, - ), - ); - const clearMcpSession = (threadId: ThreadId) => - McpSessionRegistry.revokeActiveMcpThread(threadId).pipe( - Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))), - ); - - const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect => - Effect.succeed(event).pipe( - Effect.tap((canonicalEvent) => - canonicalEventLogger - ? canonicalEventLogger.write(canonicalEvent, canonicalEvent.threadId) - : Effect.void, - ), - Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)), - Effect.asVoid, - ); - - const requireBindingInstanceId = ( - operation: string, - payload: { - readonly providerInstanceId?: ProviderInstanceId | undefined; - readonly provider?: ProviderDriverKind | undefined; - }, - ): Effect.Effect => - payload.providerInstanceId !== undefined - ? Effect.succeed(payload.providerInstanceId) - : Effect.fail( - toValidationError( - operation, - payload.provider - ? `Provider instance id is required for provider '${payload.provider}'.` - : "Provider instance id is required.", - ), - ); - - const upsertSessionBinding = ( - session: ProviderSession, - threadId: ThreadId, - extra?: { - readonly modelSelection?: unknown; - readonly lastRuntimeEvent?: string; - readonly lastRuntimeEventAt?: string; - }, - ) => - Effect.gen(function* () { - const providerInstanceId = yield* requireBindingInstanceId( - "ProviderService.upsertSessionBinding", - session, - ); - yield* directory.upsert({ - threadId, - provider: session.provider, - providerInstanceId, - runtimeMode: session.runtimeMode, - status: toRuntimeStatus(session), - ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}), - runtimePayload: toRuntimePayloadFromSession(session, extra), - }); - }); - - const processRuntimeEvent = ( - source: { - readonly instanceId: ProviderInstanceId; - readonly provider: ProviderDriverKind; - }, - event: ProviderRuntimeEvent, - ): Effect.Effect => - Effect.sync(() => correlateRuntimeEventWithInstance(source, event)).pipe( - Effect.flatMap((canonicalEvent) => - increment(providerRuntimeEventsTotal, { - provider: canonicalEvent.provider, - eventType: canonicalEvent.type, - }).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))), - ), - ); - - // `subscribedAdapters` is our source-of-truth for "which instance adapters - // are currently wired into the runtime event bus". It both tracks the set - // of live subscriptions (so `reconcileInstanceSubscriptions` can diff and - // fork only the *new* or *rebuilt* ones) and serves as the dynamic adapter - // list consumed by `stopStaleSessionsForThread`, `listSessions`, and - // `runStopAll` — replacing the pre-Slice-D startup snapshot so hot-added - // instances become visible to those call sites as soon as settings edits - // land. - const subscribedAdapters = yield* Ref.make( - new Map>(), - ); - - const getAdapterEntries = Ref.get(subscribedAdapters).pipe( - Effect.map((map) => Array.from(map.entries())), - ); - - // Rebuild the map of id → adapter from the registry and fork a new event - // subscription for every instance that is either brand new or whose adapter - // identity changed (indicating the underlying `ProviderInstance` was torn - // down and rebuilt by `ProviderInstanceRegistry.reconcile`). Orphaned - // fibers for removed/replaced instances exit on their own because their - // adapter's `streamEvents` source terminates when the old scope closes. - const reconcileInstanceSubscriptions = Effect.gen(function* () { - const previous = yield* Ref.get(subscribedAdapters); - const currentIds = yield* registry.listInstances(); - const next = new Map>(); - for (const id of currentIds) { - const adapterOption = yield* registry - .getByInstance(id) - .pipe(Effect.tapError(Effect.logWarning), Effect.option); - if (Option.isNone(adapterOption)) continue; - const adapter = adapterOption.value; - next.set(id, adapter); - if (previous.get(id) !== adapter) { - yield* Stream.runForEach(adapter.streamEvents, (event) => - processRuntimeEvent( - { - instanceId: id, - provider: adapter.provider, - }, - event, - ), - ).pipe(Effect.forkScoped); - } - } - yield* Ref.set(subscribedAdapters, next); - }); - - const instanceChanges = yield* registry.subscribeChanges; - yield* reconcileInstanceSubscriptions; - yield* Stream.runForEach( - Stream.fromSubscription(instanceChanges), - () => reconcileInstanceSubscriptions, - ).pipe(Effect.forkScoped); - - const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: { - readonly binding: ProviderSessionDirectory.ProviderRuntimeBinding; - readonly operation: string; - }) { - const bindingInstanceId = yield* requireBindingInstanceId(input.operation, input.binding); - yield* Effect.annotateCurrentSpan({ - "provider.operation": "recover-session", - "provider.kind": input.binding.provider, - "provider.instance_id": bindingInstanceId, - "provider.thread_id": input.binding.threadId, - }); - return yield* Effect.gen(function* () { - const adapter = yield* registry.getByInstance(bindingInstanceId); - const hasResumeCursor = - input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined; - const hasActiveSession = yield* adapter.hasSession(input.binding.threadId); - if (hasActiveSession) { - const activeSessions = yield* adapter.listSessions(); - const existing = activeSessions.find( - (session) => session.threadId === input.binding.threadId, - ); - if (existing) { - yield* upsertSessionBinding( - { ...existing, providerInstanceId: bindingInstanceId }, - input.binding.threadId, - ); - yield* analytics.record("provider.session.recovered", { - provider: existing.provider, - strategy: "adopt-existing", - hasResumeCursor: existing.resumeCursor !== undefined, - }); - return { adapter, session: existing } as const; - } - } - - if (!hasResumeCursor) { - return yield* toValidationError( - input.operation, - `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`, - ); - } - - const persistedCwd = readPersistedCwd(input.binding.runtimePayload); - const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload); - - yield* prepareMcpSession(input.binding.threadId, bindingInstanceId); - const resumed = yield* adapter - .startSession({ - threadId: input.binding.threadId, - provider: input.binding.provider, - providerInstanceId: bindingInstanceId, - ...(persistedCwd ? { cwd: persistedCwd } : {}), - ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}), - ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}), - runtimeMode: input.binding.runtimeMode ?? "full-access", - }) - .pipe(Effect.onError(() => clearMcpSession(input.binding.threadId))); - if (resumed.provider !== adapter.provider) { - yield* clearMcpSession(input.binding.threadId); - return yield* toValidationError( - input.operation, - `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`, - ); - } - - yield* upsertSessionBinding( - { ...resumed, providerInstanceId: bindingInstanceId }, - input.binding.threadId, - ); - yield* analytics.record("provider.session.recovered", { - provider: resumed.provider, - strategy: "resume-thread", - hasResumeCursor: resumed.resumeCursor !== undefined, - }); - return { adapter, session: resumed } as const; - }).pipe( - withMetrics({ - counter: providerSessionsTotal, - attributes: providerMetricAttributes(input.binding.provider, { - operation: "recover", - }), - }), - ); - }); - - const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: { - readonly threadId: ThreadId; - readonly operation: string; - readonly allowRecovery: boolean; - }) { - const bindingOption = yield* directory.getBinding(input.threadId); - const binding = Option.getOrUndefined(bindingOption); - if (!binding) { - return yield* toValidationError( - input.operation, - `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`, - ); - } - const instanceId = yield* requireBindingInstanceId(input.operation, binding); - const adapter = yield* registry.getByInstance(instanceId); - - const hasRequestedSession = yield* adapter.hasSession(input.threadId); - if (hasRequestedSession) { - return { - adapter, - instanceId, - threadId: input.threadId, - runtimeMode: binding.runtimeMode, - isActive: true, - } as const; - } - - if (!input.allowRecovery) { - return { - adapter, - instanceId, - threadId: input.threadId, - runtimeMode: binding.runtimeMode, - isActive: false, - } as const; - } - - const recovered = yield* recoverSessionForThread({ - binding, - operation: input.operation, - }); - return { - adapter: recovered.adapter, - instanceId, - threadId: input.threadId, - runtimeMode: recovered.session.runtimeMode, - isActive: true, - } as const; - }); - - const stopStaleSessionsForThread = Effect.fn("stopStaleSessionsForThread")(function* (input: { - readonly threadId: ThreadId; - readonly currentInstanceId: ProviderInstanceId; - }) { - const currentAdapters = yield* getAdapterEntries; - yield* Effect.forEach( - currentAdapters, - ([instanceId, adapter]) => - instanceId === input.currentInstanceId - ? Effect.void - : Effect.gen(function* () { - const hasSession = yield* adapter.hasSession(input.threadId); - if (!hasSession) { - return; - } - - yield* adapter.stopSession(input.threadId).pipe( - Effect.tap(() => - analytics.record("provider.session.stopped", { - provider: adapter.provider, - }), - ), - Effect.catchCause((cause) => - Effect.logWarning("provider.session.stop-stale-failed", { - threadId: input.threadId, - provider: adapter.provider, - cause, - }), - ), - ); - }), - { discard: true }, - ); - }); - - const startSession: ProviderServiceMethod<"startSession"> = Effect.fn("startSession")( - function* (threadId, rawInput) { - const parsed = yield* decodeInputOrValidationError({ - operation: "ProviderService.startSession", - schema: ProviderSessionStartInput, - payload: rawInput, - }); - - const resolvedInstanceId = yield* requireBindingInstanceId( - "ProviderService.startSession", - parsed, - ); - let metricProvider = parsed.provider ?? String(resolvedInstanceId); - yield* Effect.annotateCurrentSpan({ - "provider.operation": "start-session", - "provider.instance_id": resolvedInstanceId, - "provider.thread_id": threadId, - "provider.runtime_mode": parsed.runtimeMode, - }); - return yield* Effect.gen(function* () { - const instanceInfo = yield* registry.getInstanceInfo(resolvedInstanceId); - const resolvedProvider = instanceInfo.driverKind; - metricProvider = resolvedProvider; - if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) { - return yield* toValidationError( - "ProviderService.startSession", - `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`, - ); - } - const input = { - ...parsed, - threadId, - provider: resolvedProvider, - }; - if (!instanceInfo.enabled) { - return yield* toValidationError( - "ProviderService.startSession", - `Provider instance '${resolvedInstanceId}' is disabled in T3 Code settings.`, - ); - } - const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId)); - const effectiveResumeCursor = - input.resumeCursor ?? - (persistedBinding?.providerInstanceId === resolvedInstanceId - ? persistedBinding.resumeCursor - : undefined); - const effectiveCwd = - input.cwd ?? - (persistedBinding?.providerInstanceId === resolvedInstanceId - ? readPersistedCwd(persistedBinding.runtimePayload) - : undefined); - yield* Effect.annotateCurrentSpan({ - "provider.kind": resolvedProvider, - "provider.resume_cursor.source": - input.resumeCursor !== undefined - ? "request" - : effectiveResumeCursor !== undefined && - persistedBinding?.providerInstanceId === resolvedInstanceId - ? "persisted" - : "none", - "provider.resume_cursor.present": effectiveResumeCursor !== undefined, - "provider.cwd.source": - input.cwd !== undefined - ? "request" - : effectiveCwd !== undefined && - persistedBinding?.providerInstanceId === resolvedInstanceId - ? "persisted" - : "none", - "provider.cwd.effective": effectiveCwd ?? "", - }); - const adapter = yield* registry.getByInstance(resolvedInstanceId); - yield* prepareMcpSession(threadId, resolvedInstanceId); - const session = yield* adapter - .startSession({ - ...input, - providerInstanceId: resolvedInstanceId, - ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}), - ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), - }) - .pipe(Effect.onError(() => clearMcpSession(threadId))); - - if (session.provider !== adapter.provider) { - yield* clearMcpSession(threadId); - return yield* toValidationError( - "ProviderService.startSession", - `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`, - ); - } - const sessionWithInstance = { - ...session, - providerInstanceId: resolvedInstanceId, - }; - - yield* stopStaleSessionsForThread({ - threadId, - currentInstanceId: resolvedInstanceId, - }); - yield* upsertSessionBinding(sessionWithInstance, threadId, { - modelSelection: input.modelSelection, - }); - yield* analytics.record("provider.session.started", { - provider: sessionWithInstance.provider, - runtimeMode: input.runtimeMode, - hasResumeCursor: sessionWithInstance.resumeCursor !== undefined, - hasCwd: typeof effectiveCwd === "string" && effectiveCwd.trim().length > 0, - hasModel: - typeof input.modelSelection?.model === "string" && - input.modelSelection.model.trim().length > 0, - }); - - // Changing runtime mode restarts the session, so the transition is only - // observable here, by diffing against the mode the previous session for - // this thread was bound to. Recording it separately is what makes the - // "started supervised, switched to full access" funnel answerable. - const previousRuntimeMode = persistedBinding?.runtimeMode; - if (previousRuntimeMode !== undefined && previousRuntimeMode !== input.runtimeMode) { - yield* analytics.record("provider.runtime_mode.changed", { - provider: sessionWithInstance.provider, - from: previousRuntimeMode, - to: input.runtimeMode, - }); - } - - return sessionWithInstance; - }).pipe( - withMetrics({ - counter: providerSessionsTotal, - attributes: () => - providerMetricAttributes(metricProvider, { - operation: "start", - }), - }), - ); - }, - ); - - const sendTurn: ProviderServiceMethod<"sendTurn"> = Effect.fn("sendTurn")(function* (rawInput) { - const parsed = yield* decodeInputOrValidationError({ - operation: "ProviderService.sendTurn", - schema: ProviderSendTurnInput, - payload: rawInput, - }); - - const attachments = parsed.attachments ?? []; - if (!parsed.input && attachments.length === 0) { - return yield* toValidationError( - "ProviderService.sendTurn", - "Either input text or at least one attachment is required", - ); - } - - // Adapters inline attachment pixels into the model prompt, but the model's - // tools cannot dereference pixels. Appending the on-disk path is what lets - // a turn like "include this screenshot in the PR" copy the actual file. - // This runs after schema decode, so the appended lines are exempt from the - // PROVIDER_SEND_TURN_MAX_INPUT_CHARS check; attachment count is capped, so - // the overhead is bounded. Unresolvable ids are skipped here and surface - // as adapter errors when the file is read for inlining. - const attachmentPathLines = attachments.flatMap((attachment) => { - const attachmentPath = resolveAttachmentPath({ - attachmentsDir: serverConfig.attachmentsDir, - attachment, - }); - return attachmentPath === null - ? [] - : [`[Attached ${attachment.type} "${attachment.name}" is saved at: ${attachmentPath}]`]; - }); - const inputTextWithAttachmentPaths = - attachmentPathLines.length === 0 - ? parsed.input - : [parsed.input, attachmentPathLines.join("\n")] - .filter((part): part is string => typeof part === "string" && part.length > 0) - .join("\n\n"); - - const input = { - ...parsed, - ...(inputTextWithAttachmentPaths !== undefined - ? { input: inputTextWithAttachmentPaths } - : {}), - attachments, - }; - yield* Effect.annotateCurrentSpan({ - "provider.operation": "send-turn", - "provider.thread_id": input.threadId, - "provider.interaction_mode": input.interactionMode, - "provider.attachment_count": input.attachments.length, - }); - let metricProvider = "unknown"; - let metricModel = input.modelSelection?.model; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.sendTurn", - allowRecovery: true, - }); - metricProvider = routed.adapter.provider; - metricModel = input.modelSelection?.model; - yield* Effect.annotateCurrentSpan({ - "provider.kind": routed.adapter.provider, - ...(input.modelSelection?.model ? { "provider.model": input.modelSelection.model } : {}), - }); - // A turn is the clearest sign a session is still alive. The MCP - // credential is minted once at session start and cannot be rotated into - // an already-spawned agent process, so we keep the existing token valid - // rather than issuing a new one: sessions that go a long time between - // browser tool calls used to lose the toolkit outright. - yield* McpSessionRegistry.touchActiveMcpThread(input.threadId); - const turn = yield* routed.adapter.sendTurn(input); - yield* directory.upsert({ - threadId: input.threadId, - provider: routed.adapter.provider, - providerInstanceId: routed.instanceId, - status: "running", - ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}), - runtimePayload: { - ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}), - activeTurnId: turn.turnId, - lastRuntimeEvent: "provider.sendTurn", - lastRuntimeEventAt: yield* nowIso, - }, - }); - yield* analytics.record("provider.turn.sent", { - provider: routed.adapter.provider, - model: input.modelSelection?.model, - interactionMode: input.interactionMode, - // Session-start events alone skew runtime mode toward users who toggle - // often, since every toggle restarts the session. Recording it per turn - // gives a usage-weighted view and lets it cross with interactionMode. - runtimeMode: routed.runtimeMode, - attachmentCount: input.attachments.length, - hasInput: typeof input.input === "string" && input.input.trim().length > 0, - }); - return turn; - }).pipe( - withMetrics({ - counter: providerTurnsTotal, - timer: providerTurnDuration, - attributes: () => - providerTurnMetricAttributes({ - provider: metricProvider, - model: metricModel, - extra: { - operation: "send", - }, - }), - }), - ); - }); - - const interruptTurn: ProviderServiceMethod<"interruptTurn"> = Effect.fn("interruptTurn")( - function* (rawInput) { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.interruptTurn", - schema: ProviderInterruptTurnInput, - payload: rawInput, - }); - let metricProvider = "unknown"; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.interruptTurn", - allowRecovery: true, - }); - metricProvider = routed.adapter.provider; - yield* Effect.annotateCurrentSpan({ - "provider.operation": "interrupt-turn", - "provider.kind": routed.adapter.provider, - "provider.thread_id": input.threadId, - "provider.turn_id": input.turnId, - }); - yield* routed.adapter.interruptTurn(routed.threadId, input.turnId); - yield* analytics.record("provider.turn.interrupted", { - provider: routed.adapter.provider, - }); - }).pipe( - withMetrics({ - counter: providerTurnsTotal, - outcomeAttributes: () => - providerMetricAttributes(metricProvider, { - operation: "interrupt", - }), - }), - ); - }, - ); - - const respondToRequest: ProviderServiceMethod<"respondToRequest"> = Effect.fn("respondToRequest")( - function* (rawInput) { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.respondToRequest", - schema: ProviderRespondToRequestInput, - payload: rawInput, - }); - let metricProvider = "unknown"; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.respondToRequest", - allowRecovery: true, - }); - metricProvider = routed.adapter.provider; - yield* Effect.annotateCurrentSpan({ - "provider.operation": "respond-to-request", - "provider.kind": routed.adapter.provider, - "provider.thread_id": input.threadId, - "provider.request_id": input.requestId, - }); - yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision); - yield* analytics.record("provider.request.responded", { - provider: routed.adapter.provider, - decision: input.decision, - }); - }).pipe( - withMetrics({ - counter: providerTurnsTotal, - outcomeAttributes: () => - providerMetricAttributes(metricProvider, { - operation: "approval-response", - }), - }), - ); - }, - ); - - const respondToUserInput: ProviderServiceMethod<"respondToUserInput"> = Effect.fn( - "respondToUserInput", - )(function* (rawInput) { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.respondToUserInput", - schema: ProviderRespondToUserInputInput, - payload: rawInput, - }); - let metricProvider = "unknown"; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.respondToUserInput", - allowRecovery: true, - }); - metricProvider = routed.adapter.provider; - yield* Effect.annotateCurrentSpan({ - "provider.operation": "respond-to-user-input", - "provider.kind": routed.adapter.provider, - "provider.thread_id": input.threadId, - "provider.request_id": input.requestId, - }); - yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers); - }).pipe( - withMetrics({ - counter: providerTurnsTotal, - outcomeAttributes: () => - providerMetricAttributes(metricProvider, { - operation: "user-input-response", - }), - }), - ); - }); - - const stopSession: ProviderServiceMethod<"stopSession"> = Effect.fn("stopSession")( - function* (rawInput) { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.stopSession", - schema: ProviderStopSessionInput, - payload: rawInput, - }); - let metricProvider = "unknown"; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.stopSession", - allowRecovery: false, - }); - metricProvider = routed.adapter.provider; - yield* Effect.annotateCurrentSpan({ - "provider.operation": "stop-session", - "provider.kind": routed.adapter.provider, - "provider.thread_id": input.threadId, - }); - if (routed.isActive) { - yield* routed.adapter.stopSession(routed.threadId); - } - yield* clearMcpSession(input.threadId); - yield* directory.upsert({ - threadId: input.threadId, - provider: routed.adapter.provider, - providerInstanceId: routed.instanceId, - status: "stopped", - runtimePayload: { - activeTurnId: null, - }, - }); - yield* analytics.record("provider.session.stopped", { - provider: routed.adapter.provider, - }); - }).pipe( - withMetrics({ - counter: providerSessionsTotal, - outcomeAttributes: () => - providerMetricAttributes(metricProvider, { - operation: "stop", - }), - }), - ); - }, - ); - - const listSessions: ProviderServiceMethod<"listSessions"> = Effect.fn("listSessions")( - function* () { - const currentAdapters = yield* getAdapterEntries; - const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) => - adapter.listSessions().pipe( - Effect.map((sessions) => - sessions.map((session) => ({ - ...session, - providerInstanceId: instanceId, - })), - ), - ), - ); - const activeSessions = sessionsByProvider.flatMap((sessions) => sessions); - const persistedBindings = yield* directory.listThreadIds().pipe( - Effect.flatMap((threadIds) => - Effect.forEach( - threadIds, - (threadId) => - directory - .getBinding(threadId) - .pipe( - Effect.orElseSucceed(() => - Option.none(), - ), - ), - { concurrency: "unbounded" }, - ), - ), - Effect.orElseSucceed( - () => [] as Array>, - ), - ); - const bindingsByThreadId = new Map< - ThreadId, - ProviderSessionDirectory.ProviderRuntimeBinding - >(); - for (const bindingOption of persistedBindings) { - const binding = Option.getOrUndefined(bindingOption); - if (binding) { - bindingsByThreadId.set(binding.threadId, binding); - } - } - - const sessions: ProviderSession[] = []; - for (const session of activeSessions) { - const binding = bindingsByThreadId.get(session.threadId); - if (!binding) { - sessions.push(session); - continue; - } - - const overrides: { - resumeCursor?: ProviderSession["resumeCursor"]; - runtimeMode?: ProviderSession["runtimeMode"]; - providerInstanceId?: ProviderSession["providerInstanceId"]; - } = {}; - overrides.providerInstanceId = dieOnMissingBindingInstanceId( - "ProviderService.listSessions", - binding, - ); - if (binding.provider !== session.provider) { - return yield* Effect.die( - new Error( - `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`, - ), - ); - } - if (overrides.providerInstanceId !== session.providerInstanceId) { - return yield* Effect.die( - new Error( - `ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`, - ), - ); - } - if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) { - overrides.resumeCursor = binding.resumeCursor; - } - if (binding.runtimeMode !== undefined) { - overrides.runtimeMode = binding.runtimeMode; - } - sessions.push(Object.assign({}, session, overrides)); - } - return sessions; - }, - ); - - const getCapabilities: ProviderServiceMethod<"getCapabilities"> = (instanceId) => - registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities)); - - const getInstanceInfo: ProviderServiceMethod<"getInstanceInfo"> = (instanceId) => - registry.getInstanceInfo(instanceId); - - const rollbackConversation: ProviderServiceMethod<"rollbackConversation"> = Effect.fn( - "rollbackConversation", - )(function* (rawInput) { - const input = yield* decodeInputOrValidationError({ - operation: "ProviderService.rollbackConversation", - schema: ProviderRollbackConversationInput, - payload: rawInput, - }); - if (input.numTurns === 0) { - return; - } - let metricProvider = "unknown"; - return yield* Effect.gen(function* () { - const routed = yield* resolveRoutableSession({ - threadId: input.threadId, - operation: "ProviderService.rollbackConversation", - allowRecovery: true, - }); - metricProvider = routed.adapter.provider; - yield* Effect.annotateCurrentSpan({ - "provider.operation": "rollback-conversation", - "provider.kind": routed.adapter.provider, - "provider.thread_id": input.threadId, - "provider.rollback_turns": input.numTurns, - }); - yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns); - yield* analytics.record("provider.conversation.rolled_back", { - provider: routed.adapter.provider, - turns: input.numTurns, - }); - }).pipe( - withMetrics({ - counter: providerTurnsTotal, - outcomeAttributes: () => - providerMetricAttributes(metricProvider, { - operation: "rollback", - }), - }), - ); - }); - - const runStopAll = Effect.fn("runStopAll")(function* () { - const threadIds = yield* directory.listThreadIds(); - const currentAdapters = yield* getAdapterEntries; - const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) => - adapter.listSessions().pipe( - Effect.map((sessions) => - sessions.map((session) => ({ - ...session, - providerInstanceId: instanceId, - })), - ), - ), - ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions))); - yield* Effect.forEach(activeSessions, (session) => - Effect.flatMap(nowIso, (lastRuntimeEventAt) => - upsertSessionBinding(session, session.threadId, { - lastRuntimeEvent: "provider.stopAll", - lastRuntimeEventAt, - }), - ), - ).pipe(Effect.asVoid); - yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid); - yield* McpSessionRegistry.revokeAllActiveMcpCredentials(); - McpProviderSession.clearAllMcpProviderSessions(); - const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => [])); - yield* Effect.forEach(bindings, (binding) => - Effect.gen(function* () { - const providerInstanceId = dieOnMissingBindingInstanceId( - "ProviderService.stopAll", - binding, - ); - return yield* directory.upsert({ - threadId: binding.threadId, - provider: binding.provider, - providerInstanceId, - status: "stopped", - runtimePayload: { - activeTurnId: null, - lastRuntimeEvent: "provider.stopAll", - lastRuntimeEventAt: yield* nowIso, - }, - }); - }), - ).pipe(Effect.asVoid); - yield* analytics.record("provider.sessions.stopped_all", { - sessionCount: threadIds.length, - }); - yield* analytics.flush; - }); - - yield* Effect.addFinalizer(() => - runStopAll().pipe( - Effect.catchCause((cause) => - Effect.logWarning("failed to stop provider service", { - errorTag: causeErrorTag(cause), - }), - ), - ), - ); - - return { - startSession, - sendTurn, - interruptTurn, - respondToRequest, - respondToUserInput, - stopSession, - listSessions, - getCapabilities, - getInstanceInfo, - rollbackConversation, - // Each access creates a fresh PubSub subscription so that multiple - // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each - // independently receive all runtime events. - get streamEvents(): ProviderServiceMethod<"streamEvents"> { - return Stream.fromPubSub(runtimeEventPubSub); - }, - } satisfies ProviderService.ProviderService["Service"]; -}); - -export const ProviderServiceLive = Layer.effect( - ProviderService.ProviderService, - makeProviderService(), -); - -export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) { - return Layer.effect(ProviderService.ProviderService, makeProviderService(options)); -} diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts deleted file mode 100644 index 1281b2f70f..0000000000 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ /dev/null @@ -1,638 +0,0 @@ -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { - ProjectId, - ThreadId, - TurnId, - ProviderDriverKind, - ProviderInstanceId, -} from "@t3tools/contracts"; -import * as Clock from "effect/Clock"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Layer from "effect/Layer"; -import * as ManagedRuntime from "effect/ManagedRuntime"; -import * as Option from "effect/Option"; -import * as Scope from "effect/Scope"; -import * as Stream from "effect/Stream"; -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; - -import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts"; -import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; -import * as ProviderSessionRuntime from "../../persistence/ProviderSessionRuntime.ts"; -import { ProviderValidationError } from "../Errors.ts"; -import { ProviderSessionReaper } from "../Services/ProviderSessionReaper.ts"; -import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts"; -import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts"; -import { makeProviderSessionReaperLive } from "./ProviderSessionReaper.ts"; - -const defaultModelSelection = { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", -} as const; - -async function waitFor( - predicate: () => boolean | Promise, - timeoutMs = 2_000, -): Promise { - const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs; - const poll = async (): Promise => { - if (await predicate()) { - return; - } - if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) { - throw new Error("Timed out waiting for expectation."); - } - await Effect.runPromise(Effect.yieldNow); - return poll(); - }; - - return poll(); -} - -const drainFibers = Effect.forEach(Array.from({ length: 10 }), () => Effect.yieldNow, { - discard: true, -}); - -const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; - -function makeReadModel( - threads: ReadonlyArray<{ - readonly id: ThreadId; - readonly session: { - readonly threadId: ThreadId; - readonly status: "starting" | "running" | "ready" | "interrupted" | "stopped" | "error"; - readonly providerName: "codex" | "claudeAgent"; - readonly runtimeMode: "approval-required" | "full-access" | "auto-accept-edits"; - readonly activeTurnId: TurnId | null; - readonly lastError: string | null; - readonly updatedAt: string; - } | null; - readonly backgroundLiveness?: "working" | "monitoring" | null; - }>, -) { - const now = "2026-01-01T00:00:00.000Z"; - const projectId = ProjectId.make("project-provider-session-reaper"); - - return { - snapshotSequence: 0, - updatedAt: now, - projects: [ - { - id: projectId, - title: "Provider Reaper Project", - workspaceRoot: "/tmp/provider-reaper-project", - defaultModelSelection, - scripts: [], - createdAt: now, - updatedAt: now, - deletedAt: null, - }, - ], - threads: threads.map((thread) => ({ - id: thread.id, - projectId, - title: `Thread ${thread.id}`, - modelSelection: defaultModelSelection, - interactionMode: "default" as const, - runtimeMode: "full-access" as const, - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - latestUserMessageAt: null, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - latestTurn: null, - messages: [], - session: thread.session, - backgroundLiveness: thread.backgroundLiveness ?? null, - activities: [], - proposedPlans: [], - checkpoints: [], - deletedAt: null, - })), - }; -} - -describe("ProviderSessionReaper", () => { - let runtime: ManagedRuntime.ManagedRuntime< - ProviderSessionReaper | ProviderSessionRuntime.ProviderSessionRuntimeRepository, - unknown - > | null = null; - let scope: Scope.Closeable | null = null; - - afterEach(async () => { - if (scope) { - await Effect.runPromise(Scope.close(scope, Exit.void)); - } - scope = null; - if (runtime) { - await runtime.dispose(); - } - runtime = null; - }); - - // Shared start sequence so each test adds no manual Effect runners - // (no-manual-effect-runtime-in-tests tracks this file's legacy count). - async function startReaper() { - const reaper = await runtime!.runPromise(Effect.service(ProviderSessionReaper)); - scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reaper.start().pipe(Scope.provide(scope))); - } - - async function createHarness(input: { - readonly readModel: ReturnType; - readonly stopSessionImplementation?: (input: { - readonly threadId: ThreadId; - }) => ReturnType; - }) { - const stoppedThreadIds = new Set(); - const stopSession = vi.fn( - (request) => - (input.stopSessionImplementation - ? input.stopSessionImplementation(request) - : Effect.sync(() => { - stoppedThreadIds.add(request.threadId); - })) as ReturnType, - ); - - const providerService: ProviderServiceShape = { - startSession: () => unsupported(), - sendTurn: () => unsupported(), - interruptTurn: () => unsupported(), - respondToRequest: () => unsupported(), - respondToUserInput: () => unsupported(), - stopSession, - listSessions: () => Effect.succeed([]), - getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }), - getInstanceInfo: (instanceId) => { - const driverKind = ProviderDriverKind.make(String(instanceId)); - return Effect.succeed({ - instanceId, - driverKind, - displayName: undefined, - enabled: true, - continuationIdentity: { - driverKind, - continuationKey: `${driverKind}:instance:${instanceId}`, - }, - }); - }, - rollbackConversation: () => unsupported(), - streamEvents: Stream.empty, - }; - - const runtimeRepositoryLayer = ProviderSessionRuntime.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - ); - const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe( - Layer.provide(runtimeRepositoryLayer), - ); - const layer = makeProviderSessionReaperLive({ - inactivityThresholdMs: 1_000, - sweepIntervalMs: 60_000, - }).pipe( - Layer.provideMerge(providerSessionDirectoryLayer), - Layer.provideMerge(runtimeRepositoryLayer), - Layer.provideMerge(Layer.succeed(ProviderService, providerService)), - Layer.provideMerge( - Layer.succeed(ProjectionSnapshotQuery, { - getCommandReadModel: () => Effect.die("unused"), - getSnapshot: () => Effect.die("unused"), - getShellSnapshot: () => Effect.die("unused"), - getArchivedShellSnapshot: () => Effect.die("unused"), - getSnapshotSequence: () => - Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }), - getCounts: () => Effect.die("unused"), - getActiveProjectByWorkspaceRoot: () => Effect.die("unused"), - getProjectShellById: () => Effect.die("unused"), - getFirstActiveThreadIdByProjectId: () => Effect.die("unused"), - getThreadCheckpointContext: () => Effect.die("unused"), - getFullThreadDiffContext: () => Effect.die("unused"), - getThreadShellById: (threadId) => - Effect.succeed( - input.readModel.threads.find((thread) => thread.id === threadId) - ? Option.some(input.readModel.threads.find((thread) => thread.id === threadId)!) - : Option.none(), - ), - getThreadDetailById: () => Effect.die("unused"), - getThreadDetailSnapshot: () => Effect.die("unused"), - searchThreads: () => Effect.succeed({ matches: [] }), - }), - ), - Layer.provideMerge(NodeServices.layer), - ); - - runtime = ManagedRuntime.make(layer); - return { stopSession, stoppedThreadIds }; - } - - it("reaps stale persisted sessions without active turns", async () => { - const threadId = ThreadId.make("thread-reaper-stale"); - const now = "2026-01-01T00:00:00.000Z"; - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: threadId, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - ]), - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:00:00.000Z", - resumeCursor: { - opaque: "resume-stale", - }, - runtimePayload: null, - }), - ); - - await startReaper(); - - await waitFor(() => harness.stopSession.mock.calls.length === 1); - - expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ threadId }); - expect(harness.stoppedThreadIds.has(threadId)).toBe(true); - }); - - it("skips stale sessions when the thread still has an active turn", async () => { - const threadId = ThreadId.make("thread-reaper-active-turn"); - const turnId = TurnId.make("turn-reaper-active"); - const now = "2026-01-01T00:00:00.000Z"; - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: threadId, - session: { - threadId, - status: "running", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: turnId, - lastError: null, - updatedAt: now, - }, - }, - ]), - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:00:00.000Z", - resumeCursor: { - opaque: "resume-active-turn", - }, - runtimePayload: null, - }), - ); - - await startReaper(); - await Effect.runPromise(drainFibers); - - expect(harness.stopSession).not.toHaveBeenCalled(); - const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId })); - expect(Option.isSome(remaining)).toBe(true); - }); - - it("skips stale sessions while background work is still live", async () => { - const threadId = ThreadId.make("thread-reaper-background-work"); - const now = "2026-01-01T00:00:00.000Z"; - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: threadId, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - backgroundLiveness: "working", - }, - ]), - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:00:00.000Z", - resumeCursor: { - opaque: "resume-background-work", - }, - runtimePayload: null, - }), - ); - - await startReaper(); - await Effect.runPromise(drainFibers); - - expect(harness.stopSession).not.toHaveBeenCalled(); - const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId })); - expect(Option.isSome(remaining)).toBe(true); - }); - - it("does not reap sessions that are still within the inactivity threshold", async () => { - const threadId = ThreadId.make("thread-reaper-fresh"); - const now = DateTime.formatIso(await Effect.runPromise(DateTime.now)); - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: threadId, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - ]), - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: now, - resumeCursor: { - opaque: "resume-fresh", - }, - runtimePayload: null, - }), - ); - - await startReaper(); - await Effect.runPromise(drainFibers); - - expect(harness.stopSession).not.toHaveBeenCalled(); - const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId })); - expect(Option.isSome(remaining)).toBe(true); - }); - - it("skips persisted sessions that are already marked stopped", async () => { - const threadId = ThreadId.make("thread-reaper-stopped"); - const now = "2026-01-01T00:00:00.000Z"; - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: threadId, - session: { - threadId, - status: "stopped", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - ]), - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "stopped", - lastSeenAt: "2026-04-14T00:00:00.000Z", - resumeCursor: { - opaque: "resume-stopped", - }, - runtimePayload: null, - }), - ); - - await startReaper(); - await Effect.runPromise(drainFibers); - - expect(harness.stopSession).not.toHaveBeenCalled(); - const remaining = await runtime!.runPromise(repository.getByThreadId({ threadId })); - expect(Option.isSome(remaining)).toBe(true); - }); - - it("continues reaping other sessions when one stop attempt fails", async () => { - const failedThreadId = ThreadId.make("thread-reaper-stop-failure"); - const reapedThreadId = ThreadId.make("thread-reaper-stop-success"); - const now = "2026-01-01T00:00:00.000Z"; - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: failedThreadId, - session: { - threadId: failedThreadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - { - id: reapedThreadId, - session: { - threadId: reapedThreadId, - status: "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - ]), - stopSessionImplementation: (request) => - request.threadId === failedThreadId - ? Effect.fail( - new ProviderValidationError({ - operation: "ProviderSessionReaper.test", - issue: "simulated stop failure", - }), - ) - : Effect.void, - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId: failedThreadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:00:00.000Z", - resumeCursor: { - opaque: "resume-failure", - }, - runtimePayload: null, - }), - ); - await runtime!.runPromise( - repository.upsert({ - threadId: reapedThreadId, - providerName: "codex", - providerInstanceId: null, - adapterKey: "codex", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:01:00.000Z", - resumeCursor: { - opaque: "resume-success", - }, - runtimePayload: null, - }), - ); - - await startReaper(); - - await waitFor(() => harness.stopSession.mock.calls.length === 2); - - expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([ - failedThreadId, - reapedThreadId, - ]); - }); - - it("continues reaping other sessions when one stop attempt defects", async () => { - const defectThreadId = ThreadId.make("thread-reaper-stop-defect"); - const reapedThreadId = ThreadId.make("thread-reaper-stop-after-defect"); - const now = "2026-01-01T00:00:00.000Z"; - const harness = await createHarness({ - readModel: makeReadModel([ - { - id: defectThreadId, - session: { - threadId: defectThreadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - { - id: reapedThreadId, - session: { - threadId: reapedThreadId, - status: "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }, - ]), - stopSessionImplementation: (request) => - request.threadId === defectThreadId - ? Effect.die(new Error("simulated stop defect")) - : Effect.void, - }); - const repository = await runtime!.runPromise( - Effect.service(ProviderSessionRuntime.ProviderSessionRuntimeRepository), - ); - - await runtime!.runPromise( - repository.upsert({ - threadId: defectThreadId, - providerName: "claudeAgent", - providerInstanceId: null, - adapterKey: "claudeAgent", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:00:00.000Z", - resumeCursor: { - opaque: "resume-defect", - }, - runtimePayload: null, - }), - ); - await runtime!.runPromise( - repository.upsert({ - threadId: reapedThreadId, - providerName: "codex", - providerInstanceId: null, - adapterKey: "codex", - runtimeMode: "full-access", - status: "running", - lastSeenAt: "2026-04-14T00:01:00.000Z", - resumeCursor: { - opaque: "resume-after-defect", - }, - runtimePayload: null, - }), - ); - - await startReaper(); - - await waitFor(() => harness.stopSession.mock.calls.length === 2); - - expect(harness.stopSession.mock.calls.map(([request]) => request.threadId)).toEqual([ - defectThreadId, - reapedThreadId, - ]); - }); -}); diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.ts deleted file mode 100644 index 15d4f925c3..0000000000 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.ts +++ /dev/null @@ -1,152 +0,0 @@ -import * as Clock from "effect/Clock"; -import * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import * as Schedule from "effect/Schedule"; - -import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts"; -import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; -import { - ProviderSessionReaper, - type ProviderSessionReaperShape, -} from "../Services/ProviderSessionReaper.ts"; -import { forkParked } from "../../serverActivation.ts"; -import { ProviderService } from "../Services/ProviderService.ts"; - -const DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000; -const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000; - -export interface ProviderSessionReaperLiveOptions { - readonly inactivityThresholdMs?: number; - readonly sweepIntervalMs?: number; -} - -const makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) => - Effect.gen(function* () { - const providerService = yield* ProviderService; - const directory = yield* ProviderSessionDirectory; - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - - const inactivityThresholdMs = Math.max( - 1, - options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS, - ); - const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS); - - const sweep = Effect.gen(function* () { - const bindings = yield* directory.listBindings(); - const now = yield* Clock.currentTimeMillis; - let reapedCount = 0; - - for (const binding of bindings) { - if (binding.status === "stopped") { - continue; - } - - const lastSeenMs = Date.parse(binding.lastSeenAt); - if (Number.isNaN(lastSeenMs)) { - yield* Effect.logWarning("provider.session.reaper.invalid-last-seen", { - threadId: binding.threadId, - provider: binding.provider, - lastSeenAt: binding.lastSeenAt, - }); - continue; - } - - const idleDurationMs = now - lastSeenMs; - if (idleDurationMs < inactivityThresholdMs) { - continue; - } - - const thread = yield* projectionSnapshotQuery - .getThreadShellById(binding.threadId) - .pipe(Effect.map(Option.getOrUndefined)); - if (thread?.session?.activeTurnId != null) { - yield* Effect.logDebug("provider.session.reaper.skipped-active-turn", { - threadId: binding.threadId, - activeTurnId: thread.session.activeTurnId, - idleDurationMs, - }); - continue; - } - - // The turn can settle while background work runs on (subagent - // fleets, workflow runs, Monitor watch loops). Those live inside the - // provider process, so stopping the session would kill them silently, - // and nothing bumps lastSeenAt between turns. - if (thread?.backgroundLiveness != null) { - yield* Effect.logDebug("provider.session.reaper.skipped-background-work", { - threadId: binding.threadId, - backgroundLiveness: thread.backgroundLiveness, - idleDurationMs, - }); - continue; - } - - const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe( - Effect.tap(() => - Effect.logInfo("provider.session.reaped", { - threadId: binding.threadId, - provider: binding.provider, - idleDurationMs, - reason: "inactivity_threshold", - }), - ), - Effect.as(true), - Effect.catchCause((cause) => - Effect.logWarning("provider.session.reaper.stop-failed", { - threadId: binding.threadId, - provider: binding.provider, - idleDurationMs, - cause, - }).pipe(Effect.as(false)), - ), - ); - - if (reaped) { - reapedCount += 1; - } - } - - if (reapedCount > 0) { - yield* Effect.logInfo("provider.session.reaper.sweep-complete", { - reapedCount, - totalBindings: bindings.length, - }); - } - }); - - const start: ProviderSessionReaperShape["start"] = () => - Effect.gen(function* () { - yield* forkParked( - sweep.pipe( - Effect.catch((error: unknown) => - Effect.logWarning("provider.session.reaper.sweep-failed", { - error, - }), - ), - Effect.catchDefect((defect: unknown) => - Effect.logWarning("provider.session.reaper.sweep-defect", { - defect, - }), - ), - Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))), - ), - ); - - yield* Effect.logInfo("provider.session.reaper.started", { - inactivityThresholdMs, - sweepIntervalMs, - }); - }); - - return { - start, - } satisfies ProviderSessionReaperShape; - }); - -export const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) => - Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options)); - -export const ProviderSessionReaperLive = makeProviderSessionReaperLive(); diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts deleted file mode 100644 index e4019c336e..0000000000 --- a/apps/server/src/server.test.ts +++ /dev/null @@ -1,8072 +0,0 @@ -import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; -import * as NodeSocket from "@effect/platform-node/NodeSocket"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as NodeCrypto from "node:crypto"; -import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; - -import { - AuthAccessTokenType, - AuthEnvironmentBootstrapTokenType, - AuthTokenExchangeGrantType, - CommandId, - DEFAULT_SERVER_SETTINGS, - EnvironmentId, - EventId, - GitCommandError, - KeybindingRule, - MessageId, - OpenError, - ORCHESTRATION_V2_WS_METHODS, - type OrchestrationThreadShell, - TerminalNotRunningError, - type OrchestrationCommand, - type OrchestrationEvent, - type OrchestrationV2ShellStreamItem, - type OrchestrationV2ThreadStreamItem, - ORCHESTRATION_WS_METHODS, - type ProviderKind, - ProjectId, - ProviderDriverKind, - ProviderInstanceId, - ResolvedKeybindingRule, - ThreadId, - WS_METHODS, - WsRpcGroup, - EditorId, -} from "@t3tools/contracts"; -import { - computeDpopAccessTokenHash, - computeDpopJwkThumbprint, - type DpopPublicJwk, -} from "@t3tools/shared/dpop"; -import { RELAY_HEALTH_REQUEST_TYP, RELAY_MINT_REQUEST_TYP } from "@t3tools/shared/relayJwt"; -import * as RelayClient from "@t3tools/shared/relayClient"; -import { assert, it } from "@effect/vitest"; -import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils"; -import { - Deferred, - Duration, - Effect, - FileSystem, - Fiber, - Layer, - ManagedRuntime, - Option, - Path, - Queue, - Schema, - Stream, -} from "effect"; -import { - FetchHttpClient, - HttpBody, - HttpClient, - HttpClientRequest, - HttpClientResponse, - HttpRouter, - HttpServer, -} from "effect/unstable/http"; -import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; -import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; -import * as Socket from "effect/unstable/socket/Socket"; -import { vi } from "vitest"; -import { readFile } from "node:fs/promises"; - -const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"); - -import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; -import * as ServerConfig from "./config.ts"; -import { makeRoutesLayer } from "./server.ts"; -import { resolveAttachmentRelativePath } from "./attachmentPaths.ts"; -import { - CheckpointDiffQuery, - type CheckpointDiffQueryShape, -} from "./checkpointing/Services/CheckpointDiffQuery.ts"; -import { GitCore, type GitCoreShape } from "./git/Services/GitCore.ts"; -import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts"; -import { GitStatusBroadcasterLive } from "./git/Layers/GitStatusBroadcaster.ts"; -import { - GitStatusBroadcaster, - type GitStatusBroadcasterShape, -} from "./git/Services/GitStatusBroadcaster.ts"; -import { Keybindings, type KeybindingsShape } from "./keybindings.ts"; -import { Open, type OpenShape } from "./open.ts"; -import { - OrchestrationEngineService, - type OrchestrationEngineShape, -} from "./orchestration/Services/OrchestrationEngine.ts"; -import { layerUnavailable as OrchestratorV2UnavailableLayer } from "./orchestration-v2/Orchestrator.ts"; -import { layer as ThreadManagementServiceLayer } from "./orchestration-v2/ThreadManagementService.ts"; -import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts"; -import { - OrchestratorV2, - layerUnavailable as OrchestratorV2Unavailable, -} from "./orchestration-v2/Orchestrator.ts"; -import { CodexOrchestratorReplayHarness } from "./orchestration-v2/Adapters/CodexAdapterV2.testkit.ts"; -import { layer as idAllocatorV2Layer } from "./orchestration-v2/IdAllocator.ts"; -import { provideDeterministicTestRuntime } from "./orchestration-v2/testkit/DeterministicRuntime.ts"; -import { ORCHESTRATOR_REPLAY_FIXTURES } from "./orchestration-v2/testkit/fixtures/index.ts"; -import { materializeFixtureInput } from "./orchestration-v2/testkit/fixtures/shared.ts"; -import { makeOrchestratorV2ProviderReplayLayer } from "./orchestration-v2/testkit/ProviderReplayHarness.ts"; -import { decodeProviderReplayNdjson } from "./orchestration-v2/testkit/ReplayTranscriptNdjson.ts"; -import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts"; -import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts"; -import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts"; -import { PersistenceSqlError } from "./persistence/Errors.ts"; -import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts"; -import { makeManualOnlyProviderMaintenanceCapabilities } from "./provider/providerMaintenance.ts"; -import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; -import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; -import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; -import * as ServerSettings from "./serverSettings.ts"; -import * as TerminalManager from "./terminal/Manager.ts"; -import * as PreviewManager from "./preview/Manager.ts"; -import * as PortScanner from "./preview/PortScanner.ts"; -import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts"; -import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts"; -import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts"; -import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts"; -import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; -import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; -import { layer as mcpSessionRegistryTestLayer } from "./mcp/McpSessionRegistry.testkit.ts"; -import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; -import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts"; -import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; -import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; -import * as VcsDriver from "./vcs/VcsDriver.ts"; -import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; -import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts"; -import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; -import * as GitWorkflowService from "./git/GitWorkflowService.ts"; -import * as ReviewService from "./review/ReviewService.ts"; -import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts"; -import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; -import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; -import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts"; -import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts"; -import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; -import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; -import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; -import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts"; -import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts"; -import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts"; -import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; -import * as UsageService from "./usage/UsageService.ts"; -import * as Data from "effect/Data"; - -const OrchestrationV2UnavailableTestLayer = Layer.merge( - OrchestratorV2UnavailableLayer, - ThreadManagementServiceLayer.pipe(Layer.provide(OrchestratorV2UnavailableLayer)), -); - -const defaultProjectId = ProjectId.make("project-default"); -const defaultThreadId = ThreadId.make("thread-default"); -const defaultDesktopBootstrapToken = "test-desktop-bootstrap-token"; -const defaultModelSelection = { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", -} as const; -const testEnvironmentDescriptor = { - environmentId: EnvironmentId.make("environment-test"), - label: "Test environment", - platform: { - os: "darwin" as const, - arch: "arm64" as const, - }, - serverVersion: "0.0.0-test", - capabilities: { - repositoryIdentity: true, - }, -}; -const makeDefaultOrchestrationReadModel = () => { - const now = "2026-01-01T00:00:00.000Z"; - return { - snapshotSequence: 0, - updatedAt: now, - projects: [ - { - id: defaultProjectId, - title: "Default Project", - workspaceRoot: "/tmp/default-project", - defaultModelSelection, - scripts: [], - createdAt: now, - updatedAt: now, - deletedAt: null, - }, - ], - threads: [ - { - id: defaultThreadId, - projectId: defaultProjectId, - title: "Default Thread", - modelSelection: defaultModelSelection, - interactionMode: "default" as const, - runtimeMode: "full-access" as const, - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - latestTurn: null, - messages: [], - session: null, - activities: [], - proposedPlans: [], - checkpoints: [], - deletedAt: null, - }, - ], - }; -}; - -const makeDefaultOrchestrationThreadShell = ( - overrides: Partial = {}, -): OrchestrationThreadShell => { - const now = "2026-01-01T00:00:00.000Z"; - return { - id: defaultThreadId, - projectId: defaultProjectId, - title: "Default Thread", - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - latestTurn: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - session: null, - latestUserMessageAt: null, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - ...overrides, - }; -}; - -const browserOtlpTracingLayer = Layer.mergeAll( - FetchHttpClient.layer, - OtlpSerialization.layerJson, - Layer.succeed(HttpClient.TracerDisabledWhen, () => true), -); - -const makeAuthTestLayer = () => - EnvironmentAuth.layer.pipe( - Layer.provide(SqlitePersistenceMemory), - Layer.provide(ServerSecretStore.layer), - ); - -const makeBrowserOtlpPayload = (spanName: string) => - Effect.gen(function* () { - const collector = yield* Effect.acquireRelease( - Effect.promise(async () => { - const NodeHttp = await import("node:http"); - - return await new Promise<{ - readonly close: () => Promise; - readonly firstRequest: Promise<{ - readonly body: string; - readonly contentType: string | null; - }>; - readonly url: string; - }>((resolve, reject) => { - let resolveFirstRequest: - | ((request: { readonly body: string; readonly contentType: string | null }) => void) - | undefined; - const firstRequest = new Promise<{ - readonly body: string; - readonly contentType: string | null; - }>((resolveRequest) => { - resolveFirstRequest = resolveRequest; - }); - - const server = NodeHttp.createServer((request, response) => { - const chunks: Buffer[] = []; - request.on("data", (chunk) => { - chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); - }); - request.on("end", () => { - resolveFirstRequest?.({ - body: Buffer.concat(chunks).toString("utf8"), - contentType: request.headers["content-type"] ?? null, - }); - resolveFirstRequest = undefined; - response.statusCode = 204; - response.end(); - }); - }); - - server.on("error", reject); - server.listen(0, "127.0.0.1", () => { - const address = server.address(); - if (!address || typeof address === "string") { - reject(new Error("Expected TCP collector address")); - return; - } - - resolve({ - url: `http://127.0.0.1:${address.port}/v1/traces`, - firstRequest, - close: () => - new Promise((resolveClose, rejectClose) => { - server.close((error) => { - if (error) { - rejectClose(error); - return; - } - resolveClose(); - }); - }), - }); - }); - }); - }), - ({ close }) => Effect.promise(close), - ); - - const runtime = ManagedRuntime.make( - OtlpTracer.layer({ - url: collector.url, - exportInterval: "10 millis", - resource: { - serviceName: "t3-web", - attributes: { - "service.runtime": "t3-web", - "service.mode": "browser", - "service.version": "test", - }, - }, - }).pipe(Layer.provide(browserOtlpTracingLayer)), - ); - - try { - yield* Effect.promise(() => runtime.runPromise(Effect.void.pipe(Effect.withSpan(spanName)))); - } finally { - yield* Effect.promise(() => runtime.dispose()); - } - - const request = yield* Effect.raceFirst( - Effect.promise(() => collector.firstRequest).pipe(Effect.orDie), - Effect.sleep(Duration.seconds(1)).pipe( - Effect.andThen(Effect.die(new Error("Timed out waiting for OTLP trace export"))), - ), - ); - // @effect-diagnostics-next-line preferSchemaOverJson:off - return JSON.parse(request.body) as OtlpTracer.TraceData; - }); - -const buildAppUnderTest = (options?: { - config?: Partial; - layers?: { - keybindings?: Partial; - providerRegistry?: Partial; - serverSettings?: Partial; - open?: Partial; - gitCore?: Partial; - gitManager?: Partial; - gitStatusBroadcaster?: Partial; - projectSetupScriptRunner?: Partial; - terminalManager?: Partial; - orchestrationEngine?: Partial; - projectionSnapshotQuery?: Partial; - checkpointDiffQuery?: Partial; - browserTraceCollector?: Partial; - serverLifecycleEvents?: Partial; - serverRuntimeStartup?: Partial; - serverEnvironment?: Partial; - repositoryIdentityResolver?: Partial; - orchestratorV2?: Layer.Layer; - }; -}) => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const tempBaseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-test-" }); - const baseDir = options?.config?.baseDir ?? tempBaseDir; - const devUrl = options?.config?.devUrl; - const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl); - const config: ServerConfig.ServerConfig["Service"] = { - logLevel: "Info", - traceMinLevel: "Info", - traceTimingEnabled: true, - traceBatchWindowMs: 200, - traceMaxBytes: 10 * 1024 * 1024, - traceMaxFiles: 10, - otlpTracesUrl: undefined, - otlpMetricsUrl: undefined, - otlpExportIntervalMs: 10_000, - otlpServiceName: "t3-server", - mode: "desktop", - port: 0, - host: "127.0.0.1", - cwd: process.cwd(), - baseDir, - ...derivedPaths, - staticDir: undefined, - devUrl, - devAllowedOrigins: [], - noBrowser: true, - startupPresentation: "browser", - desktopBootstrapToken: defaultDesktopBootstrapToken, - autoBootstrapProjectFromCwd: false, - logWebSocketEvents: false, - tailscaleServeEnabled: false, - tailscaleServePort: 443, - ...options?.config, - }; - const layerConfig = ServerConfig.layer(config); - const defaultVcsDriver: VcsDriver.VcsDriver["Service"] = { - capabilities: { - kind: "git", - supportsWorktrees: true, - supportsBookmarks: false, - supportsAtomicSnapshot: false, - supportsPushDefaultRemote: true, - ignoreClassifier: "native", - }, - execute: () => - Effect.succeed({ - exitCode: ChildProcessSpawner.ExitCode(0), - stdout: "", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }), - detectRepository: () => Effect.succeed(null), - isInsideWorkTree: () => Effect.succeed(false), - listWorkspaceFiles: () => - Effect.succeed({ - paths: [], - truncated: false, - freshness: { - source: "live-local", - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - }), - listRemotes: () => - Effect.succeed({ - remotes: [], - freshness: { - source: "live-local", - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - }), - filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths), - initRepository: () => Effect.void, - ...options?.layers?.vcsDriver, - }; - const vcsDriverRegistryLayer = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({ - get: () => Effect.succeed(defaultVcsDriver), - detect: (input) => - defaultVcsDriver.detectRepository(input.cwd).pipe( - Effect.flatMap((repository) => - repository - ? Effect.succeed(repository) - : defaultVcsDriver.isInsideWorkTree(input.cwd).pipe( - Effect.map((isInsideWorkTree) => - isInsideWorkTree - ? { - kind: "git" as const, - rootPath: input.cwd, - metadataPath: null, - freshness: { - source: "live-local" as const, - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - } - : null, - ), - ), - ), - Effect.map((repository) => - repository - ? ({ - kind: repository.kind, - repository, - driver: defaultVcsDriver, - } satisfies VcsDriverRegistry.VcsDriverHandle) - : null, - ), - ), - resolve: (input) => - Effect.succeed({ - kind: - input.requestedKind === "auto" || !input.requestedKind ? "git" : input.requestedKind, - repository: { - kind: - input.requestedKind === "auto" || !input.requestedKind ? "git" : input.requestedKind, - rootPath: input.cwd, - metadataPath: null, - freshness: { - source: "live-local", - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - }, - driver: defaultVcsDriver, - }), - ...options?.layers?.vcsDriverRegistry, - }); - const gitVcsDriverLayer = Layer.mock(GitVcsDriver.GitVcsDriver)({ - ...options?.layers?.gitVcsDriver, - }); - const gitManagerLayer = Layer.mock(GitManager.GitManager)({ - ...options?.layers?.gitManager, - }); - const workspaceEntriesLayer = WorkspaceEntries.layer.pipe( - Layer.provide(WorkspacePaths.layer), - Layer.provideMerge(vcsDriverRegistryLayer), - ); - const workspaceAndProjectServicesLayer = Layer.mergeAll( - WorkspacePaths.layer, - workspaceEntriesLayer, - WorkspaceFileSystem.layer.pipe( - Layer.provide(WorkspacePaths.layer), - Layer.provide(workspaceEntriesLayer), - ), - ProjectFaviconResolver.layer.pipe( - Layer.provide(WorkspacePaths.layer), - Layer.provide(T3ProjectFileLoader.layer), - ), - ); - const gitWorkflowLayer = GitWorkflowService.layer.pipe( - Layer.provideMerge(vcsDriverRegistryLayer), - Layer.provideMerge(gitVcsDriverLayer), - Layer.provideMerge(gitManagerLayer), - ); - const vcsProvisioningLayer = VcsProvisioningService.layer.pipe( - Layer.provide(vcsDriverRegistryLayer), - ); - const reviewLayer = options?.layers?.reviewService - ? Layer.mock(ReviewService.ReviewService)({ - ...options.layers.reviewService, - }) - : ReviewService.layer.pipe( - Layer.provideMerge(gitVcsDriverLayer), - Layer.provide(vcsDriverRegistryLayer), - ); - const vcsStatusBroadcasterLayer = options?.layers?.vcsStatusBroadcaster - ? Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({ - ...options.layers.vcsStatusBroadcaster, - }) - : VcsStatusBroadcaster.layer.pipe(Layer.provide(gitWorkflowLayer)); - const resourceTelemetryLayer = ResourceTelemetry.layer.pipe( - Layer.provide( - Layer.mergeAll( - NativeTelemetryClient.layerTest(options?.layers?.nativeTelemetryClient), - DesktopTelemetryReceiver.layerTest(options?.layers?.desktopTelemetryReceiver), - ResourceAttribution.layer, - ), - ), - ); - - const servedRoutesBaseLayer = HttpRouter.serve(makeRoutesLayer, { - disableListenLog: true, - disableLogger: true, - }).pipe( - Layer.provide( - Layer.merge( - mcpSessionRegistryTestLayer, - Layer.mock(Keybindings.Keybindings)({ - loadConfigState: Effect.succeed({ - keybindings: [], - issues: [], - }), - streamChanges: Stream.empty, - ...options?.layers?.keybindings, - }), - ), - ), - Layer.provide( - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([]), - refresh: () => Effect.succeed([]), - refreshInstance: () => Effect.succeed([]), - getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) => - Effect.succeed( - makeManualOnlyProviderMaintenanceCapabilities({ provider, packageName: null }), - ), - setProviderMaintenanceActionState: () => Effect.succeed([]), - streamChanges: Stream.empty, - ...options?.layers?.providerRegistry, - }), - ), - Layer.provide( - Layer.mock(ServerSettings.ServerSettingsService)({ - start: Effect.void, - ready: Effect.void, - getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS), - updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS), - streamChanges: Stream.empty, - ...options?.layers?.serverSettings, - }), - ), - Layer.provide( - Layer.mock(ExternalLauncher.ExternalLauncher)({ - resolveAvailableEditors: () => Effect.succeed([]), - ...options?.layers?.externalLauncher, - }), - ), - Layer.provide( - Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({ - read: Effect.succeed({ - serverPid: process.pid, - readAt: TEST_EPOCH, - processCount: 0, - totalRssBytes: 0, - totalCpuPercent: 0, - processes: [], - error: Option.none(), - }), - signal: (input) => - Effect.succeed({ - pid: input.pid, - signal: input.signal, - signaled: true, - message: Option.none(), - }), - }), - ), - Layer.provide( - Layer.mock(ProcessResourceMonitor.ProcessResourceMonitor)({ - readHistory: (input) => - Effect.succeed({ - readAt: TEST_EPOCH, - windowMs: input.windowMs, - bucketMs: input.bucketMs, - sampleIntervalMs: 5_000, - retainedSampleCount: 0, - totalCpuSecondsApprox: 0, - buckets: [], - topProcesses: [], - error: Option.none(), - }), - }), - ), - Layer.provide( - Layer.mock(TraceDiagnostics.TraceDiagnostics)({ - read: () => - Effect.succeed({ - traceFilePath: "", - scannedFilePaths: [], - readAt: TEST_EPOCH, - recordCount: 0, - parseErrorCount: 0, - firstSpanAt: Option.none(), - lastSpanAt: Option.none(), - failureCount: 0, - interruptionCount: 0, - slowSpanThresholdMs: 1_000, - slowSpanCount: 0, - logLevelCounts: {}, - topSpansByCount: [], - slowestSpans: [], - commonFailures: [], - latestFailures: [], - latestWarningAndErrorLogs: [], - partialFailure: Option.none(), - error: Option.none(), - }), - }), - ), - Layer.provide(gitManagerLayer), - Layer.provide(gitVcsDriverLayer), - Layer.provide(gitWorkflowLayer), - Layer.provide(reviewLayer), - Layer.provide(vcsProvisioningLayer), - Layer.provide( - Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({ - ...options?.layers?.sourceControlRepositoryService, - }), - ), - Layer.provideMerge(vcsStatusBroadcasterLayer), - Layer.provide( - Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ - runForThread: () => Effect.succeed({ status: "no-script" as const }), - ...options?.layers?.projectSetupScriptRunner, - }), - ), - Layer.provide( - Layer.mergeAll( - Layer.mock(TerminalManager)({ - ...options?.layers?.terminalManager, - }), - Layer.mock(PreviewManager.PreviewManager)({ - open: () => Effect.die("PreviewManager not stubbed in this test"), - navigate: () => Effect.die("PreviewManager not stubbed in this test"), - resize: () => Effect.die("PreviewManager not stubbed in this test"), - reportStatus: () => Effect.void, - refresh: () => Effect.void, - close: () => Effect.void, - list: () => Effect.succeed({ sessions: [], serverEpoch: "test-server", revision: 0 }), - events: Stream.empty, - subscribeEvents: Effect.flatMap(PubSub.unbounded(), (pubsub) => - PubSub.subscribe(pubsub), - ), - }), - Layer.mock(PortScanner.PortDiscovery)({ - scan: () => Effect.succeed([]), - subscribe: () => Effect.void, - retain: Effect.void, - registerTerminalProcesses: () => Effect.void, - unregisterTerminal: () => Effect.void, - }), - ), - ), - Layer.provide( - Layer.mock(OrchestrationEngine.OrchestrationEngineService)({ - readEvents: () => Stream.empty, - dispatch: () => Effect.succeed({ sequence: 0 }), - streamDomainEvents: Stream.empty, - latestSequence: Effect.succeed(0), - ...options?.layers?.orchestrationEngine, - }), - ), - Layer.provide( - Layer.mock(ProjectionSnapshotQuery.ProjectionSnapshotQuery)({ - getCommandReadModel: () => Effect.succeed(makeDefaultOrchestrationReadModel()), - getSnapshot: () => Effect.succeed(makeDefaultOrchestrationReadModel()), - getShellSnapshot: () => - Effect.succeed({ - snapshotSequence: 0, - projects: [], - threads: [], - updatedAt: "1970-01-01T00:00:00.000Z", - }), - getArchivedShellSnapshot: () => - Effect.succeed({ - snapshotSequence: 0, - projects: [], - threads: [], - updatedAt: "1970-01-01T00:00:00.000Z", - }), - searchThreads: () => Effect.succeed({ matches: [] }), - getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }), - getProjectShellById: () => Effect.succeed(Option.none()), - getThreadShellById: () => Effect.succeed(Option.none()), - getThreadDetailById: () => Effect.succeed(Option.none()), - getThreadDetailSnapshot: () => Effect.succeed(Option.none()), - getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), - getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), - getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()), - getThreadCheckpointContext: () => Effect.succeed(Option.none()), - ...options?.layers?.projectionSnapshotQuery, - }), - ), - Layer.provide(options?.layers?.orchestratorV2 ?? OrchestratorV2Unavailable), - Layer.provide( - Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({ - getTurnDiff: () => - Effect.succeed({ - threadId: defaultThreadId, - fromTurnCount: 0, - toTurnCount: 0, - diff: "", - }), - getFullThreadDiff: () => - Effect.succeed({ - threadId: defaultThreadId, - fromTurnCount: 0, - toTurnCount: 0, - diff: "", - }), - ...options?.layers?.checkpointDiffQuery, - }), - ), - ); - - const servedRoutesLayer = servedRoutesBaseLayer.pipe( - Layer.provide(OrchestrationV2UnavailableTestLayer), - ); - - const appLayer = servedRoutesLayer.pipe( - Layer.provide(resourceTelemetryLayer), - Layer.provide(UsageService.layerTest), - Layer.provide( - Layer.mock(BrowserTraceCollector.BrowserTraceCollector)({ - record: () => Effect.void, - ...options?.layers?.browserTraceCollector, - }), - ), - Layer.provide( - Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({ - publish: (event) => Effect.succeed({ ...(event as any), sequence: 1 }), - snapshot: Effect.succeed({ sequence: 0, events: [] }), - stream: Stream.empty, - ...options?.layers?.serverLifecycleEvents, - }), - ), - Layer.provide( - Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({ - awaitCommandReady: Effect.void, - markHttpListening: Effect.void, - enqueueCommand: (effect) => effect, - ...options?.layers?.serverRuntimeStartup, - }), - ), - Layer.provide( - Layer.mock(BackgroundPolicy.BackgroundPolicy)({ - reportClientActivity: () => Effect.void, - removeRpcClient: () => Effect.void, - reportHostPowerState: () => Effect.void, - snapshot: Effect.succeed({ - hostPower: { - source: "unknown", - idle: "unknown", - idleSeconds: null, - locked: "unknown", - suspended: false, - onBattery: "unknown", - lowPowerMode: "unknown", - thermalState: "unknown", - stale: true, - updatedAt: TEST_EPOCH, - }, - leases: [], - activeForegroundLeaseCount: 0, - activeScopeKeys: [], - shouldRunOpportunisticWork: false, - updatedAt: TEST_EPOCH, - }), - streamChanges: Stream.empty, - subscribe: Effect.succeed({ - latest: { - hostPower: { - source: "unknown", - idle: "unknown", - idleSeconds: null, - locked: "unknown", - suspended: false, - onBattery: "unknown", - lowPowerMode: "unknown", - thermalState: "unknown", - stale: true, - updatedAt: TEST_EPOCH, - }, - leases: [], - activeForegroundLeaseCount: 0, - activeScopeKeys: [], - shouldRunOpportunisticWork: false, - updatedAt: TEST_EPOCH, - }, - changes: Stream.empty, - }), - hasDemand: () => Effect.succeed(false), - shouldRunScopeWork: () => Effect.succeed(false), - shouldRunOpportunisticWork: Effect.succeed(false), - }), - ), - Layer.provide( - Layer.mock(ServerEnvironment.ServerEnvironment)({ - getEnvironmentId: Effect.succeed(testEnvironmentDescriptor.environmentId), - getDescriptor: Effect.succeed(testEnvironmentDescriptor), - ...options?.layers?.serverEnvironment, - }), - ), - Layer.provide( - Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({ - resolve: () => Effect.succeed(null), - ...options?.layers?.repositoryIdentityResolver, - }), - ), - Layer.provide( - Layer.succeed( - CloudManagedEndpointRuntime.CloudManagedEndpointRuntime, - CloudManagedEndpointRuntime.CloudManagedEndpointRuntime.of({ - applyConfig: () => Effect.succeed({ status: "disabled" }), - ...options?.layers?.cloudManagedEndpointRuntime, - }), - ), - ), - Layer.provide( - Layer.succeed( - RelayClient.RelayClient, - RelayClient.RelayClient.of({ - resolve: Effect.succeed({ - status: "missing", - version: RelayClient.CLOUDFLARED_VERSION, - }), - install: Effect.die("unused relay-client install"), - installWithProgress: () => Effect.die("unused relay-client install"), - ...options?.layers?.relayClient, - }), - ), - ), - Layer.provide( - Layer.mock(CloudCliTokenManager.CloudCliTokenManager)({ - get: Effect.die(new Error("Unexpected T3 Connect CLI authorization request.")), - getExisting: Effect.succeed(Option.none()), - hasCredential: Effect.succeed(false), - clear: Effect.void, - ...options?.layers?.cloudCliTokenManager, - }), - ), - Layer.provideMerge(makeAuthTestLayer()), - Layer.provideMerge(ServerSecretStore.layer), - Layer.provide(workspaceAndProjectServicesLayer), - Layer.provideMerge(FetchHttpClient.layer), - Layer.provide(layerConfig), - ); - - yield* Layer.build(appLayer); - return config; - }); - -const parseSessionCookieFromWsUrl = ( - wsUrl: string, -): { readonly cookie: string | null; readonly url: string } => { - const next = new URL(wsUrl); - const cookie = next.hash.startsWith("#cookie=") - ? decodeURIComponent(next.hash.slice("#cookie=".length)) - : null; - next.hash = ""; - return { - cookie, - url: next.toString(), - }; -}; - -const wsRpcProtocolLayer = (wsUrl: string) => { - const { cookie, url } = parseSessionCookieFromWsUrl(wsUrl); - const webSocketConstructorLayer = Layer.succeed( - Socket.WebSocketConstructor, - (socketUrl, protocols) => - new NodeSocket.NodeWS.WebSocket( - socketUrl, - protocols, - cookie ? { headers: { cookie } } : undefined, - ) as unknown as globalThis.WebSocket, - ); - - return RpcClient.layerProtocolSocket().pipe( - Layer.provide(Socket.layerWebSocket(url).pipe(Layer.provide(webSocketConstructorLayer))), - Layer.provide(RpcSerialization.layerJson), - ); -}; - -const makeWsRpcClient = RpcClient.make(WsRpcGroup); -type WsRpcClient = - typeof makeWsRpcClient extends Effect.Effect ? Client : never; - -class WsRpcTestTimeoutError extends Schema.TaggedErrorClass()( - "WsRpcTestTimeoutError", - { - label: Schema.String, - cause: Schema.optional(Schema.Defect), - }, -) { - override get message(): string { - return `Timed out waiting for ${this.label}.`; - } -} - -const withWsRpcClient = ( - wsUrl: string, - f: (client: WsRpcClient) => Effect.Effect, -) => makeWsRpcClient.pipe(Effect.flatMap(f), Effect.provide(wsRpcProtocolLayer(wsUrl))); - -const ORCHESTRATION_V2_REPLAY_HARNESSES = [CodexOrchestratorReplayHarness] as const; - -function orchestrationV2ReplayHarnessFor(provider: ProviderKind) { - const harness = ORCHESTRATION_V2_REPLAY_HARNESSES.find( - (candidate) => candidate.provider === provider, - ); - if (!harness) { - throw new Error(`No orchestration V2 replay harness registered for ${provider}.`); - } - return harness; -} - -const readProviderReplayTranscript = (file: URL) => - Effect.promise(() => readFile(file, "utf8")).pipe(Effect.flatMap(decodeProviderReplayNdjson)); - -const takeWsItem = (queue: Queue.Queue, label: string) => - Queue.take(queue).pipe( - Effect.raceFirst( - Effect.tryPromise({ - try: () => - new Promise((_resolve, reject) => { - setTimeout(() => reject(new WsRpcTestTimeoutError({ label })), 5_000); - }), - catch: (cause) => - Schema.is(WsRpcTestTimeoutError)(cause) - ? cause - : new WsRpcTestTimeoutError({ label, cause }), - }), - ), - ); - -const appendSessionCookieToWsUrl = (url: string, sessionCookieHeader: string) => { - const isAbsoluteUrl = /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url); - const next = new URL(url, "http://localhost"); - next.hash = `cookie=${encodeURIComponent(sessionCookieHeader)}`; - return isAbsoluteUrl ? next.toString() : `${next.pathname}${next.search}${next.hash}`; -}; - -const getHttpServerUrl = (pathname = "") => - Effect.gen(function* () { - const server = yield* HttpServer.HttpServer; - const address = server.address as HttpServer.TcpAddress; - return `http://127.0.0.1:${address.port}${pathname}`; - }); - -const bootstrapBrowserSession = ( - credential = defaultDesktopBootstrapToken, - options?: { - readonly headers?: Record; - }, -) => - Effect.gen(function* () { - const bootstrapUrl = yield* getHttpServerUrl("/api/auth/browser-session"); - const response = yield* fetchEffect(bootstrapUrl, { - method: "POST", - headers: { - "content-type": "application/json", - ...options?.headers, - }, - body: jsonRequestBody({ - credential, - }), - }); - const body = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly sessionMethod: string; - readonly expiresAt: string; - }>(response); - return { - response, - body, - cookie: response.headers["set-cookie"], - }; - }); - -const exchangeAccessToken = ( - credential = defaultDesktopBootstrapToken, - options?: { - readonly headers?: Record; - readonly scope?: string; - readonly clientMetadata?: { - readonly label?: string; - readonly deviceType?: string; - readonly os?: string; - }; - }, -) => - Effect.gen(function* () { - const tokenUrl = yield* getHttpServerUrl("/oauth/token"); - const response = yield* fetchEffect(tokenUrl, { - method: "POST", - headers: { - "content-type": "application/x-www-form-urlencoded", - ...options?.headers, - }, - body: new URLSearchParams({ - grant_type: AuthTokenExchangeGrantType, - subject_token: credential, - subject_token_type: AuthEnvironmentBootstrapTokenType, - requested_token_type: AuthAccessTokenType, - scope: - options?.scope ?? - "orchestration:read orchestration:operate terminal:operate review:write relay:read access:read access:write relay:write", - ...(options?.clientMetadata?.label ? { client_label: options.clientMetadata.label } : {}), - ...(options?.clientMetadata?.deviceType - ? { client_device_type: options.clientMetadata.deviceType } - : {}), - ...(options?.clientMetadata?.os ? { client_os: options.clientMetadata.os } : {}), - }).toString(), - }); - const body = yield* responseJsonEffect<{ - readonly access_token?: string; - readonly issued_token_type?: string; - readonly token_type?: string; - readonly expires_in?: number; - readonly scope?: string; - readonly _tag?: string; - readonly code?: string; - readonly reason?: string; - readonly traceId?: string; - }>(response); - return { - response, - body, - }; - }); - -const makeDpopProof = (input: { - readonly method: string; - readonly url: string; - readonly iat: number; - readonly accessToken?: string; - readonly jti?: string; - readonly privateKey?: NodeCrypto.KeyObject; - readonly publicJwk?: DpopPublicJwk; -}) => { - const keyPair = - input.privateKey && input.publicJwk - ? { privateKey: input.privateKey, publicJwk: input.publicJwk } - : (() => { - const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", { - namedCurve: "P-256", - }); - return { privateKey, publicJwk: publicKey.export({ format: "jwk" }) as DpopPublicJwk }; - })(); - const header = Buffer.from( - JSON.stringify({ - typ: "dpop+jwt", - alg: "ES256", - jwk: keyPair.publicJwk, - }), - ).toString("base64url"); - const payload = Buffer.from( - JSON.stringify({ - htm: input.method, - htu: input.url, - jti: input.jti ?? "proof-1", - iat: input.iat, - ...(input.accessToken ? { ath: computeDpopAccessTokenHash(input.accessToken) } : {}), - }), - ).toString("base64url"); - const signature = NodeCrypto.sign("sha256", Buffer.from(`${header}.${payload}`), { - key: keyPair.privateKey, - dsaEncoding: "ieee-p1363", - }).toString("base64url"); - return { - proof: `${header}.${payload}.${signature}`, - thumbprint: computeDpopJwkThumbprint(keyPair.publicJwk), - privateKey: keyPair.privateKey, - publicJwk: keyPair.publicJwk, - }; -}; - -const makeCloudMintCredentialRequest = (input: { - readonly privateKey: string; - readonly environmentId: EnvironmentId; - readonly clientProofKeyThumbprint: string; - readonly issuer?: string; - readonly audience?: string; - readonly subject?: string; - readonly jti?: string; - readonly nonce: string; - readonly issuedAt: string; - readonly expiresAt: string; - readonly scope?: ReadonlyArray<"environment:connect">; -}) => { - const payload = { - iss: input.issuer ?? "https://relay.example.test", - aud: input.audience ?? `t3-env:${input.environmentId}`, - sub: input.subject ?? "user_123", - jti: input.jti ?? "cloud-mint-jti-1", - environmentId: input.environmentId, - clientProofKeyThumbprint: input.clientProofKeyThumbprint, - cnf: { - jkt: input.clientProofKeyThumbprint, - }, - nonce: input.nonce, - iat: Math.floor(DateTime.makeUnsafe(input.issuedAt).epochMilliseconds / 1_000), - exp: Math.floor(DateTime.makeUnsafe(input.expiresAt).epochMilliseconds / 1_000), - scope: input.scope ?? ["environment:connect"], - } as const; - const header = Buffer.from( - JSON.stringify({ alg: "EdDSA", typ: RELAY_MINT_REQUEST_TYP }), - ).toString("base64url"); - const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url"); - const signingInput = `${header}.${encodedPayload}`; - return { - proof: `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), input.privateKey).toString("base64url")}`, - }; -}; - -const makeCloudEnvironmentHealthRequest = (input: { - readonly privateKey: string; - readonly environmentId: EnvironmentId; - readonly issuer?: string; - readonly audience?: string; - readonly subject?: string; - readonly jti?: string; - readonly nonce: string; - readonly issuedAt: string; - readonly expiresAt: string; - readonly scope?: ReadonlyArray<"environment:status">; -}) => { - const payload = { - iss: input.issuer ?? "https://relay.example.test", - aud: input.audience ?? `t3-env:${input.environmentId}`, - sub: input.subject ?? "user_123", - jti: input.jti ?? "cloud-health-jti-1", - environmentId: input.environmentId, - nonce: input.nonce, - iat: Math.floor(DateTime.makeUnsafe(input.issuedAt).epochMilliseconds / 1_000), - exp: Math.floor(DateTime.makeUnsafe(input.expiresAt).epochMilliseconds / 1_000), - scope: input.scope ?? ["environment:status"], - } as const; - const header = Buffer.from( - JSON.stringify({ alg: "EdDSA", typ: RELAY_HEALTH_REQUEST_TYP }), - ).toString("base64url"); - const encodedPayload = Buffer.from(JSON.stringify(payload)).toString("base64url"); - const signingInput = `${header}.${encodedPayload}`; - return { - proof: `${signingInput}.${NodeCrypto.sign(null, Buffer.from(signingInput), input.privateKey).toString("base64url")}`, - }; -}; - -const decodeCompactJwtPayload = (token: string): A => { - const encodedPayload = token.split(".")[1]; - if (!encodedPayload) { - throw new Error("JWT does not contain a payload."); - } - return JSON.parse(Buffer.from(encodedPayload, "base64url").toString("utf8")) as A; -}; - -class AuthenticationGetterError extends Data.TaggedError("AuthenticationGetterError")<{ - readonly message: string; -}> {} - -class TestHttpRequestError extends Data.TaggedError("TestHttpRequestError")<{ - readonly cause: unknown; -}> {} - -const testRequestUrl = (input: Parameters[0]): string => { - const value = input.toString(); - if (!/^https?:\/\//i.test(value)) { - return value; - } - const url = new URL(value); - return `${url.pathname}${url.search}`; -}; - -const fetchEffect = (input: Parameters[0], init?: RequestInit) => { - const request = HttpClientRequest.make((init?.method ?? "GET") as "GET" | "POST")( - testRequestUrl(input), - { - headers: init?.headers as Record | undefined, - }, - ).pipe( - typeof init?.body === "string" - ? HttpClientRequest.bodyText( - init.body, - (init.headers as Record | undefined)?.["content-type"] ?? - "application/json", - ) - : (request) => request, - ); - const effect = HttpClient.execute(request); - return ( - init?.redirect === "manual" - ? effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" })) - : effect - ).pipe(Effect.mapError((cause) => new TestHttpRequestError({ cause }))); -}; - -const jsonRequestBody = (value: unknown): string => { - return JSON.stringify(value); -}; - -const responseJsonEffect = (response: HttpClientResponse.HttpClientResponse) => - response.json.pipe( - Effect.map((json) => json as A), - Effect.mapError((cause) => new TestHttpRequestError({ cause })), - ); - -const responseOk = (response: HttpClientResponse.HttpClientResponse) => - response.status >= 200 && response.status < 300; - -const getAuthenticatedSessionCookieHeader = (credential = defaultDesktopBootstrapToken) => - Effect.gen(function* () { - const { response, cookie } = yield* bootstrapBrowserSession(credential); - if (!responseOk(response)) { - return yield* new AuthenticationGetterError({ - message: `Expected bootstrap session response to succeed, got ${response.status}`, - }); - } - - if (!cookie) { - return yield* new AuthenticationGetterError({ - message: "Expected bootstrap session response to set a cookie.", - }); - } - - return cookie.split(";")[0] ?? cookie; - }); - -const getAuthenticatedBearerSessionToken = (credential = defaultDesktopBootstrapToken) => - Effect.gen(function* () { - const { response, body } = yield* exchangeAccessToken(credential); - if (!responseOk(response)) { - return yield* new AuthenticationGetterError({ - message: `Expected bearer bootstrap response to succeed, got ${response.status}`, - }); - } - - if (!body.access_token) { - return yield* new AuthenticationGetterError({ - message: "Expected token exchange response to include an access token.", - }); - } - - return body.access_token; - }); - -const extractSessionTokenFromSetCookie = (cookieHeader: string): string => { - const [nameValue] = cookieHeader.split(";", 1); - const token = nameValue?.split("=", 2)[1]; - if (!token) { - throw new Error("Expected session cookie header to contain a token value."); - } - return token; -}; - -const splitHeaderTokens = (value: string | null | undefined) => - (value ?? "") - .split(",") - .map((token) => token.trim()) - .filter((token) => token.length > 0) - .toSorted(); - -const assertBrowserApiCorsResponseHeaders = ( - headers: Readonly>, - options?: { - readonly origin?: string; - readonly credentials?: boolean; - }, -) => { - assert.equal(headers["access-control-allow-origin"], options?.origin ?? "*"); - assert.equal( - headers["access-control-allow-credentials"], - options?.credentials ? "true" : undefined, - ); -}; - -const assertBrowserApiCorsPreflightHeaders = ( - headers: Readonly>, - options?: { - readonly origin?: string; - readonly credentials?: boolean; - }, -) => { - assertBrowserApiCorsResponseHeaders(headers, options); - assert.deepEqual(splitHeaderTokens(headers["access-control-allow-methods"] ?? null), [ - "GET", - "OPTIONS", - "POST", - ]); - assert.deepEqual(splitHeaderTokens(headers["access-control-allow-headers"]), [ - "authorization", - "b3", - "content-type", - "dpop", - "traceparent", - ]); -}; -const crossOriginClientOrigin = "http://remote-client.test:3773"; - -const getWsServerUrl = ( - pathname = "", - options?: { authenticated?: boolean; credential?: string }, -) => - Effect.gen(function* () { - const server = yield* HttpServer.HttpServer; - const address = server.address as HttpServer.TcpAddress; - const baseUrl = `ws://127.0.0.1:${address.port}${pathname}`; - if (options?.authenticated === false) { - return baseUrl; - } - return appendSessionCookieToWsUrl( - baseUrl, - yield* getAuthenticatedSessionCookieHeader(options?.credential), - ); - }); - -it.layer(NodeServices.layer)("server router seam", (it) => { - it.effect("parks HTTP ingress until command readiness", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-gate-" }); - yield* fileSystem.writeFileString(path.join(staticDir, "index.html"), "ready"); - const entered = yield* Deferred.make(); - const ready = yield* Deferred.make(); - const completed = yield* Deferred.make(); - - yield* buildAppUnderTest({ - config: { staticDir }, - layers: { - serverRuntimeStartup: { - awaitCommandReady: Deferred.succeed(entered, undefined).pipe( - Effect.andThen(Deferred.await(ready)), - ), - }, - }, - }); - const request = yield* HttpClient.get("/").pipe( - Effect.tap(() => Deferred.succeed(completed, undefined)), - Effect.forkChild, - ); - yield* Deferred.await(entered); - assert.isFalse(yield* Deferred.isDone(completed)); - - yield* Deferred.succeed(ready, undefined); - assert.equal((yield* Fiber.join(request)).status, 200); - assert.isTrue(yield* Deferred.isDone(completed)); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("serves static index content for GET / when staticDir is configured", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const staticDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-router-static-" }); - const indexPath = path.join(staticDir, "index.html"); - yield* fileSystem.writeFileString(indexPath, "router-static-ok"); - - yield* buildAppUnderTest({ config: { staticDir } }); - - const response = yield* HttpClient.get("/"); - assert.equal(response.status, 200); - assert.include(yield* response.text, "router-static-ok"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("redirects to dev URL when configured", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { devUrl: new URL("http://127.0.0.1:5173") }, - }); - - const url = yield* getHttpServerUrl("/foo/bar?token=test-token"); - const response = yield* fetchEffect(url, { redirect: "manual" }); - - assert.equal(response.status, 302); - assert.equal(response.headers.location, "http://127.0.0.1:5173/foo/bar?token=test-token"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("serves the public environment descriptor without requiring auth", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const url = yield* getHttpServerUrl("/.well-known/t3/environment"); - const response = yield* fetchEffect(url); - const body = yield* responseJsonEffect(response); - - assert.equal(response.status, 200); - assert.deepEqual(body, testEnvironmentDescriptor); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("compresses large JSON responses through the composed routes", () => - Effect.gen(function* () { - const descriptor = { - ...testEnvironmentDescriptor, - label: "Test environment".repeat(100), - }; - yield* buildAppUnderTest({ - layers: { - serverEnvironment: { - getDescriptor: Effect.succeed(descriptor), - }, - }, - }); - - const url = yield* getHttpServerUrl("/.well-known/t3/environment"); - const response = yield* fetchEffect(url, { - headers: { - "accept-encoding": "gzip", - }, - }); - const body = yield* responseJsonEffect(response); - - assert.equal(response.status, 200); - assert.equal(response.headers["content-encoding"], "gzip"); - assert.equal(response.headers.vary, "Accept-Encoding"); - assert.deepEqual(body, descriptor); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("includes CORS headers on public environment descriptor responses", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const url = yield* getHttpServerUrl("/.well-known/t3/environment"); - const response = yield* fetchEffect(url, { - headers: { - origin: crossOriginClientOrigin, - }, - }); - const body = yield* responseJsonEffect(response); - - assert.equal(response.status, 200); - assertBrowserApiCorsResponseHeaders(response.headers); - assert.deepEqual(body, testEnvironmentDescriptor); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("reports unauthenticated session state without requiring auth", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const url = yield* getHttpServerUrl("/api/auth/session"); - const response = yield* fetchEffect(url); - const body = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly auth: { - readonly policy: string; - readonly bootstrapMethods: ReadonlyArray; - readonly sessionMethods: ReadonlyArray; - readonly sessionCookieName: string; - }; - }>(response); - - assert.equal(response.status, 200); - assert.equal(body.authenticated, false); - assert.equal(body.auth.policy, "desktop-managed-local"); - assert.deepEqual(body.auth.bootstrapMethods, ["desktop-bootstrap"]); - assert.deepEqual(body.auth.sessionMethods, [ - "browser-session-cookie", - "bearer-access-token", - "dpop-access-token", - ]); - // Desktop, so port-scoped: instances scan for a free port and share - // 127.0.0.1, and cookies are not scoped by port. - assert.isTrue(body.auth.sessionCookieName.startsWith("t3_session_")); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("bootstraps a browser session and authenticates the session endpoint via cookie", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { - response: bootstrapResponse, - body: bootstrapBody, - cookie: setCookie, - } = yield* bootstrapBrowserSession(); - - assert.equal(bootstrapResponse.status, 200); - assert.equal(bootstrapBody.authenticated, true); - assert.equal(bootstrapBody.sessionMethod, "browser-session-cookie"); - assert.isUndefined((bootstrapBody as { readonly sessionToken?: string }).sessionToken); - assert.isDefined(setCookie); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const sessionResponse = yield* fetchEffect(sessionUrl, { - headers: { - cookie: setCookie?.split(";")[0] ?? "", - }, - }); - const sessionBody = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly sessionMethod?: string; - }>(sessionResponse); - - assert.equal(sessionResponse.status, 200); - assert.equal(sessionBody.authenticated, true); - assert.equal(sessionBody.sessionMethod, "browser-session-cookie"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("exchanges a bootstrap grant for a scoped bearer access token", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { response: tokenResponse, body: tokenBody } = yield* exchangeAccessToken(); - - assert.equal(tokenResponse.status, 200); - assert.equal(tokenBody.issued_token_type, AuthAccessTokenType); - assert.equal(tokenBody.token_type, "Bearer"); - assert.equal( - tokenBody.scope, - "orchestration:read orchestration:operate terminal:operate review:write relay:read access:read access:write relay:write", - ); - assert.equal(typeof tokenBody.access_token, "string"); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const sessionResponse = yield* fetchEffect(sessionUrl, { - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - }, - }); - const sessionBody = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly sessionMethod?: string; - readonly scopes?: ReadonlyArray; - }>(sessionResponse); - - assert.equal(sessionResponse.status, 200); - assert.equal(sessionBody.authenticated, true); - assert.equal(sessionBody.sessionMethod, "bearer-access-token"); - assert.deepEqual(sessionBody.scopes, [ - "orchestration:read", - "orchestration:operate", - "terminal:operate", - "review:write", - "relay:read", - "access:read", - "access:write", - "relay:write", - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("persists token exchange client display metadata for authorized-client listings", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const pairingBody = (yield* pairingResponse.json) as { - readonly credential: string; - }; - - const { response } = yield* exchangeAccessToken(pairingBody.credential, { - headers: { - "user-agent": "undici", - }, - scope: "orchestration:read orchestration:operate terminal:operate review:write", - clientMetadata: { - label: "T3 Code Mobile", - deviceType: "mobile", - os: "iOS", - }, - }); - - const clientsResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: ownerCookie, - }, - }); - const clients = (yield* clientsResponse.json) as ReadonlyArray<{ - readonly current: boolean; - readonly client: { - readonly label?: string; - readonly deviceType: string; - readonly ipAddress?: string; - readonly os?: string; - readonly userAgent?: string; - }; - }>; - const mobileClient = clients.find((client) => !client.current); - - assert.equal(pairingResponse.status, 200); - assert.equal(response.status, 200); - assert.equal(clientsResponse.status, 200); - assert.deepInclude(mobileClient?.client, { - label: "T3 Code Mobile", - deviceType: "mobile", - os: "iOS", - ipAddress: "127.0.0.1", - userAgent: "undici", - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "exchanges a bootstrap credential for a DPoP-bound access token without bearer downgrade", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { cookie: ownerCookie }, - body: yield* HttpBody.json({}), - }); - const credential = (yield* credentialResponse.json) as { readonly credential: string }; - const tokenUrl = yield* getHttpServerUrl("/oauth/token"); - const now = yield* DateTime.now; - const tokenProof = makeDpopProof({ - method: "POST", - url: tokenUrl, - iat: Math.floor(now.epochMilliseconds / 1_000), - jti: "token-exchange-proof", - }); - const tokenResponse = yield* fetchEffect(tokenUrl, { - method: "POST", - headers: { - "content-type": "application/x-www-form-urlencoded", - dpop: tokenProof.proof, - }, - body: new URLSearchParams({ - grant_type: "urn:ietf:params:oauth:grant-type:token-exchange", - subject_token: credential.credential, - subject_token_type: "urn:t3:params:oauth:token-type:environment-bootstrap", - requested_token_type: "urn:ietf:params:oauth:token-type:access_token", - scope: "orchestration:read orchestration:operate terminal:operate review:write", - }).toString(), - }); - const token = yield* responseJsonEffect<{ - readonly access_token: string; - readonly token_type: string; - }>(tokenResponse); - - assert.equal(tokenResponse.status, 200); - assert.equal(tokenResponse.headers["cache-control"], "no-store"); - assert.equal(token.token_type, "DPoP"); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const bearerResponse = yield* fetchEffect(sessionUrl, { - headers: { authorization: `Bearer ${token.access_token}` }, - }); - const bearerState = yield* responseJsonEffect<{ readonly authenticated: boolean }>( - bearerResponse, - ); - assert.equal(bearerState.authenticated, false); - - const sessionProof = makeDpopProof({ - method: "GET", - url: sessionUrl, - iat: Math.floor(now.epochMilliseconds / 1_000), - jti: "session-proof", - accessToken: token.access_token, - privateKey: tokenProof.privateKey, - publicJwk: tokenProof.publicJwk, - }); - const dpopResponse = yield* fetchEffect(sessionUrl, { - headers: { - authorization: `DPoP ${token.access_token}`, - dpop: sessionProof.proof, - }, - }); - const dpopState = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly sessionMethod?: string; - }>(dpopResponse); - assert.equal(dpopState.authenticated, true); - assert.equal(dpopState.sessionMethod, "dpop-access-token"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects replayed DPoP proofs across token exchanges", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const firstCredentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const firstCredential = (yield* firstCredentialResponse.json) as { - readonly credential: string; - }; - const secondCredentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const secondCredential = (yield* secondCredentialResponse.json) as { - readonly credential: string; - }; - const tokenUrl = yield* getHttpServerUrl("/oauth/token"); - const now = yield* DateTime.now; - const dpop = makeDpopProof({ - method: "POST", - url: tokenUrl, - iat: Math.floor(now.epochMilliseconds / 1_000), - }); - - const firstBootstrap = yield* exchangeAccessToken(firstCredential.credential, { - headers: { - dpop: dpop.proof, - }, - scope: "orchestration:read orchestration:operate terminal:operate review:write", - }); - const replayBootstrap = yield* exchangeAccessToken(secondCredential.credential, { - headers: { - dpop: dpop.proof, - }, - scope: "orchestration:read orchestration:operate terminal:operate review:write", - }); - - assert.equal(firstBootstrap.response.status, 200); - assert.equal(replayBootstrap.response.status, 401); - assert.equal(replayBootstrap.body._tag, "EnvironmentAuthInvalidError"); - assert.equal(replayBootstrap.body.code, "auth_invalid"); - assert.equal(replayBootstrap.body.reason, "invalid_credential"); - assert.equal(typeof replayBootstrap.body.traceId, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("ignores forwarded host headers when validating token exchange DPoP URLs", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const credential = (yield* credentialResponse.json) as { - readonly credential: string; - }; - const tokenUrl = yield* getHttpServerUrl("/oauth/token"); - const now = yield* DateTime.now; - const dpop = makeDpopProof({ - method: "POST", - url: tokenUrl, - iat: Math.floor(now.epochMilliseconds / 1_000), - }); - - const bootstrap = yield* exchangeAccessToken(credential.credential, { - headers: { - dpop: dpop.proof, - "x-forwarded-host": "environment.example.test", - }, - scope: "orchestration:read orchestration:operate terminal:operate review:write", - }); - - assert.equal(bootstrap.response.status, 200); - assert.equal(bootstrap.body.token_type, "DPoP"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects token exchange DPoP proofs bound to spoofed forwarded hosts", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const credential = (yield* credentialResponse.json) as { - readonly credential: string; - }; - const tokenUrl = yield* getHttpServerUrl("/oauth/token"); - const spoofedUrl = new URL(tokenUrl); - spoofedUrl.hostname = "environment.example.test"; - const now = yield* DateTime.now; - const dpop = makeDpopProof({ - method: "POST", - url: spoofedUrl.href, - iat: Math.floor(now.epochMilliseconds / 1_000), - }); - - const bootstrap = yield* exchangeAccessToken(credential.credential, { - headers: { - dpop: dpop.proof, - "x-forwarded-host": spoofedUrl.host, - }, - scope: "orchestration:read orchestration:operate terminal:operate review:write", - }); - - assert.equal(bootstrap.response.status, 401); - assert.equal(bootstrap.body._tag, "EnvironmentAuthInvalidError"); - assert.equal(bootstrap.body.code, "auth_invalid"); - assert.equal(bootstrap.body.reason, "invalid_credential"); - assert.equal(typeof bootstrap.body.traceId, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud link proofs for non-loopback managed endpoint origins", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const linkProofResponse = yield* fetchEffect(linkProofUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: "https://environment.example.test/", - wsBaseUrl: "wss://environment.example.test/ws", - providerKind: "manual", - }, - origin: { - localHttpHost: "192.168.1.42", - localHttpPort: 3773, - }, - }), - }); - const body = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(linkProofResponse); - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud link proofs for unsupported endpoint providers", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* fetchEffect(linkProofUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: linkProofUrl.replace("/api/connect/link-proof", ""), - wsBaseUrl: linkProofUrl - .replace("http://", "ws://") - .replace("/api/connect/link-proof", "/ws"), - // "manual" and "cloudflare_tunnel" are supported; "t3_relay" is not. - providerKind: "t3_relay", - }, - origin: { - localHttpHost: "127.0.0.1", - localHttpPort: serverPort, - }, - }), - }); - const body = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(linkProofResponse); - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud link proofs requested through a public managed endpoint", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - "content-type": "application/json", - host: "environment.example.test", - "x-forwarded-host": "environment.example.test", - "x-forwarded-proto": "https", - }, - body: HttpBody.text( - jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: "https://environment.example.test/", - wsBaseUrl: "wss://environment.example.test/ws", - providerKind: "manual", - }, - origin: { - localHttpHost: "127.0.0.1", - localHttpPort: serverPort, - }, - }), - "application/json", - ), - }); - const body = (yield* linkProofResponse.json) as { - readonly _tag?: string; - readonly message?: string; - }; - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "rejects cloud link proofs when a public request spoofs loopback forwarded headers", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - "content-type": "application/json", - host: "environment.example.test", - "x-forwarded-host": `127.0.0.1:${serverPort}`, - "x-forwarded-proto": "http", - }, - body: HttpBody.text( - jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: "https://environment.example.test/", - wsBaseUrl: "wss://environment.example.test/ws", - providerKind: "manual", - }, - origin: { - localHttpHost: "127.0.0.1", - localHttpPort: serverPort, - }, - }), - "application/json", - ), - }); - const body = (yield* linkProofResponse.json) as { - readonly _tag?: string; - readonly message?: string; - }; - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud link proofs with malformed forwarded request hosts", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* HttpClient.post("/api/connect/link-proof", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - "content-type": "application/json", - host: "bad host", - "x-forwarded-host": "bad host", - "x-forwarded-proto": "https", - }, - body: HttpBody.text( - jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: "https://environment.example.test/", - wsBaseUrl: "wss://environment.example.test/ws", - providerKind: "manual", - }, - origin: { - localHttpHost: "127.0.0.1", - localHttpPort: serverPort, - }, - }), - "application/json", - ), - }); - const body = (yield* linkProofResponse.json) as { - readonly _tag?: string; - readonly message?: string; - }; - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects local cloud link proofs for a different loopback port", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const serverPort = Number(new URL(linkProofUrl).port); - const linkProofResponse = yield* fetchEffect(linkProofUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - challenge: "relay-link-challenge", - relayIssuer: "https://relay.example.test", - endpoint: { - httpBaseUrl: "https://environment.example.test/", - wsBaseUrl: "wss://environment.example.test/ws", - providerKind: "manual", - }, - origin: { - localHttpHost: "127.0.0.1", - localHttpPort: serverPort === 65_535 ? serverPort - 1 : serverPort + 1, - }, - }), - }); - const body = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(linkProofResponse); - - assert.equal(linkProofResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Invalid managed endpoint origin."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("allows standard clients to read managed relay configuration state", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { cookie: ownerCookie }, - body: yield* HttpBody.json({}), - }); - const credential = (yield* credentialResponse.json) as { readonly credential: string }; - const pairedCookie = yield* getAuthenticatedSessionCookieHeader(credential.credential); - const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state"); - const response = yield* fetchEffect(linkStateUrl, { - headers: { cookie: pairedCookie }, - }); - const body = yield* responseJsonEffect<{ - readonly linked?: boolean; - readonly publishAgentActivity?: boolean; - }>(response); - - assert.equal(response.status, 200); - assert.equal(body.linked, false); - assert.equal(body.publishAgentActivity, false); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "reports relay client status and streams installation progress over environment RPC", - () => - Effect.gen(function* () { - const installedRelayClient = { - status: "available" as const, - executablePath: "/tmp/t3/tools/cloudflared", - source: "managed" as const, - version: RelayClient.CLOUDFLARED_VERSION, - }; - yield* buildAppUnderTest({ - layers: { - relayClient: { - resolve: Effect.succeed({ - status: "missing", - version: RelayClient.CLOUDFLARED_VERSION, - }), - install: Effect.succeed(installedRelayClient), - installWithProgress: (report) => - report({ type: "progress", stage: "checking" }).pipe( - Effect.andThen(report({ type: "progress", stage: "downloading" })), - Effect.as(installedRelayClient), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const status = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.cloudGetRelayClientStatus]({})), - ); - const installEvents = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.cloudInstallRelayClient]({}).pipe(Stream.runCollect), - ), - ); - - assert.equal(status.status, "missing"); - assert.deepEqual(Array.from(installEvents), [ - { type: "progress", stage: "checking" }, - { type: "progress", stage: "downloading" }, - { type: "complete", status: installedRelayClient }, - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("requires relay write scope to update agent activity publication", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const preferencesUrl = yield* getHttpServerUrl("/api/connect/preferences"); - const ownerResponse = yield* fetchEffect(preferencesUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ publishAgentActivity: true }), - }); - const ownerBody = yield* responseJsonEffect<{ - readonly publishAgentActivity?: boolean; - }>(ownerResponse); - assert.equal(ownerResponse.status, 200); - assert.equal(ownerBody.publishAgentActivity, true); - - const credentialResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { cookie: ownerCookie }, - body: yield* HttpBody.json({}), - }); - const credential = (yield* credentialResponse.json) as { readonly credential: string }; - const pairedCookie = yield* getAuthenticatedSessionCookieHeader(credential.credential); - const pairedResponse = yield* fetchEffect(preferencesUrl, { - method: "POST", - headers: { - cookie: pairedCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ publishAgentActivity: false }), - }); - const pairedBody = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly requiredScope?: string; - }>(pairedResponse); - assert.equal(pairedResponse.status, 403); - assert.equal(pairedBody._tag, "EnvironmentScopeRequiredError"); - assert.equal(pairedBody.requiredScope, "relay:write"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects relay config with an invalid cloud mint public key", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: "not-a-public-key", - endpointRuntime: null, - }), - }); - const body = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(relayConfigResponse); - - assert.equal(relayConfigResponse.status, 400); - assert.equal(body._tag, "EnvironmentHttpBadRequestError"); - assert.equal(body.message, "Cloud mint public key must be a valid Ed25519 public key."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects relay config with insecure relay metadata or empty credentials", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const postRelayConfig = (body: { - readonly relayUrl: string; - readonly relayIssuer?: string; - readonly cloudUserId: string; - readonly environmentCredential: string; - }) => - fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - ...body, - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - - const insecureRelayUrl = yield* postRelayConfig({ - relayUrl: "http://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - }); - const insecureRelayIssuer = yield* postRelayConfig({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - relayIssuer: "http://relay.example.test", - environmentCredential: "t3env_test_credential", - }); - const nonOriginRelayUrl = yield* postRelayConfig({ - relayUrl: "https://relay.example.test/path", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - }); - const emptyCredential = yield* postRelayConfig({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: " ", - }); - const insecureRelayUrlBody = yield* responseJsonEffect<{ readonly message?: string }>( - insecureRelayUrl, - ); - const insecureRelayIssuerBody = yield* responseJsonEffect<{ readonly message?: string }>( - insecureRelayIssuer, - ); - const nonOriginRelayUrlBody = yield* responseJsonEffect<{ readonly message?: string }>( - nonOriginRelayUrl, - ); - const emptyCredentialBody = yield* responseJsonEffect<{ readonly message?: string }>( - emptyCredential, - ); - - assert.equal(insecureRelayUrl.status, 400); - assert.equal(insecureRelayUrlBody.message, "Relay URL must be a secure absolute HTTPS URL."); - assert.equal(insecureRelayIssuer.status, 400); - assert.equal( - insecureRelayIssuerBody.message, - "Relay issuer must be a secure absolute HTTPS URL.", - ); - assert.equal(nonOriginRelayUrl.status, 400); - assert.equal(nonOriginRelayUrlBody.message, "Relay URL must be a secure absolute HTTPS URL."); - assert.equal(emptyCredential.status, 400); - assert.equal(emptyCredentialBody.message, "Relay environment credential is required."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects relay config replacement from a different cloud account", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const postRelayConfig = (cloudUserId: string, environmentCredential: string) => - fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId, - environmentCredential, - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - - const firstResponse = yield* postRelayConfig("user_123", "t3env_first_credential"); - const replacementResponse = yield* postRelayConfig("user_456", "t3env_second_credential"); - const replacementBody = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(replacementResponse); - - assert.equal(firstResponse.status, 200); - assert.equal(replacementResponse.status, 409); - assert.equal(replacementBody._tag, "EnvironmentHttpConflictError"); - assert.equal( - replacementBody.message, - "This environment is already linked to a different cloud account. Unlink it before switching accounts.", - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("reports local cloud link state from persisted relay config", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state"); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - - const initialResponse = yield* fetchEffect(linkStateUrl, { - headers: { - cookie: ownerCookie, - }, - }); - const initialBody = yield* responseJsonEffect<{ - readonly linked?: boolean; - readonly cloudUserId?: string | null; - }>(initialResponse); - assert.equal(initialResponse.status, 200); - assert.equal(initialBody.linked, false); - assert.equal(initialBody.cloudUserId, null); - - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://transport.example.test", - relayIssuer: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const linkedResponse = yield* fetchEffect(linkStateUrl, { - headers: { - cookie: ownerCookie, - }, - }); - const linkedBody = yield* responseJsonEffect<{ - readonly linked?: boolean; - readonly cloudUserId?: string | null; - readonly relayUrl?: string | null; - readonly relayIssuer?: string | null; - }>(linkedResponse); - - assert.equal(linkedResponse.status, 200); - assert.equal(linkedBody.linked, true); - assert.equal(linkedBody.cloudUserId, "user_123"); - assert.equal(linkedBody.relayUrl, "https://transport.example.test"); - assert.equal(linkedBody.relayIssuer, "https://relay.example.test"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("does not expose internal cloud reconciliation over HTTP", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const reconcileUrl = yield* getHttpServerUrl("/api/connect/reconcile"); - const response = yield* fetchEffect(reconcileUrl, { - method: "POST", - }); - - assert.equal(response.status, 404); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("unlinks local cloud state and disables the managed endpoint runtime", () => - Effect.gen(function* () { - const appliedRuntimeConfigs: Array = []; - yield* buildAppUnderTest({ - layers: { - cloudManagedEndpointRuntime: { - applyConfig: (config) => { - appliedRuntimeConfigs.push(config); - if (!config) { - return Effect.succeed({ status: "disabled" }); - } - return Effect.succeed({ - status: "running", - providerKind: "cloudflare_tunnel", - pid: 123, - ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}), - ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}), - }); - }, - }, - }, - }); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const unlinkUrl = yield* getHttpServerUrl("/api/connect/unlink"); - const linkStateUrl = yield* getHttpServerUrl("/api/connect/link-state"); - - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://transport.example.test", - relayIssuer: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: { - providerKind: "cloudflare_tunnel", - connectorToken: "connector-token", - tunnelId: "tunnel-id", - tunnelName: "tunnel-name", - }, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const unlinkResponse = yield* fetchEffect(unlinkUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - }, - }); - const unlinkBody = yield* responseJsonEffect<{ - readonly ok?: boolean; - readonly endpointRuntimeStatus?: { readonly status?: string }; - }>(unlinkResponse); - assert.equal(unlinkResponse.status, 200); - assert.equal(unlinkBody.ok, true); - assert.equal(unlinkBody.endpointRuntimeStatus?.status, "disabled"); - - const linkStateResponse = yield* fetchEffect(linkStateUrl, { - headers: { - cookie: ownerCookie, - }, - }); - const linkStateBody = yield* responseJsonEffect<{ - readonly linked?: boolean; - readonly cloudUserId?: string | null; - readonly relayUrl?: string | null; - readonly relayIssuer?: string | null; - }>(linkStateResponse); - assert.equal(linkStateResponse.status, 200); - assert.equal(linkStateBody.linked, false); - assert.equal(linkStateBody.cloudUserId, null); - assert.equal(linkStateBody.relayUrl, null); - assert.equal(linkStateBody.relayIssuer, null); - assert.deepEqual(appliedRuntimeConfigs, [ - { - providerKind: "cloudflare_tunnel", - connectorToken: "connector-token", - tunnelId: "tunnel-id", - tunnelName: "tunnel-name", - }, - null, - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects replayed cloud mint requests atomically", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const request = makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - nonce: "cloud-mint-nonce-1", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }); - const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential"); - const postMint = () => - fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - const firstResponse = yield* postMint(); - const replayResponse = yield* postMint(); - const replayBody = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(replayResponse); - - assert.equal(firstResponse.status, 200); - assert.equal(replayResponse.status, 409); - assert.equal(replayBody._tag, "EnvironmentHttpConflictError"); - assert.equal(replayBody.message, "Cloud mint request was already consumed."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("serves the documented T3 Connect mint credential endpoint", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const request = makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - jti: "cloud-mint-jti-documented-endpoint", - nonce: "cloud-mint-nonce-documented-endpoint", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }); - const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); - const response = yield* fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - assert.equal(response.status, 200); - const body = yield* responseJsonEffect<{ - readonly credential?: string; - readonly proof?: string; - }>(response); - assert.equal(typeof body.credential, "string"); - assert.equal(typeof body.proof, "string"); - assert.equal( - decodeCompactJwtPayload<{ readonly requestNonce?: string }>(body.proof!).requestNonce, - "cloud-mint-nonce-documented-endpoint", - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("serves signed T3 Connect environment health checks", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const request = makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - jti: "cloud-health-jti-documented-endpoint", - nonce: "cloud-health-nonce-documented-endpoint", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }); - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const response = yield* fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - assert.equal(response.status, 200); - const body = yield* responseJsonEffect<{ - readonly status?: string; - readonly descriptor?: { readonly environmentId?: string }; - readonly proof?: string; - }>(response); - assert.equal(body.status, "online"); - assert.equal(body.descriptor?.environmentId, testEnvironmentDescriptor.environmentId); - assert.equal(typeof body.proof, "string"); - assert.equal( - decodeCompactJwtPayload<{ readonly requestNonce?: string }>(body.proof!).requestNonce, - "cloud-health-nonce-documented-endpoint", - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects replayed cloud health requests atomically", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const request = makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - jti: "cloud-health-jti-replay", - nonce: "cloud-health-nonce-replay", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }); - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const postHealth = () => - fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - const firstResponse = yield* postHealth(); - const replayResponse = yield* postHealth(); - const replayBody = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly message?: string; - }>(replayResponse); - - assert.equal(firstResponse.status, 200); - assert.equal(replayResponse.status, 409); - assert.equal(replayBody._tag, "EnvironmentHttpConflictError"); - assert.equal(replayBody.message, "Cloud health request was already consumed."); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "validates cloud proofs against the configured relay issuer, not the transport URL", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://transport.example.test", - cloudUserId: "user_123", - relayIssuer: "https://relay.example.test", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); - const postMint = (request: ReturnType) => - fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - const acceptedResponse = yield* postMint( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - issuer: "https://relay.example.test", - jti: "cloud-mint-jti-explicit-relay-issuer", - nonce: "cloud-mint-nonce-explicit-relay-issuer", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - const rejectedResponse = yield* postMint( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - issuer: "https://transport.example.test", - jti: "cloud-mint-jti-transport-url", - nonce: "cloud-mint-nonce-transport-url", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - - assert.equal(acceptedResponse.status, 200); - assert.equal(rejectedResponse.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("fails relay config when the managed endpoint connector cannot start", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - layers: { - cloudManagedEndpointRuntime: { - applyConfig: () => - Effect.succeed({ - status: "failed", - providerKind: "cloudflare_tunnel", - reason: "cloudflared missing", - tunnelId: "tunnel-1", - }), - }, - }, - }); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: { - providerKind: "cloudflare_tunnel", - connectorToken: "connector-token", - tunnelId: "tunnel-1", - }, - }), - }); - - assert.equal(relayConfigResponse.status, 503); - const relayConfigBody = yield* responseJsonEffect<{ - _tag?: string; - message?: string; - endpointRuntimeStatus?: { status?: string; reason?: string }; - }>(relayConfigResponse); - assert.equal(relayConfigBody._tag, "EnvironmentCloudEndpointUnavailableError"); - assert.equal(relayConfigBody.message, "Managed endpoint runtime could not be started."); - assert.equal(relayConfigBody.endpointRuntimeStatus?.status, "failed"); - assert.equal(relayConfigBody.endpointRuntimeStatus?.reason, "cloudflared missing"); - - const now = yield* DateTime.now; - const healthRequest = makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - nonce: "cloud-health-after-failed-runtime", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }); - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const healthResponse = yield* fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(healthRequest), - }); - const healthBody = yield* responseJsonEffect<{ - _tag?: string; - message?: string; - }>(healthResponse); - assert.equal(healthResponse.status, 500); - assert.equal(healthBody._tag, "EnvironmentHttpInternalServerError"); - assert.equal( - healthBody.message, - "Cloud mint public key is not installed for this environment.", - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud mint requests with the wrong issuer or audience", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/connect/mint-credential"); - const postMint = (request: ReturnType) => - fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - const wrongIssuer = yield* postMint( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - issuer: "https://attacker.example.test", - jti: "cloud-mint-jti-wrong-issuer", - nonce: "cloud-mint-nonce-wrong-issuer", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - const wrongAudience = yield* postMint( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - audience: "t3-env:other-environment", - jti: "cloud-mint-jti-wrong-audience", - nonce: "cloud-mint-nonce-wrong-audience", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - - assert.equal(wrongIssuer.status, 401); - assert.equal(wrongAudience.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud mint requests for a cloud subject other than the linked user", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); - const response = yield* fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - subject: "user_other", - jti: "cloud-mint-jti-wrong-subject", - nonce: "cloud-mint-nonce-wrong-subject", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ), - }); - - assert.equal(response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud mint requests without the exact connect scope", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const mintUrl = yield* getHttpServerUrl("/api/t3-connect/mint-credential"); - const response = yield* fetchEffect(mintUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody( - makeCloudMintCredentialRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - clientProofKeyThumbprint: "client-proof-key-thumbprint", - jti: "cloud-mint-jti-duplicate-scope", - nonce: "cloud-mint-nonce-duplicate-scope", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - scope: ["environment:connect", "environment:connect"], - }), - ), - }); - - assert.equal(response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud health requests with the wrong issuer or audience", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const postHealth = (request: ReturnType) => - fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody(request), - }); - - const wrongIssuer = yield* postHealth( - makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - issuer: "https://attacker.example.test", - jti: "cloud-health-jti-wrong-issuer", - nonce: "cloud-health-nonce-wrong-issuer", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - const wrongAudience = yield* postHealth( - makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - audience: "t3-env:other-environment", - jti: "cloud-health-jti-wrong-audience", - nonce: "cloud-health-nonce-wrong-audience", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ); - - assert.equal(wrongIssuer.status, 401); - assert.equal(wrongAudience.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud health requests for a cloud subject other than the linked user", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const response = yield* fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody( - makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - subject: "user_other", - jti: "cloud-health-jti-wrong-subject", - nonce: "cloud-health-nonce-wrong-subject", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - }), - ), - }); - - assert.equal(response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects cloud health requests without the exact status scope", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", { - privateKeyEncoding: { format: "pem", type: "pkcs8" }, - publicKeyEncoding: { format: "pem", type: "spki" }, - }); - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const relayConfigUrl = yield* getHttpServerUrl("/api/connect/relay-config"); - const relayConfigResponse = yield* fetchEffect(relayConfigUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - relayUrl: "https://relay.example.test/", - cloudUserId: "user_123", - environmentCredential: "t3env_test_credential", - cloudMintPublicKey: cloudKeyPair.publicKey, - endpointRuntime: null, - }), - }); - assert.equal(relayConfigResponse.status, 200); - - const now = yield* DateTime.now; - const healthUrl = yield* getHttpServerUrl("/api/t3-connect/health"); - const response = yield* fetchEffect(healthUrl, { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: jsonRequestBody( - makeCloudEnvironmentHealthRequest({ - privateKey: cloudKeyPair.privateKey, - environmentId: testEnvironmentDescriptor.environmentId, - jti: "cloud-health-jti-duplicate-scope", - nonce: "cloud-health-nonce-duplicate-scope", - issuedAt: DateTime.formatIso(now), - expiresAt: DateTime.formatIso(DateTime.add(now, { minutes: 5 })), - scope: ["environment:status", "environment:status"], - }), - ), - }); - - assert.equal(response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - // Mirrors NodeHttpServer.layerTest, which does not expose server options, - // with the production `websocket: { perMessageDeflate: true }` setting. - const NodeHttpServerTestWithWsDeflate = HttpServer.layerTestClient.pipe( - Layer.provide( - Layer.fresh(FetchHttpClient.layer).pipe( - Layer.provide(Layer.succeed(FetchHttpClient.RequestInit)({ keepalive: false })), - ), - ), - Layer.provideMerge( - Layer.unwrap( - Effect.map( - Effect.promise(() => import("node:http")), - (NodeHttp) => - NodeHttpServer.layer(NodeHttp.createServer, { - port: 0, - websocket: { perMessageDeflate: true }, - }), - ), - ), - ), - ); - - it.effect("negotiates permessage-deflate with clients that offer it", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { cookie, url } = parseSessionCookieFromWsUrl(yield* getWsServerUrl("/ws")); - const openSocket = (perMessageDeflate: boolean) => - Effect.acquireRelease( - Effect.callback((resume) => { - const socket = new NodeSocket.NodeWS.WebSocket(url, { - perMessageDeflate, - ...(cookie ? { headers: { cookie } } : {}), - }); - socket.on("open", () => resume(Effect.succeed(socket))); - socket.on("error", (error) => resume(Effect.fail(error))); - }), - (socket) => Effect.sync(() => socket.close()), - ); - - const compressed = yield* openSocket(true); - // The ws client records the negotiated extension only when the server's - // 101 response accepted the offer. - assert.include(compressed.extensions, "permessage-deflate"); - - const plain = yield* openSocket(false); - assert.notInclude(plain.extensions, "permessage-deflate"); - }).pipe(Effect.scoped, Effect.provide(NodeHttpServerTestWithWsDeflate)), - ); - - it.effect("issues short-lived websocket tickets for authenticated bearer sessions", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const bearerToken = yield* getAuthenticatedBearerSessionToken(); - const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); - const wsTicketResponse = yield* fetchEffect(wsTicketUrl, { - method: "POST", - headers: { - authorization: `Bearer ${bearerToken}`, - }, - }); - const wsTicketBody = yield* responseJsonEffect<{ - readonly ticket: string; - readonly expiresAt: string; - }>(wsTicketResponse); - - assert.equal(wsTicketResponse.status, 200); - assert.equal(typeof wsTicketBody.ticket, "string"); - assert.isTrue(wsTicketBody.ticket.length > 0); - assert.equal(typeof wsTicketBody.expiresAt, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("does not allow management-only access tokens to operate the environment", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { response: exchangeResponse, body: tokenBody } = yield* exchangeAccessToken( - defaultDesktopBootstrapToken, - { scope: "access:write" }, - ); - assert.equal(exchangeResponse.status, 200); - assert.equal(tokenBody.scope, "access:write"); - assert.isDefined(tokenBody.access_token); - - const overbroadPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - }, - body: yield* HttpBody.json({}), - }); - const overbroadPairingBody = (yield* overbroadPairingResponse.json) as { - readonly requiredScope: string; - }; - const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - }, - body: yield* HttpBody.json({ scopes: ["access:write"] }), - }); - const wsTicketResponse = yield* HttpClient.post("/api/auth/websocket-ticket", { - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - }, - }); - const wsTicketBody = (yield* wsTicketResponse.json) as { readonly ticket: string }; - assert.equal(overbroadPairingResponse.status, 403); - assert.equal(overbroadPairingBody.requiredScope, "orchestration:read"); - assert.equal(pairingResponse.status, 200); - assert.equal(wsTicketResponse.status, 200); - const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsTicket=${encodeURIComponent(wsTicketBody.ticket)}`; - const rpcError = yield* Effect.flip( - Effect.scoped(withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({}))), - ); - assert.equal(rpcError._tag, "EnvironmentAuthorizationError"); - if (rpcError._tag === "EnvironmentAuthorizationError") { - assert.equal(rpcError.requiredScope, "orchestration:read"); - } - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("includes CORS headers on remote auth success responses", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const origin = crossOriginClientOrigin; - const { response: tokenResponse, body: tokenBody } = yield* exchangeAccessToken( - defaultDesktopBootstrapToken, - { - headers: { origin }, - }, - ); - - assert.equal(tokenResponse.status, 200); - assertBrowserApiCorsResponseHeaders(tokenResponse.headers); - assert.equal(tokenBody.token_type, "Bearer"); - assert.equal(typeof tokenBody.access_token, "string"); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const sessionResponse = yield* fetchEffect(sessionUrl, { - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - origin, - }, - }); - const sessionBody = yield* responseJsonEffect<{ - readonly authenticated: boolean; - readonly sessionMethod?: string; - }>(sessionResponse); - - assert.equal(sessionResponse.status, 200); - assertBrowserApiCorsResponseHeaders(sessionResponse.headers); - assert.equal(sessionBody.authenticated, true); - assert.equal(sessionBody.sessionMethod, "bearer-access-token"); - - const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); - const wsTicketResponse = yield* fetchEffect(wsTicketUrl, { - method: "POST", - headers: { - authorization: `Bearer ${tokenBody.access_token ?? ""}`, - origin, - }, - }); - const wsTicketBody = yield* responseJsonEffect<{ - readonly ticket: string; - }>(wsTicketResponse); - - assert.equal(wsTicketResponse.status, 200); - assertBrowserApiCorsResponseHeaders(wsTicketResponse.headers); - assert.equal(typeof wsTicketBody.ticket, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "responds to remote auth websocket-ticket preflight requests with authorization CORS headers", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); - const response = yield* fetchEffect(wsTicketUrl, { - method: "OPTIONS", - headers: { - origin: crossOriginClientOrigin, - "access-control-request-method": "POST", - "access-control-request-headers": "authorization", - }, - }); - - assert.equal(response.status, 204); - assertBrowserApiCorsPreflightHeaders(response.headers); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("allows credentialed cloud link proof preflights from the configured dev UI", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { devUrl: new URL(crossOriginClientOrigin) }, - }); - - const linkProofUrl = yield* getHttpServerUrl("/api/connect/link-proof"); - const response = yield* fetchEffect(linkProofUrl, { - method: "OPTIONS", - headers: { - origin: crossOriginClientOrigin, - "access-control-request-method": "POST", - "access-control-request-headers": "content-type", - }, - }); - - assert.equal(response.status, 204); - assertBrowserApiCorsPreflightHeaders(response.headers, { - origin: crossOriginClientOrigin, - credentials: true, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("allows configured development origins through ServerConfig", () => - Effect.gen(function* () { - const tailnetOrigin = "https://host.example.ts.net"; - yield* buildAppUnderTest({ - config: { - devUrl: new URL(crossOriginClientOrigin), - devAllowedOrigins: [tailnetOrigin], - }, - }); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const response = yield* fetchEffect(sessionUrl, { - method: "OPTIONS", - headers: { - origin: tailnetOrigin, - "access-control-request-method": "GET", - "access-control-request-headers": "content-type", - }, - }); - - assert.equal(response.status, 204); - assertBrowserApiCorsPreflightHeaders(response.headers, { - origin: tailnetOrigin, - credentials: true, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - for (const desktopOrigin of ["t3code://app", "t3code-dev://app"]) { - it.effect(`allows credentialed preflights from ${desktopOrigin} in development`, () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { devUrl: new URL(crossOriginClientOrigin) }, - }); - - const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); - const response = yield* fetchEffect(sessionUrl, { - method: "OPTIONS", - headers: { - origin: desktopOrigin, - "access-control-request-method": "GET", - "access-control-request-headers": "content-type", - }, - }); - - assert.equal(response.status, 204); - assertBrowserApiCorsPreflightHeaders(response.headers, { - origin: desktopOrigin, - credentials: true, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - } - - it.effect("includes CORS headers on remote websocket-ticket auth failures", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); - const response = yield* fetchEffect(wsTicketUrl, { - method: "POST", - headers: { - origin: crossOriginClientOrigin, - }, - }); - const body = yield* responseJsonEffect<{ - readonly _tag?: string; - readonly code?: string; - readonly reason?: string; - readonly traceId?: string; - }>(response); - - assert.equal(response.status, 401); - assertBrowserApiCorsResponseHeaders(response.headers); - assert.equal(body._tag, "EnvironmentAuthInvalidError"); - assert.equal(body.code, "auth_invalid"); - assert.equal(body.reason, "missing_credential"); - assert.equal(typeof body.traceId, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("issues authenticated one-time pairing credentials for additional clients", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const response = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - }, - body: yield* HttpBody.json({}), - }); - const body = (yield* response.json) as { - readonly credential: string; - readonly expiresAt: string; - }; - - assert.equal(response.status, 200); - assert.equal(typeof body.credential, "string"); - assert.isTrue(body.credential.length > 0); - assert.equal(typeof body.expiresAt, "string"); - - const bootstrapResult = yield* bootstrapBrowserSession(body.credential); - assert.equal(bootstrapResult.response.status, 200); - - const reusedResult = yield* bootstrapBrowserSession(body.credential); - assert.equal(reusedResult.response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("issues pairing credentials for bearer sessions with access management scope", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const bearerToken = yield* getAuthenticatedBearerSessionToken(); - const response = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - authorization: `Bearer ${bearerToken}`, - }, - body: yield* HttpBody.json({ label: "Hosted web" }), - }); - const body = (yield* response.json) as { - readonly credential: string; - readonly label?: string; - }; - - assert.equal(response.status, 200); - assert.isTrue(body.credential.length > 0); - assert.equal(body.label, "Hosted web"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects pairing credentials with an empty scope grant", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const response = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - }, - body: yield* HttpBody.json({ scopes: [] }), - }); - const body = (yield* response.json) as { - readonly code: string; - readonly reason: string; - }; - - assert.equal(response.status, 400); - assert.equal(body.code, "invalid_request"); - assert.equal(body.reason, "invalid_scope"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects unauthenticated pairing credential requests", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const response = yield* HttpClient.post("/api/auth/pairing-token", { - body: yield* HttpBody.json({}), - }); - assert.equal(response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("lists and revokes pairing links for access management sessions", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const createdResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const createdBody = (yield* createdResponse.json) as { - readonly id: string; - readonly credential: string; - }; - - const listResponse = yield* HttpClient.get("/api/auth/pairing-links", { - headers: { - cookie: ownerCookie, - }, - }); - const listedLinks = (yield* listResponse.json) as ReadonlyArray<{ - readonly id: string; - readonly credential: string; - }>; - - const revokeResponse = yield* HttpClient.post("/api/auth/pairing-links/revoke", { - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: HttpBody.text(jsonRequestBody({ id: createdBody.id }), "application/json"), - }); - const revokedBootstrap = yield* bootstrapBrowserSession(createdBody.credential); - - assert.equal(createdResponse.status, 200); - assert.equal(listResponse.status, 200); - assert.isTrue(listedLinks.some((entry) => entry.id === createdBody.id)); - assert.equal(revokeResponse.status, 200); - assert.equal(revokedBootstrap.response.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects pairing credential requests without access management scope", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - }, - body: yield* HttpBody.json({}), - }); - const ownerBody = (yield* ownerResponse.json) as { - readonly credential: string; - }; - assert.equal(ownerResponse.status, 200); - - const pairedSessionCookie = yield* getAuthenticatedSessionCookieHeader(ownerBody.credential); - const pairedResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: pairedSessionCookie, - }, - body: yield* HttpBody.json({}), - }); - const pairedBody = (yield* pairedResponse.json) as { - readonly _tag: string; - readonly code: string; - readonly requiredScope: string; - readonly traceId: string; - }; - - assert.equal(pairedResponse.status, 403); - assert.equal(pairedBody._tag, "EnvironmentScopeRequiredError"); - assert.equal(pairedBody.code, "insufficient_scope"); - assert.equal(pairedBody.requiredScope, "access:write"); - assert.equal(typeof pairedBody.traceId, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("lists paired clients and revokes other sessions while keeping the administrator", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const pairingTokenUrl = yield* getHttpServerUrl("/api/auth/pairing-token"); - const ownerPairingResponse = yield* fetchEffect(pairingTokenUrl, { - method: "POST", - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: jsonRequestBody({ - label: "Julius iPhone", - }), - }); - const ownerPairingBody = yield* responseJsonEffect<{ - readonly credential: string; - readonly label?: string; - }>(ownerPairingResponse); - assert.equal(ownerPairingResponse.status, 200); - const pairedSessionBootstrap = yield* bootstrapBrowserSession(ownerPairingBody.credential, { - headers: { - "user-agent": - "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1", - }, - }); - const pairedSessionCookie = pairedSessionBootstrap.cookie?.split(";")[0]; - assert.isDefined(pairedSessionCookie); - - const pairedSessionCookieHeader = pairedSessionCookie ?? ""; - const listBeforeResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: ownerCookie, - }, - }); - const clientsBefore = (yield* listBeforeResponse.json) as ReadonlyArray<{ - readonly sessionId: string; - readonly current: boolean; - readonly client: { - readonly label?: string; - readonly deviceType: string; - readonly ipAddress?: string; - readonly os?: string; - readonly browser?: string; - }; - }>; - const pairedClientBefore = clientsBefore.find((entry) => !entry.current); - const pairedSessionId = clientsBefore.find((entry) => !entry.current)?.sessionId; - - const revokeOthersResponse = yield* HttpClient.post("/api/auth/clients/revoke-others", { - headers: { - cookie: ownerCookie, - }, - }); - const revokeOthersBody = (yield* revokeOthersResponse.json) as { - readonly revokedCount: number; - }; - - const listAfterResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: ownerCookie, - }, - }); - const clientsAfter = (yield* listAfterResponse.json) as ReadonlyArray<{ - readonly sessionId: string; - readonly current: boolean; - }>; - - const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: pairedSessionCookieHeader, - }, - body: yield* HttpBody.json({}), - }); - const pairedClientPairingBody = (yield* pairedClientPairingResponse.json) as { - readonly _tag: string; - readonly code: string; - readonly reason: string; - readonly traceId: string; - }; - - assert.equal(listBeforeResponse.status, 200); - assert.equal(ownerPairingBody.label, "Julius iPhone"); - assert.lengthOf(clientsBefore, 2); - assert.isDefined(pairedSessionId); - assert.isDefined(pairedClientBefore); - assert.deepInclude(pairedClientBefore?.client, { - label: "Julius iPhone", - deviceType: "mobile", - os: "iOS", - browser: "Safari", - ipAddress: "127.0.0.1", - }); - assert.equal(revokeOthersResponse.status, 200); - assert.equal(revokeOthersBody.revokedCount, 1); - assert.equal(listAfterResponse.status, 200); - assert.lengthOf(clientsAfter, 1); - assert.equal(clientsAfter[0]?.current, true); - assert.equal(pairedClientPairingResponse.status, 401); - assert.equal(pairedClientPairingBody._tag, "EnvironmentAuthInvalidError"); - assert.equal(pairedClientPairingBody.code, "auth_invalid"); - assert.equal(pairedClientPairingBody.reason, "invalid_credential"); - assert.equal(typeof pairedClientPairingBody.traceId, "string"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("separates access inventory reads from credential management writes", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const issueScopedSession = Effect.fnUntraced(function* ( - scope: "access:read" | "access:write", - ) { - const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({ scopes: [scope] }), - }); - assert.equal(pairingResponse.status, 200); - const pairingBody = (yield* pairingResponse.json) as { - readonly credential: string; - }; - return yield* getAuthenticatedSessionCookieHeader(pairingBody.credential); - }); - - const readCookie = yield* issueScopedSession("access:read"); - const readListResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: readCookie, - }, - }); - const readWriteResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: readCookie, - }, - body: yield* HttpBody.json({}), - }); - const readWriteBody = (yield* readWriteResponse.json) as { - readonly requiredScope: string; - }; - - const writeCookie = yield* issueScopedSession("access:write"); - const writeListResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: writeCookie, - }, - }); - const writeListBody = (yield* writeListResponse.json) as { - readonly requiredScope: string; - }; - - assert.equal(readListResponse.status, 200); - assert.equal(readWriteResponse.status, 403); - assert.equal(readWriteBody.requiredScope, "access:write"); - assert.equal(writeListResponse.status, 403); - assert.equal(writeListBody.requiredScope, "access:read"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("revokes an individual paired client session", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - host: "0.0.0.0", - }, - }); - - const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); - const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: ownerCookie, - }, - body: yield* HttpBody.json({}), - }); - const pairingBody = (yield* pairingResponse.json) as { - readonly credential: string; - }; - const pairedSessionCookie = yield* getAuthenticatedSessionCookieHeader( - pairingBody.credential, - ); - - const clientsResponse = yield* HttpClient.get("/api/auth/clients", { - headers: { - cookie: ownerCookie, - }, - }); - const clients = (yield* clientsResponse.json) as ReadonlyArray<{ - readonly sessionId: string; - readonly current: boolean; - }>; - const pairedSessionId = clients.find((entry) => !entry.current)?.sessionId; - assert.isDefined(pairedSessionId); - - const revokeResponse = yield* HttpClient.post("/api/auth/clients/revoke", { - headers: { - cookie: ownerCookie, - "content-type": "application/json", - }, - body: HttpBody.text(jsonRequestBody({ sessionId: pairedSessionId }), "application/json"), - }); - const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { - headers: { - cookie: pairedSessionCookie, - }, - body: yield* HttpBody.json({}), - }); - - assert.equal(revokeResponse.status, 200); - assert.equal(pairedClientPairingResponse.status, 401); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("allows reusing the desktop bootstrap credential", () => - Effect.gen(function* () { - // The desktop-bootstrap grant is delivered over trusted IPC at - // backend launch and needs to stay claimable after a renderer - // refresh, so it's intentionally reusable (unlike user-facing - // one-time pairing credentials). - yield* buildAppUnderTest(); - - const first = yield* bootstrapBrowserSession(); - const second = yield* bootstrapBrowserSession(); - - assert.equal(first.response.status, 200); - assert.equal(second.response.status, 200); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("accepts websocket rpc handshake with a bootstrapped browser session cookie", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { response: bootstrapResponse, cookie } = yield* bootstrapBrowserSession(); - - assert.equal(bootstrapResponse.status, 200); - assert.isDefined(cookie); - - const wsUrl = appendSessionCookieToWsUrl( - yield* getWsServerUrl("/ws", { authenticated: false }), - cookie?.split(";")[0] ?? "", - ); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({})), - ); - - assert.equal(response.environment.environmentId, testEnvironmentDescriptor.environmentId); - assert.equal(response.auth.policy, "desktop-managed-local"); - assert.equal(response.shellResumeCompletionMarker, true); - assert.equal(response.threadResumeCompletionMarker, true); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("does not block server config when editor discovery never resolves", () => - Effect.gen(function* () { - const discoveryInterrupted = yield* Deferred.make(); - const responseFiber = yield* resolveAvailableEditorsForConfig( - Effect.never.pipe( - Effect.onInterrupt(() => Deferred.succeed(discoveryInterrupted, undefined)), - ), - ).pipe(Effect.forkChild); - - yield* TestClock.adjust(Duration.seconds(5)); - - const availableEditors = yield* Fiber.join(responseFiber); - yield* Deferred.await(discoveryInterrupted); - assert.deepEqual(availableEditors, []); - }), - ); - - it.effect( - "rejects websocket rpc handshake when a session token is only provided via query string", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const { cookie } = yield* bootstrapBrowserSession(); - assert.isDefined(cookie); - const sessionToken = extractSessionTokenFromSetCookie(cookie ?? ""); - const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?token=${encodeURIComponent(sessionToken)}`; - - const error = yield* Effect.flip( - Effect.scoped(withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({}))), - ); - - assert.equal(error._tag, "RpcClientError"); - assertInclude(String(error), "SocketOpenError"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "accepts websocket rpc handshake with a dedicated websocket ticket in the query string", - () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const bearerToken = yield* getAuthenticatedBearerSessionToken(); - const wsTicketUrl = yield* getHttpServerUrl("/api/auth/websocket-ticket"); - const wsTicketResponse = yield* fetchEffect(wsTicketUrl, { - method: "POST", - headers: { - authorization: `Bearer ${bearerToken}`, - }, - }); - const wsTicketBody = yield* responseJsonEffect<{ - readonly ticket: string; - }>(wsTicketResponse); - const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsTicket=${encodeURIComponent(wsTicketBody.ticket)}`; - - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({})), - ); - - assert.equal(response.environment.environmentId, testEnvironmentDescriptor.environmentId); - assert.equal(response.auth.policy, "desktop-managed-local"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("proxies browser OTLP trace exports through the server", () => - Effect.gen(function* () { - const upstreamRequests: Array<{ - readonly body: string; - readonly contentType: string | null; - }> = []; - const localTraceRecords: Array = []; - const payload = { - resourceSpans: [ - { - resource: { - attributes: [ - { - key: "service.name", - value: { stringValue: "t3-web" }, - }, - ], - }, - scopeSpans: [ - { - scope: { - name: "effect", - version: "4.0.0-beta.43", - }, - spans: [ - { - traceId: "11111111111111111111111111111111", - spanId: "2222222222222222", - parentSpanId: "3333333333333333", - name: "RpcClient.server.getSettings", - kind: 3, - startTimeUnixNano: "1000000", - endTimeUnixNano: "2000000", - attributes: [ - { - key: "rpc.method", - value: { stringValue: "server.getSettings" }, - }, - ], - events: [ - { - name: "http.request", - timeUnixNano: "1500000", - attributes: [ - { - key: "http.status_code", - value: { intValue: "200" }, - }, - ], - }, - ], - links: [], - status: { - code: "STATUS_CODE_OK", - }, - flags: 1, - }, - ], - }, - ], - }, - ], - }; - - const collector = yield* Effect.acquireRelease( - Effect.promise(async () => { - const NodeHttp = await import("node:http"); - - return await new Promise<{ - readonly close: () => Promise; - readonly url: string; - }>((resolve, reject) => { - const server = NodeHttp.createServer((request, response) => { - const chunks: Buffer[] = []; - request.on("data", (chunk) => { - chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); - }); - request.on("end", () => { - upstreamRequests.push({ - body: Buffer.concat(chunks).toString("utf8"), - contentType: request.headers["content-type"] ?? null, - }); - response.statusCode = 204; - response.end(); - }); - }); - - server.on("error", reject); - server.listen(0, "127.0.0.1", () => { - const address = server.address(); - if (!address || typeof address === "string") { - reject(new Error("Expected TCP collector address")); - return; - } - - resolve({ - url: `http://127.0.0.1:${address.port}/v1/traces`, - close: () => - new Promise((resolveClose, rejectClose) => { - server.close((error) => { - if (error) { - rejectClose(error); - return; - } - resolveClose(); - }); - }), - }); - }); - }); - }), - ({ close }) => Effect.promise(close), - ); - - yield* buildAppUnderTest({ - config: { - otlpTracesUrl: collector.url, - }, - layers: { - browserTraceCollector: { - record: (records) => - Effect.sync(() => { - localTraceRecords.push(...records); - }), - }, - }, - }); - - const response = yield* HttpClient.post("/api/observability/v1/traces", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - "content-type": "application/json", - origin: "http://localhost:5733", - }, - // @effect-diagnostics-next-line preferSchemaOverJson:off - body: HttpBody.text(JSON.stringify(payload), "application/json"), - }); - - assert.equal(response.status, 204); - assert.equal(response.headers["access-control-allow-origin"], "*"); - assert.deepEqual(localTraceRecords, [ - { - type: "otlp-span", - name: "RpcClient.server.getSettings", - traceId: "11111111111111111111111111111111", - spanId: "2222222222222222", - parentSpanId: "3333333333333333", - sampled: true, - kind: "client", - startTimeUnixNano: "1000000", - endTimeUnixNano: "2000000", - durationMs: 1, - attributes: { - "rpc.method": "server.getSettings", - }, - resourceAttributes: { - "service.name": "t3-web", - }, - scope: { - name: "effect", - version: "4.0.0-beta.43", - attributes: {}, - }, - events: [ - { - name: "http.request", - timeUnixNano: "1500000", - attributes: { - "http.status_code": "200", - }, - }, - ], - links: [], - status: { - code: "STATUS_CODE_OK", - }, - }, - ]); - assert.deepEqual(upstreamRequests, [ - { - body: jsonRequestBody(payload), - contentType: "application/json", - }, - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("responds to browser OTLP trace preflight requests with CORS headers", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const response = yield* HttpClient.options("/api/observability/v1/traces", { - headers: { - origin: "http://localhost:5733", - "access-control-request-method": "POST", - "access-control-request-headers": "content-type", - }, - }); - - assert.equal(response.status, 204); - assert.equal(response.headers["access-control-allow-origin"], "*"); - assert.deepEqual(splitHeaderTokens(response.headers["access-control-allow-methods"]), [ - "GET", - "OPTIONS", - "POST", - ]); - assert.deepEqual(splitHeaderTokens(response.headers["access-control-allow-headers"]), [ - "authorization", - "b3", - "content-type", - "dpop", - "traceparent", - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "stores browser OTLP trace exports locally when no upstream collector is configured", - () => - Effect.gen(function* () { - const localTraceRecords: Array = []; - const payload = yield* makeBrowserOtlpPayload("client.test"); - const resourceSpan = payload.resourceSpans[0]; - const scopeSpan = resourceSpan?.scopeSpans[0]; - const span = scopeSpan?.spans[0]; - - assert.notEqual(resourceSpan, undefined); - assert.notEqual(scopeSpan, undefined); - assert.notEqual(span, undefined); - if (!resourceSpan || !scopeSpan || !span) { - return; - } - - yield* buildAppUnderTest({ - layers: { - browserTraceCollector: { - record: (records) => - Effect.sync(() => { - localTraceRecords.push(...records); - }), - }, - }, - }); - - const response = yield* HttpClient.post("/api/observability/v1/traces", { - headers: { - cookie: yield* getAuthenticatedSessionCookieHeader(), - "content-type": "application/json", - }, - // @effect-diagnostics-next-line preferSchemaOverJson:off - body: HttpBody.text(JSON.stringify(payload), "application/json"), - }); - - assert.equal(response.status, 204); - assert.equal(localTraceRecords.length, 1); - const record = localTraceRecords[0] as { - readonly type: string; - readonly name: string; - readonly traceId: string; - readonly spanId: string; - readonly kind: string; - readonly attributes: Readonly>; - readonly events: ReadonlyArray; - readonly links: ReadonlyArray; - readonly scope: { - readonly name?: string; - readonly attributes: Readonly>; - }; - readonly resourceAttributes: Readonly>; - readonly status?: { - readonly code?: string; - }; - }; - - assert.equal(record.type, "otlp-span"); - assert.equal(record.name, span.name); - assert.equal(record.traceId, span.traceId); - assert.equal(record.spanId, span.spanId); - assert.equal(record.kind, "internal"); - assert.deepEqual(record.attributes, {}); - assert.deepEqual(record.events, []); - assert.deepEqual(record.links, []); - assert.equal(record.scope.name, scopeSpan.scope.name); - assert.deepEqual(record.scope.attributes, {}); - assert.equal(record.resourceAttributes["service.name"], "t3-web"); - assert.equal(record.status?.code, String(span.status.code)); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc server.upsertKeybinding", () => - Effect.gen(function* () { - const rule: KeybindingRule = { - command: "terminal.toggle", - key: "ctrl+k", - }; - const resolved: ResolvedKeybindingRule = { - command: "terminal.toggle", - shortcut: { - key: "k", - metaKey: false, - ctrlKey: true, - shiftKey: false, - altKey: false, - modKey: true, - }, - }; - - yield* buildAppUnderTest({ - layers: { - keybindings: { - upsertKeybindingRule: () => Effect.succeed([resolved]), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverUpsertKeybinding](rule)), - ); - - assert.deepEqual(response.issues, []); - assert.deepEqual(response.keybindings, [resolved]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc server.removeKeybinding", () => - Effect.gen(function* () { - const rule: KeybindingRule = { - command: "terminal.toggle", - key: "ctrl+k", - }; - const resolved: ResolvedKeybindingRule = { - command: "terminal.toggle", - shortcut: { - key: "j", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - }; - - yield* buildAppUnderTest({ - layers: { - keybindings: { - removeKeybindingRule: () => Effect.succeed([resolved]), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverRemoveKeybinding](rule)), - ); - - assert.deepEqual(response.issues, []); - assert.deepEqual(response.keybindings, [resolved]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("shares one preview automation broker across websocket sessions", () => - Effect.scoped( - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const firstConnected = yield* Deferred.make(); - const firstClosed = yield* Deferred.make(); - const host = { - clientId: "shared-preview-host", - environmentId: testEnvironmentDescriptor.environmentId, - } as const; - - yield* withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.previewAutomationConnect](host).pipe( - Stream.tap((event) => - event.type === "connected" - ? Deferred.succeed(firstConnected, event.connectionId) - : Effect.void, - ), - Stream.runDrain, - Effect.ensuring(Deferred.succeed(firstClosed, undefined)), - ), - ).pipe(Effect.forkScoped); - - const firstConnectionId = yield* Deferred.await(firstConnected); - const replacementEvent = yield* withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.previewAutomationConnect](host).pipe(Stream.runHead), - ).pipe(Effect.map(Option.getOrThrow)); - const firstStreamClosed = yield* Deferred.await(firstClosed).pipe( - Effect.timeoutOption("2 seconds"), - ); - - assert.equal(replacementEvent.type, "connected"); - assert.notEqual(replacementEvent.connectionId, firstConnectionId); - assert.isTrue(Option.isSome(firstStreamClosed)); - }), - ).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("rejects websocket rpc handshake when session authentication is missing", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-auth-required-" }); - yield* fs.writeFileString( - path.join(workspaceDir, "needle-file.ts"), - "export const needle = 1;", - ); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws", { authenticated: false }); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsSearchEntries]({ - cwd: workspaceDir, - query: "needle", - limit: 10, - }), - ).pipe(Effect.result), - ); - - assertTrue(result._tag === "Failure"); - const failureMessage = String(result.failure); - assertTrue( - failureMessage.includes("SocketOpenError") || failureMessage.includes("SocketCloseError"), - ); - assertTrue( - failureMessage.includes("Unauthorized") || - failureMessage.includes("An error occurred during Open"), - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () => - Effect.gen(function* () { - const providers = [ - { - instanceId: ProviderInstanceId.make("codex"), - driver: ProviderDriverKind.make("codex"), - enabled: true, - installed: true, - version: "1.0.0", - status: "ready" as const, - auth: { status: "authenticated" as const }, - checkedAt: "2026-04-11T00:00:00.000Z", - models: [], - slashCommands: [], - skills: [], - }, - ] as const; - const changeEvent = { - keybindings: [], - issues: [], - } as const; - - yield* buildAppUnderTest({ - config: { - otlpTracesUrl: "http://localhost:4318/v1/traces", - otlpMetricsUrl: "http://localhost:4318/v1/metrics", - }, - layers: { - keybindings: { - loadConfigState: Effect.succeed({ - keybindings: [], - issues: [], - }), - streamChanges: Stream.succeed(changeEvent), - }, - providerRegistry: { - getProviders: Effect.succeed(providers), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const events = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(events); - assert.equal(first?.type, "snapshot"); - if (first?.type === "snapshot") { - assert.equal(first.version, 1); - assert.deepEqual(first.config.keybindings, []); - assert.deepEqual(first.config.issues, []); - assert.deepEqual(first.config.providers, providers); - assert.equal(first.config.observability.logsDirectoryPath.endsWith("/logs"), true); - assert.equal(first.config.observability.localTracingEnabled, true); - assert.equal(first.config.observability.otlpTracesUrl, "http://localhost:4318/v1/traces"); - assert.equal(first.config.observability.otlpTracesEnabled, true); - assert.equal(first.config.observability.otlpMetricsUrl, "http://localhost:4318/v1/metrics"); - assert.equal(first.config.observability.otlpMetricsEnabled, true); - assert.deepEqual(first.config.settings, DEFAULT_SERVER_SETTINGS); - } - assert.deepEqual(second, { - version: 1, - type: "keybindingsUpdated", - payload: { keybindings: [], issues: [] }, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket resource telemetry through the subscription", () => - Effect.gen(function* () { - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const snapshot = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.subscribeResourceTelemetry]({}).pipe(Stream.runHead), - ), - ); - - assertTrue(Option.isSome(snapshot)); - assert.equal(snapshot.value.processes.length, 0); - assert.equal(snapshot.value.groups.backend.processCount, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc subscribeServerConfig emits provider status updates", () => - Effect.gen(function* () { - const nextProviders = [ - { - instanceId: ProviderInstanceId.make("codex"), - driver: ProviderDriverKind.make("codex"), - enabled: true, - installed: true, - version: "1.0.0", - status: "ready" as const, - auth: { status: "authenticated" as const }, - checkedAt: "2026-04-11T00:00:00.000Z", - models: [], - slashCommands: [], - skills: [], - }, - ] as const; - - yield* buildAppUnderTest({ - layers: { - keybindings: { - loadConfigState: Effect.succeed({ - keybindings: [], - issues: [], - }), - streamChanges: Stream.empty, - }, - providerRegistry: { - getProviders: Effect.succeed([]), - streamChanges: Stream.succeed(nextProviders), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const events = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(events); - assert.equal(first?.type, "snapshot"); - if (first?.type === "snapshot") { - assert.deepEqual(first.config.providers, []); - } - assert.deepEqual(second, { - version: 1, - type: "providerStatuses", - payload: { providers: nextProviders }, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "routes websocket rpc subscribeServerLifecycle replays snapshot and streams updates", - () => - Effect.gen(function* () { - const lifecycleEvents = [ - { - version: 1 as const, - sequence: 1, - type: "welcome" as const, - payload: { - environment: testEnvironmentDescriptor, - cwd: "/tmp/project", - projectName: "project", - }, - }, - ] as const; - const liveEvents = Stream.make({ - version: 1 as const, - sequence: 2, - type: "ready" as const, - payload: { at: "2026-01-01T00:00:00.000Z", environment: testEnvironmentDescriptor }, - }); - - yield* buildAppUnderTest({ - layers: { - serverLifecycleEvents: { - snapshot: Effect.succeed({ - sequence: 1, - events: lifecycleEvents, - }), - stream: liveEvents, - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const events = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.subscribeServerLifecycle]({}).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(events); - assert.equal(first?.type, "welcome"); - assert.equal(first?.sequence, 1); - assert.equal(second?.type, "ready"); - assert.equal(second?.sequence, 2); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc projects.searchEntries", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-search-" }); - yield* fs.writeFileString( - path.join(workspaceDir, "needle-file.ts"), - "export const needle = 1;", - ); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsSearchEntries]({ - cwd: workspaceDir, - query: "needle", - limit: 10, - }), - ), - ); - - assert.isAtLeast(response.entries.length, 1); - assert.isTrue(response.entries.some((entry) => entry.path === "needle-file.ts")); - assert.equal(response.truncated, false); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("routes websocket rpc projects.listEntries and projects.readFile", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-files-" }); - yield* fs.makeDirectory(path.join(workspaceDir, "src"), { recursive: true }); - yield* fs.writeFileString( - path.join(workspaceDir, "src", "index.ts"), - "export const answer = 42;\n", - ); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - Effect.all({ - listing: client[WS_METHODS.projectsListEntries]({ cwd: workspaceDir }), - file: client[WS_METHODS.projectsReadFile]({ - cwd: workspaceDir, - relativePath: "src/index.ts", - }), - }), - ), - ); - - assert.isTrue(response.listing.entries.some((entry) => entry.path === "src/index.ts")); - assert.deepEqual(response.file, { - relativePath: "src/index.ts", - contents: "export const answer = 42;\n", - byteLength: 26, - truncated: false, - }); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("routes websocket rpc projects.searchEntries excludes gitignored files", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ - prefix: "t3-ws-project-search-gitignored-", - }); - yield* fs.writeFileString(path.join(workspaceDir, ".gitignore"), ".venv/\n"); - yield* fs.makeDirectory(path.join(workspaceDir, ".venv", "lib"), { recursive: true }); - yield* fs.writeFileString( - path.join(workspaceDir, ".venv", "lib", "ignored-search-target.ts"), - "export const ignored = true;", - ); - yield* fs.makeDirectory(path.join(workspaceDir, "src"), { recursive: true }); - yield* fs.writeFileString( - path.join(workspaceDir, "src", "tracked.ts"), - "export const ok = 1;", - ); - - yield* buildAppUnderTest({ - layers: { - vcsDriver: { - isInsideWorkTree: () => Effect.succeed(true), - listWorkspaceFiles: () => - Effect.succeed({ - paths: ["src/tracked.ts"], - truncated: false, - freshness: { - source: "live-local", - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - }), - filterIgnoredPaths: (_cwd, relativePaths) => - Effect.succeed( - relativePaths.filter((relativePath) => !relativePath.startsWith(".venv/")), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsSearchEntries]({ - cwd: workspaceDir, - query: "ignored-search-target", - limit: 10, - }), - ), - ); - - assert.equal(response.entries.length, 0); - assert.equal(response.truncated, false); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("preserves structured workspace rpc failures", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ - prefix: "t3-ws-workspace-errors-", - }); - const outsideDir = yield* fs.makeTempDirectoryScoped({ - prefix: "t3-ws-workspace-errors-outside-", - }); - const outsideFile = path.join(outsideDir, "outside.txt"); - yield* fs.writeFileString(outsideFile, "outside\n"); - yield* fs.symlink(outsideFile, path.join(workspaceDir, "linked-outside.txt")); - const resolvedOutsideFile = yield* fs.realPath(outsideFile); - - yield* buildAppUnderTest(); - - const invalidWorkspace = path.join(workspaceDir, "missing-workspace"); - const missingBrowseParent = path.join(workspaceDir, "missing-browse"); - const sensitiveQuery = "authorization: Bearer secret-token"; - const wsUrl = yield* getWsServerUrl("/ws"); - const results = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - Effect.all({ - search: client[WS_METHODS.projectsSearchEntries]({ - cwd: invalidWorkspace, - query: sensitiveQuery, - limit: 10, - }).pipe(Effect.result), - list: client[WS_METHODS.projectsListEntries]({ cwd: invalidWorkspace }).pipe( - Effect.result, - ), - read: client[WS_METHODS.projectsReadFile]({ - cwd: workspaceDir, - relativePath: "linked-outside.txt", - }).pipe(Effect.result), - browse: client[WS_METHODS.filesystemBrowse]({ - cwd: workspaceDir, - partialPath: "./missing-browse/child", - }).pipe(Effect.result), - }), - ), - ); - - if ( - results.search._tag !== "Failure" || - results.search.failure._tag !== "ProjectSearchEntriesError" - ) { - assert.fail("Expected a ProjectSearchEntriesError"); - } - const searchError = results.search.failure; - assert.equal( - searchError.message, - `Failed to search workspace entries in '${invalidWorkspace}'.`, - ); - assert.equal(searchError.cwd, invalidWorkspace); - assert.equal(searchError.queryLength, sensitiveQuery.length); - assert.notProperty(searchError, "query"); - assert.notInclude(searchError.message, "Bearer"); - assert.notInclude(searchError.message, "secret-token"); - assert.equal(searchError.limit, 10); - assert.equal(searchError.failure, "workspace_root_not_found"); - assert.equal(searchError.normalizedCwd, invalidWorkspace); - assert.isDefined(searchError.cause); - - if ( - results.list._tag !== "Failure" || - results.list.failure._tag !== "ProjectListEntriesError" - ) { - assert.fail("Expected a ProjectListEntriesError"); - } - const listError = results.list.failure; - assert.equal(listError.message, `Failed to list workspace entries in '${invalidWorkspace}'.`); - assert.equal(listError.cwd, invalidWorkspace); - assert.equal(listError.failure, "workspace_root_not_found"); - assert.equal(listError.normalizedCwd, invalidWorkspace); - assert.isDefined(listError.cause); - - if (results.read._tag !== "Failure" || results.read.failure._tag !== "ProjectReadFileError") { - assert.fail("Expected a ProjectReadFileError"); - } - const readError = results.read.failure; - assert.equal( - readError.message, - `Failed to read workspace file 'linked-outside.txt' in '${workspaceDir}'.`, - ); - assert.equal(readError.cwd, workspaceDir); - assert.equal(readError.relativePath, "linked-outside.txt"); - assert.equal(readError.failure, "resolved_path_outside_root"); - assert.equal(readError.resolvedPath, resolvedOutsideFile); - assert.isDefined(readError.cause); - - if ( - results.browse._tag !== "Failure" || - results.browse.failure._tag !== "FilesystemBrowseError" - ) { - assert.fail("Expected a FilesystemBrowseError"); - } - const browseError = results.browse.failure; - assert.equal( - browseError.message, - `Failed to browse filesystem path './missing-browse/child' from '${workspaceDir}'.`, - ); - assert.equal(browseError.cwd, workspaceDir); - assert.equal(browseError.partialPath, "./missing-browse/child"); - assert.equal(browseError.failure, "read_directory_failed"); - assert.equal(browseError.parentPath, missingBrowseParent); - assert.isDefined(browseError.cause); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("reports workspace root stat failures without relabeling them as missing", () => - Effect.gen(function* () { - if ((yield* HostProcessPlatform) === "win32") return; - - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const blockedRoot = yield* fs.makeTempDirectoryScoped({ - prefix: "t3-ws-workspace-stat-error-", - }); - const workspaceRoot = path.join(blockedRoot, "workspace"); - yield* fs.makeDirectory(workspaceRoot); - yield* fs.chmod(blockedRoot, 0o000); - - const result = yield* Effect.gen(function* () { - yield* buildAppUnderTest(); - const wsUrl = yield* getWsServerUrl("/ws"); - return yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsListEntries]({ cwd: workspaceRoot }).pipe(Effect.result), - ), - ); - }).pipe(Effect.ensuring(fs.chmod(blockedRoot, 0o700).pipe(Effect.ignore))); - - if (result._tag !== "Failure" || result.failure._tag !== "ProjectListEntriesError") { - assert.fail("Expected a ProjectListEntriesError"); - } - const error = result.failure; - assert.equal(error.failure, "workspace_root_stat_failed"); - assert.equal(error.normalizedCwd, workspaceRoot); - assert.equal(error.detail, "validate-existing"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc projects.writeFile", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-write-" }); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsWriteFile]({ - cwd: workspaceDir, - relativePath: "nested/created.txt", - contents: "written-by-rpc", - }), - ), - ); - - assert.equal(response.relativePath, "nested/created.txt"); - const persisted = yield* fs.readFileString(path.join(workspaceDir, "nested", "created.txt")); - assert.equal(persisted, "written-by-rpc"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("creates a missing workspace root during websocket project.create dispatch", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const parentDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-create-" }); - const missingWorkspaceRoot = path.join(parentDir, "nested", "new-project"); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "project.create", - commandId: CommandId.make("cmd-project-create-missing-root"), - projectId: ProjectId.make("project-create-missing-root"), - title: "New Project", - workspaceRoot: missingWorkspaceRoot, - createWorkspaceRootIfMissing: true, - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5-codex", - }, - createdAt: "2026-01-01T00:00:00.000Z", - }), - ), - ); - const stat = yield* fs.stat(missingWorkspaceRoot); - - assert.isAtLeast(response.sequence, 0); - assert.equal(stat.type, "Directory"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc projects.writeFile errors", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-project-write-" }); - - yield* buildAppUnderTest(); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsWriteFile]({ - cwd: workspaceDir, - relativePath: "../escape.txt", - contents: "nope", - }), - ).pipe(Effect.result), - ); - - if (result._tag !== "Failure" || result.failure._tag !== "ProjectWriteFileError") { - assert.fail("Expected a ProjectWriteFileError"); - } - const writeError = result.failure; - assert.equal( - writeError.message, - `Failed to write workspace file '../escape.txt' in '${workspaceDir}'.`, - ); - assert.equal(writeError.cwd, workspaceDir); - assert.equal(writeError.relativePath, "../escape.txt"); - assert.equal(writeError.failure, "workspace_path_outside_root"); - assert.isDefined(writeError.cause); - assert.notProperty(writeError, "contents"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc shell.openInEditor", () => - Effect.gen(function* () { - let openedInput: { cwd: string; editor: EditorId } | null = null; - yield* buildAppUnderTest({ - layers: { - externalLauncher: { - launchEditor: (input) => - Effect.sync(() => { - openedInput = input; - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.shellOpenInEditor]({ - cwd: "/tmp/project", - editor: "cursor", - }), - ), - ); - - assert.deepEqual(openedInput, { cwd: "/tmp/project", editor: "cursor" }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc shell.openInEditor errors", () => - Effect.gen(function* () { - const externalLauncherError = new ExternalLauncherCommandNotFoundError({ - editor: "cursor", - command: "cursor", - }); - yield* buildAppUnderTest({ - layers: { - externalLauncher: { - launchEditor: () => Effect.fail(externalLauncherError), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.shellOpenInEditor]({ - cwd: "/tmp/project", - editor: "cursor", - }), - ).pipe(Effect.result), - ); - - assertFailure(result, externalLauncherError); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc git methods", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - config: { - cwd: "/tmp/repo", - }, - layers: { - vcsDriver: { - isInsideWorkTree: () => Effect.succeed(true), - }, - gitManager: { - invalidateLocalStatus: () => Effect.void, - invalidateRemoteStatus: () => Effect.void, - invalidateStatus: () => Effect.void, - localStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - remoteStatus: () => - Effect.succeed({ - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - status: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - runStackedAction: (input, options) => - Effect.gen(function* () { - const result = { - action: "commit" as const, - branch: { status: "skipped_not_requested" as const }, - commit: { - status: "created" as const, - commitSha: "abc123", - subject: "feat: demo", - }, - push: { status: "skipped_not_requested" as const }, - pr: { status: "skipped_not_requested" as const }, - toast: { - title: "Committed abc123", - description: "feat: demo", - cta: { - kind: "run_action" as const, - label: "Push", - action: { - kind: "push" as const, - }, - }, - }, - }; - - yield* ( - options?.progressReporter?.publish({ - actionId: options.actionId ?? input.actionId, - cwd: input.cwd, - action: input.action, - kind: "phase_started", - phase: "commit", - label: "Committing...", - }) ?? Effect.void - ); - - yield* ( - options?.progressReporter?.publish({ - actionId: options.actionId ?? input.actionId, - cwd: input.cwd, - action: input.action, - kind: "action_finished", - result, - }) ?? Effect.void - ); - - return result; - }), - resolvePullRequest: () => - Effect.succeed({ - pullRequest: { - number: 1, - title: "Demo PR", - url: "https://example.com/pr/1", - baseBranch: "main", - headBranch: "feature/demo", - state: "open", - }, - }), - preparePullRequestThread: () => - Effect.succeed({ - pullRequest: { - number: 1, - title: "Demo PR", - url: "https://example.com/pr/1", - baseBranch: "main", - headBranch: "feature/demo", - state: "open", - }, - branch: "feature/demo", - worktreePath: null, - isOnPullRequestHead: true, - }), - }, - gitVcsDriver: { - pullCurrentBranch: () => - Effect.succeed({ - status: "pulled", - refName: "main", - upstreamRef: "origin/main", - }), - listRefs: () => - Effect.succeed({ - refs: [ - { - name: "main", - current: true, - isDefault: true, - worktreePath: null, - }, - ], - isRepo: true, - hasPrimaryRemote: true, - nextCursor: null, - totalCount: 1, - }), - createWorktree: () => - Effect.succeed({ - worktree: { path: "/tmp/wt", refName: "feature/demo" }, - }), - removeWorktree: () => Effect.void, - createRef: (input) => Effect.succeed({ refName: input.refName }), - switchRef: (input) => Effect.succeed({ refName: input.refName }), - }, - vcsStatusBroadcaster: { - refreshStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - }, - reviewService: { - getDiffPreview: (input) => - Effect.succeed({ - cwd: input.cwd, - generatedAt: DateTime.nowUnsafe(), - sources: [ - { - id: "working-tree", - kind: "working-tree", - title: "Dirty worktree", - baseRef: "HEAD", - headRef: null, - diff: "dirty-diff", - diffHash: "hash-dirty", - truncated: false, - }, - { - id: "branch-range", - kind: "branch-range", - title: "Against main", - baseRef: "main", - headRef: "feature/demo", - diff: "base-diff", - diffHash: "hash-base", - truncated: false, - }, - ], - }), - getDiffFileContents: () => - Effect.succeed({ - oldContents: "before\n", - newContents: "after\n", - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - - const pull = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })), - ); - assert.equal(pull.status, "pulled"); - - const refreshedStatus = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsRefreshStatus]({ cwd: "/tmp/repo" }), - ), - ); - assert.equal(refreshedStatus.isRepo, true); - - const stackedEvents = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitRunStackedAction]({ - actionId: "action-1", - cwd: "/tmp/repo", - action: "commit", - }).pipe( - Stream.runCollect, - Effect.map((events) => Array.from(events)), - ), - ), - ); - const lastStackedEvent = stackedEvents.at(-1); - assert.equal(lastStackedEvent?.kind, "action_finished"); - if (lastStackedEvent?.kind === "action_finished") { - assert.equal(lastStackedEvent.result.action, "commit"); - } - - const resolvedPr = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitResolvePullRequest]({ - cwd: "/tmp/repo", - reference: "1", - }), - ), - ); - assert.equal(resolvedPr.pullRequest.number, 1); - - const prepared = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitPreparePullRequestThread]({ - cwd: "/tmp/repo", - reference: "1", - mode: "local", - }), - ), - ); - assert.equal(prepared.branch, "feature/demo"); - - const refs = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsListRefs]({ cwd: "/tmp/repo" })), - ); - assert.equal(refs.refs[0]?.name, "main"); - - const worktree = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsCreateWorktree]({ - cwd: "/tmp/repo", - refName: "main", - path: null, - }), - ), - ); - assert.equal(worktree.worktree.refName, "feature/demo"); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsRemoveWorktree]({ - cwd: "/tmp/repo", - path: "/tmp/wt", - }), - ), - ); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsCreateRef]({ - cwd: "/tmp/repo", - refName: "feature/new", - }), - ), - ); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsSwitchRef]({ - cwd: "/tmp/repo", - refName: "main", - }), - ), - ); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.vcsInit]({ - cwd: "/tmp/repo", - }), - ), - ); - - const diffPreview = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.reviewGetDiffPreview]({ cwd: "/tmp/repo" }), - ), - ); - assert.equal(diffPreview.sources[0]?.diff, "dirty-diff"); - - const diffFileContents = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.reviewGetDiffFileContents]({ - cwd: "/tmp/repo", - sourceKind: "working-tree", - changeType: "change", - baseRef: "HEAD", - headRef: null, - oldPath: "README.md", - newPath: "README.md", - }), - ), - ); - assert.equal(diffFileContents.oldContents, "before\n"); - assert.equal(diffFileContents.newContents, "after\n"); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc git.pull errors", () => - Effect.gen(function* () { - const gitError = new GitCommandError({ - operation: "pull", - command: "git pull --ff-only", - cwd: "/tmp/repo", - detail: "upstream missing", - }); - let invalidationCalls = 0; - let statusCalls = 0; - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - pullCurrentBranch: () => Effect.fail(gitError), - }, - gitManager: { - invalidateLocalStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - invalidateRemoteStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - invalidateStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - localStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: true, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - remoteStatus: () => - Effect.sync(() => { - statusCalls += 1; - return { - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }; - }), - status: () => - Effect.sync(() => { - statusCalls += 1; - return { - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: true, - workingTree: { files: [], insertions: 0, deletions: 0 }, - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }; - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })).pipe( - Effect.result, - ), - ); - - assertFailure(result, gitError); - assert.equal(invalidationCalls, 0); - assert.equal(statusCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc git.runStackedAction errors after refreshing git status", () => - Effect.gen(function* () { - const gitError = new GitCommandError({ - operation: "commit", - command: "git commit", - cwd: "/tmp/repo", - detail: "nothing to commit", - }); - let invalidationCalls = 0; - let statusCalls = 0; - yield* buildAppUnderTest({ - layers: { - gitManager: { - invalidateLocalStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - invalidateRemoteStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - invalidateStatus: () => - Effect.sync(() => { - invalidationCalls += 1; - }), - localStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: false, - refName: "feature/demo", - hasWorkingTreeChanges: true, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - remoteStatus: () => - Effect.sync(() => { - statusCalls += 1; - return { - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }; - }), - status: () => - Effect.sync(() => { - statusCalls += 1; - return { - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: false, - refName: "feature/demo", - hasWorkingTreeChanges: true, - workingTree: { files: [], insertions: 0, deletions: 0 }, - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }; - }), - runStackedAction: () => Effect.fail(gitError), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitRunStackedAction]({ - actionId: "action-1", - cwd: "/tmp/repo", - action: "commit", - }).pipe(Stream.runCollect, Effect.result), - ), - ); - - assertFailure(result, gitError); - assert.equal(invalidationCalls, 0); - assert.equal(statusCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("completes websocket rpc git.pull before background git status refresh finishes", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - pullCurrentBranch: () => - Effect.succeed({ - status: "pulled" as const, - refName: "main", - upstreamRef: "origin/main", - }), - }, - gitManager: { - invalidateLocalStatus: () => Effect.void, - invalidateRemoteStatus: () => Effect.void, - invalidateStatus: () => Effect.void, - localStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: true, - refName: "main", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - remoteStatus: () => - Effect.sleep(Duration.seconds(2)).pipe( - Effect.as({ - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const startedAt = yield* Clock.currentTimeMillis; - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => client[WS_METHODS.vcsPull]({ cwd: "/tmp/repo" })), - ); - const elapsedMs = (yield* Clock.currentTimeMillis) - startedAt; - - assert.equal(result.status, "pulled"); - assertTrue(elapsedMs < 1_000); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "completes websocket rpc git.runStackedAction before background git status refresh finishes", - () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - layers: { - vcsDriver: { - isInsideWorkTree: () => Effect.succeed(true), - }, - gitManager: { - invalidateLocalStatus: () => Effect.void, - invalidateRemoteStatus: () => Effect.void, - invalidateStatus: () => Effect.void, - localStatus: () => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: false, - refName: "feature/demo", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - remoteStatus: () => - Effect.sleep(Duration.seconds(2)).pipe( - Effect.as({ - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - ), - runStackedAction: () => - Effect.succeed({ - action: "commit" as const, - branch: { status: "skipped_not_requested" as const }, - commit: { - status: "created" as const, - commitSha: "abc123", - subject: "feat: demo", - }, - push: { status: "skipped_not_requested" as const }, - pr: { status: "skipped_not_requested" as const }, - toast: { - title: "Committed abc123", - description: "feat: demo", - cta: { - kind: "run_action" as const, - label: "Push", - action: { - kind: "push" as const, - }, - }, - }, - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const startedAt = yield* Clock.currentTimeMillis; - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitRunStackedAction]({ - actionId: "action-1", - cwd: "/tmp/repo", - action: "commit", - }).pipe(Stream.runCollect), - ), - ); - const elapsedMs = (yield* Clock.currentTimeMillis) - startedAt; - - assertTrue(elapsedMs < 1_000); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "starts a background local git status refresh after a successful git.runStackedAction", - () => - Effect.gen(function* () { - const localRefreshStarted = yield* Deferred.make(); - - yield* buildAppUnderTest({ - layers: { - vcsDriver: { - isInsideWorkTree: () => Effect.succeed(true), - }, - gitManager: { - invalidateLocalStatus: () => Effect.void, - invalidateRemoteStatus: () => Effect.void, - invalidateStatus: () => Effect.void, - localStatus: () => - Deferred.succeed(localRefreshStarted, undefined).pipe( - Effect.ignore, - Effect.andThen( - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: false, - refName: "feature/demo", - hasWorkingTreeChanges: false, - workingTree: { files: [], insertions: 0, deletions: 0 }, - }), - ), - ), - remoteStatus: () => - Effect.sleep(Duration.seconds(2)).pipe( - Effect.as({ - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - ), - runStackedAction: () => - Effect.succeed({ - action: "commit" as const, - branch: { status: "skipped_not_requested" as const }, - commit: { - status: "created" as const, - commitSha: "abc123", - subject: "feat: demo", - }, - push: { status: "skipped_not_requested" as const }, - pr: { status: "skipped_not_requested" as const }, - toast: { - title: "Committed abc123", - description: "feat: demo", - cta: { - kind: "run_action" as const, - label: "Push", - action: { - kind: "push" as const, - }, - }, - }, - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.gitRunStackedAction]({ - actionId: "action-1", - cwd: "/tmp/repo", - action: "commit", - }).pipe(Stream.runCollect), - ), - ); - - yield* Deferred.await(localRefreshStarted); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc orchestration methods", () => - Effect.gen(function* () { - const now = "2026-01-01T00:00:00.000Z"; - const snapshot = { - snapshotSequence: 1, - updatedAt: now, - projects: [ - { - id: ProjectId.make("project-a"), - title: "Project A", - workspaceRoot: "/tmp/project-a", - defaultModelSelection, - scripts: [], - createdAt: now, - updatedAt: now, - deletedAt: null, - }, - ], - threads: [ - { - id: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-a"), - title: "Thread A", - modelSelection: defaultModelSelection, - interactionMode: "default" as const, - runtimeMode: "full-access" as const, - branch: null, - worktreePath: null, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - latestTurn: null, - messages: [], - session: null, - activities: [], - proposedPlans: [], - checkpoints: [], - deletedAt: null, - }, - ], - }; - - yield* buildAppUnderTest({ - layers: { - projectionSnapshotQuery: { - getSnapshot: () => Effect.succeed(snapshot), - searchThreads: () => - Effect.succeed({ - matches: [ - { - threadId: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-a"), - source: "assistant", - snippet: "Search reached the final response.", - messageCreatedAt: now, - }, - ], - }), - }, - orchestrationEngine: { - dispatch: () => Effect.succeed({ sequence: 7 }), - readEvents: () => Stream.empty, - }, - checkpointDiffQuery: { - getTurnDiff: () => - Effect.succeed({ - threadId: ThreadId.make("thread-1"), - fromTurnCount: 0, - toTurnCount: 1, - diff: "turn-diff", - }), - getFullThreadDiff: () => - Effect.succeed({ - threadId: ThreadId.make("thread-1"), - fromTurnCount: 0, - toTurnCount: 1, - diff: "full-diff", - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.session.stop", - commandId: CommandId.make("cmd-1"), - threadId: ThreadId.make("thread-1"), - createdAt: now, - }), - ), - ); - assert.equal(dispatchResult.sequence, 7); - - const turnDiffResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.getTurnDiff]({ - threadId: ThreadId.make("thread-1"), - fromTurnCount: 0, - toTurnCount: 1, - }), - ), - ); - assert.equal(turnDiffResult.diff, "turn-diff"); - - const fullDiffResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.getFullThreadDiff]({ - threadId: ThreadId.make("thread-1"), - toTurnCount: 1, - }), - ), - ); - assert.equal(fullDiffResult.diff, "full-diff"); - - const searchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.searchThreads]({ - query: "final response", - }), - ), - ); - assert.deepEqual(searchResult.matches, [ - { - threadId: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-a"), - source: "assistant", - snippet: "Search reached the final response.", - messageCreatedAt: now, - }, - ]); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("streams orchestration V2 replay output over websocket rpc", () => - Effect.gen(function* () { - const fixture = ORCHESTRATOR_REPLAY_FIXTURES.find((candidate) => candidate.name === "simple"); - if (!fixture) { - throw new Error("Missing simple orchestration V2 replay fixture."); - } - const provider = fixture.providers.find((candidate) => candidate.provider === "codex"); - if (!provider) { - throw new Error("Missing Codex provider variant for simple orchestration V2 fixture."); - } - - const harness = orchestrationV2ReplayHarnessFor(provider.provider); - const rawTranscript = yield* readProviderReplayTranscript(provider.transcriptFile); - const transcript = yield* harness.decodeTranscript(rawTranscript); - const materialized = yield* materializeFixtureInput({ - scenario: fixture.name, - fixtureInput: fixture.buildInput(), - modelSelection: provider.modelSelection, - }).pipe(Effect.provide(idAllocatorV2Layer), provideDeterministicTestRuntime); - const scenario = { - name: `${fixture.name}/${provider.provider}/ws`, - transcript, - commands: materialized.commands, - steps: materialized.steps, - projectionThreadIds: materialized.projectionThreadIds, - }; - const [createThreadCommand, dispatchMessageCommand] = materialized.commands; - if (createThreadCommand?.type !== "thread.create") { - throw new Error("Expected first simple fixture command to create a thread."); - } - if (dispatchMessageCommand?.type !== "message.dispatch") { - throw new Error("Expected second simple fixture command to dispatch a message."); - } - - yield* buildAppUnderTest({ - layers: { - orchestratorV2: makeOrchestratorV2ProviderReplayLayer(scenario, harness).pipe( - Layer.orDie, - ), - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const received = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - Effect.gen(function* () { - const createResult = - yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](createThreadCommand); - const duplicateCreateResult = - yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](createThreadCommand); - assert.equal(duplicateCreateResult.sequence, createResult.sequence); - - const shellItems = yield* Queue.unbounded(); - const shellFiber = yield* client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({}).pipe( - Stream.runForEach((item) => Queue.offer(shellItems, item)), - Effect.forkDetach, - ); - const shellSnapshot = yield* takeWsItem(shellItems, "orchestration V2 shell snapshot"); - assert.equal(shellSnapshot.kind, "snapshot"); - if (shellSnapshot.kind === "snapshot") { - const thread = shellSnapshot.snapshot.threads.find( - (candidate) => candidate.id === createThreadCommand.threadId, - ); - assert.isDefined(thread); - assert.equal(thread.itemCount, 0); - assert.equal(thread.status, "idle"); - } - - const streamItems = yield* Queue.unbounded(); - const streamFiber = yield* client[ORCHESTRATION_V2_WS_METHODS.subscribeThread]({ - threadId: createThreadCommand.threadId, - }).pipe( - Stream.runForEach((item) => Queue.offer(streamItems, item)), - Effect.forkDetach, - ); - - const snapshot = yield* takeWsItem(streamItems, "orchestration V2 snapshot"); - assert.equal(snapshot.kind, "snapshot"); - if (snapshot.kind === "snapshot") { - assert.equal(snapshot.projection.thread.id, createThreadCommand.threadId); - assert.equal(snapshot.snapshotSequence, createResult.sequence); - assert.deepEqual( - snapshot.projection.turnItems.map((item) => item.type), - [], - ); - } - - yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](dispatchMessageCommand); - - const items: Array = []; - const shellUpdates: Array = []; - const turnItemTypes = new Set(); - for (let index = 0; index < 20; index += 1) { - const item = yield* takeWsItem(streamItems, `orchestration V2 event ${index + 1}`); - items.push(item); - if (item.kind === "event") { - assert.isAbove(item.sequence, createResult.sequence); - } - if (item.kind === "event" && item.event.type === "turn-item.updated") { - turnItemTypes.add(item.event.payload.type); - } - if (turnItemTypes.has("user_message") && turnItemTypes.has("assistant_message")) { - break; - } - } - for (let index = 0; index < 20; index += 1) { - const item = yield* takeWsItem( - shellItems, - `orchestration V2 shell update ${index + 1}`, - ); - shellUpdates.push(item); - if ( - item.kind === "thread.updated" && - item.thread.id === createThreadCommand.threadId && - item.thread.visibleItemCount >= 2 - ) { - break; - } - } - - const projection = yield* client[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]({ - threadId: createThreadCommand.threadId, - }); - yield* Fiber.interrupt(streamFiber); - yield* Fiber.interrupt(shellFiber); - - return { items, shellUpdates, projection }; - }), - ), - ); - - const streamedTurnItems = received.items.flatMap((item) => - item.kind === "event" && item.event.type === "turn-item.updated" - ? [item.event.payload] - : [], - ); - assert.deepEqual( - streamedTurnItems.map((item) => item.type), - ["user_message", "assistant_message"], - ); - assert.deepEqual( - received.projection.turnItems.map((item) => item.type), - ["user_message", "assistant_message"], - ); - assert.isTrue( - received.shellUpdates.some( - (item) => - item.kind === "thread.updated" && - item.thread.visibleItemCount === received.projection.visibleTurnItems.length, - ), - ); - assert.equal( - received.projection.turnItems.find((item) => item.type === "assistant_message")?.text, - "fixture simple ok", - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("enriches replayed project events with repository identity metadata", () => - Effect.gen(function* () { - const projectionError = new PersistenceSqlError({ - operation: "ProjectionSnapshotQuery.getShellSnapshot:test", - detail: "failed to read projection shell snapshot", - }); - yield* buildAppUnderTest({ - layers: { - projectionSnapshotQuery: { - getShellSnapshot: () => Effect.fail(projectionError), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({}).pipe(Stream.runCollect), - ).pipe(Effect.result), - ); - - assertTrue(result._tag === "Failure"); - assertTrue(result.failure._tag === "OrchestrationGetSnapshotError"); - assertTrue(result.failure.cause instanceof Error); - assert.include(result.failure.cause.message, projectionError.message); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("marks an empty shell catch-up replay as synchronized when requested", () => - Effect.gen(function* () { - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - readEvents: () => Stream.empty, - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const firstItem = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ - afterSequence: 0, - requestCompletionMarker: true, - }).pipe(Stream.runHead), - ), - ); - - assert.deepEqual(Option.getOrThrow(firstItem), { kind: "synchronized" }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("marks a socket thread snapshot as synchronized when requested", () => - Effect.gen(function* () { - const thread = makeDefaultOrchestrationReadModel().threads[0]!; - yield* buildAppUnderTest({ - layers: { - projectionSnapshotQuery: { - getThreadDetailSnapshot: () => - Effect.succeed(Option.some({ snapshotSequence: 1, thread })), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeThread]({ - threadId: defaultThreadId, - requestCompletionMarker: true, - }).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - assert.equal(items[0]?.kind, "snapshot"); - assert.deepEqual(items[1], { kind: "synchronized" }); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("buffers shell events published while the fallback snapshot loads", () => - Effect.gen(function* () { - const liveEvents = yield* PubSub.unbounded(); - const deletedEvent = { - sequence: 2, - eventId: EventId.make("event-shell-thread-deleted"), - aggregateKind: "thread", - aggregateId: defaultThreadId, - occurredAt: "2026-01-01T00:00:01.000Z", - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.deleted", - payload: { - threadId: defaultThreadId, - deletedAt: "2026-01-01T00:00:01.000Z", - }, - } satisfies Extract; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - streamDomainEvents: Stream.fromPubSub(liveEvents), - }, - projectionSnapshotQuery: { - getShellSnapshot: () => - Effect.gen(function* () { - yield* PubSub.publish(liveEvents, deletedEvent); - return { - snapshotSequence: 1, - projects: [], - threads: [makeDefaultOrchestrationThreadShell()], - updatedAt: "2026-01-01T00:00:00.000Z", - }; - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ - requestCompletionMarker: true, - }).pipe(Stream.take(3), Stream.runCollect), - ), - ).pipe(Effect.timeout("2 seconds")); - - assert.equal(items[0]?.kind, "snapshot"); - assert.equal(items[1]?.kind, "thread-removed"); - assert.deepEqual(items[2], { kind: "synchronized" }); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("buffers thread events published while the initial snapshot loads", () => - Effect.gen(function* () { - const thread = makeDefaultOrchestrationReadModel().threads[0]!; - const liveEvents = yield* PubSub.unbounded(); - const messageEvent = { - sequence: 2, - eventId: EventId.make("event-message"), - aggregateKind: "thread", - aggregateId: defaultThreadId, - occurredAt: "2026-01-01T00:00:01.000Z", - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.message-sent", - payload: { - threadId: defaultThreadId, - messageId: MessageId.make("message-1"), - role: "user", - text: "First message", - turnId: null, - streaming: false, - createdAt: "2026-01-01T00:00:01.000Z", - updatedAt: "2026-01-01T00:00:01.000Z", - }, - } satisfies Extract; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - streamDomainEvents: Stream.fromPubSub(liveEvents), - }, - projectionSnapshotQuery: { - getThreadDetailSnapshot: () => - Effect.gen(function* () { - yield* Effect.sleep("25 millis"); - yield* PubSub.publish(liveEvents, messageEvent); - return Option.some({ snapshotSequence: 1, thread }); - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeThread]({ - threadId: defaultThreadId, - }).pipe(Stream.take(2), Stream.runCollect), - ), - ).pipe(Effect.timeout("2 seconds")); - - assert.equal(items[0]?.kind, "snapshot"); - assert.equal(items[1]?.kind, "event"); - assert.equal(items[1]?.kind === "event" ? items[1].event.sequence : null, 2); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("subscribeThread sends a fresh snapshot instead of replaying a large gap", () => - Effect.gen(function* () { - let readEventsCalls = 0; - const thread = makeDefaultOrchestrationReadModel().threads[0]!; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - // Head is far ahead of the client's afterSequence (gap > 1000). - latestSequence: Effect.succeed(100_000), - readEvents: () => - Stream.sync(() => { - readEventsCalls += 1; - return {} as OrchestrationEvent; - }), - }, - projectionSnapshotQuery: { - getThreadDetailSnapshot: () => - Effect.succeed(Option.some({ snapshotSequence: 100_000, thread })), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeThread]({ - threadId: defaultThreadId, - afterSequence: 5, - requestCompletionMarker: true, - }).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(items); - // Large gap => fresh thread snapshot, and the global replay never starts. - assert.equal(first?.kind, "snapshot"); - if (first?.kind === "snapshot") { - assert.equal(first.snapshot.thread.id, defaultThreadId); - assert.equal(first.snapshot.snapshotSequence, 100_000); - } - assert.equal(second?.kind, "synchronized"); - assert.equal(readEventsCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeThread replaces a cursor ahead of the authoritative head", () => - Effect.gen(function* () { - let readEventsCalls = 0; - const thread = makeDefaultOrchestrationReadModel().threads[0]!; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(5), - readEvents: () => - Stream.sync(() => { - readEventsCalls += 1; - return {} as OrchestrationEvent; - }), - }, - projectionSnapshotQuery: { - getThreadDetailSnapshot: () => - Effect.succeed(Option.some({ snapshotSequence: 5, thread })), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const first = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeThread]({ - threadId: defaultThreadId, - afterSequence: 10, - }).pipe(Stream.runHead), - ), - ); - - assert.equal(Option.getOrThrow(first).kind, "snapshot"); - assert.equal(readEventsCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeThread bounds catch-up replay to the captured head", () => - Effect.gen(function* () { - let replayLimit: number | undefined; - const now = "2026-01-01T00:00:00.000Z"; - const messageEvent = { - sequence: 3, - eventId: EventId.make("event-replay-message"), - aggregateKind: "thread", - aggregateId: defaultThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.message-sent", - payload: { - threadId: defaultThreadId, - messageId: MessageId.make("message-replay"), - role: "user", - text: "Replayed message", - turnId: null, - streaming: false, - createdAt: now, - updatedAt: now, - }, - } satisfies Extract; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(50), - readEvents: (_afterSequence, limit) => { - replayLimit = limit; - return Stream.make(messageEvent); - }, - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeThread]({ - threadId: defaultThreadId, - afterSequence: 0, - requestCompletionMarker: true, - }).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(items); - assert.equal(first?.kind, "event"); - assert.equal(first?.kind === "event" ? first.event.sequence : null, 3); - assert.equal(second?.kind, "synchronized"); - // The replay is bounded to the head captured before the read, not - // Number.MAX_SAFE_INTEGER. - assert.equal(replayLimit, 50); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell sends a fresh snapshot instead of replaying a large gap", () => - Effect.gen(function* () { - let readEventsCalls = 0; - const snapshotThreadId = ThreadId.make("thread-from-snapshot"); - const now = "2026-01-01T00:00:00.000Z"; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - // Head is far ahead of the client's afterSequence (gap > 1000). - latestSequence: Effect.succeed(100_000), - readEvents: () => - Stream.sync(() => { - readEventsCalls += 1; - return { - sequence: 1, - eventId: EventId.make("event-should-not-be-read"), - aggregateKind: "thread", - aggregateId: snapshotThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.created", - payload: {} as never, - } satisfies OrchestrationEvent; - }), - }, - projectionSnapshotQuery: { - getShellSnapshot: () => - Effect.succeed({ - snapshotSequence: 100_000, - projects: [], - threads: [makeDefaultOrchestrationThreadShell({ id: snapshotThreadId })], - updatedAt: now, - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ - afterSequence: 5, - requestCompletionMarker: true, - }).pipe(Stream.take(2), Stream.runCollect), - ), - ); - - const [first, second] = Array.from(items); - // Large gap => fresh snapshot, and the unbounded replay is never started. - assert.equal(first?.kind, "snapshot"); - if (first?.kind === "snapshot") { - assert.equal(first.snapshot.threads[0]?.id, snapshotThreadId); - } - assert.equal(second?.kind, "synchronized"); - assert.equal(readEventsCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell replaces a cursor ahead of the authoritative head", () => - Effect.gen(function* () { - let readEventsCalls = 0; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(5), - readEvents: () => - Stream.sync(() => { - readEventsCalls += 1; - return {} as OrchestrationEvent; - }), - }, - projectionSnapshotQuery: { - getShellSnapshot: () => - Effect.succeed({ - snapshotSequence: 5, - projects: [], - threads: [], - updatedAt: "2026-01-01T00:00:00.000Z", - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const first = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ afterSequence: 10 }).pipe( - Stream.runHead, - ), - ), - ); - - assert.equal(Option.getOrThrow(first).kind, "snapshot"); - assert.equal(readEventsCalls, 0); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell coalesces a per-thread burst without stalling other threads", () => - Effect.gen(function* () { - const busyThreadId = ThreadId.make("thread-busy"); - const newThreadId = ThreadId.make("thread-new"); - const now = "2026-01-01T00:00:00.000Z"; - const shellFetches: Array = []; - let replayLimit: number | undefined; - - const messageEvent = (sequence: number): OrchestrationEvent => - ({ - sequence, - eventId: EventId.make(`event-${sequence}`), - aggregateKind: "thread", - aggregateId: busyThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.message-sent", - payload: {} as never, - }) satisfies OrchestrationEvent; - - const createdEvent: OrchestrationEvent = { - sequence: 50, - eventId: EventId.make("event-created"), - aggregateKind: "thread", - aggregateId: newThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.created", - payload: {} as never, - }; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(50), - // A burst of message-sent deltas for the busy thread, plus one - // thread.created for a different thread, all within one batch. - readEvents: (_afterSequence, limit) => { - replayLimit = limit; - return Stream.fromIterable([ - ...Array.from({ length: 20 }, (_unused, index) => messageEvent(index + 1)), - createdEvent, - ]); - }, - }, - projectionSnapshotQuery: { - getThreadShellById: (threadId) => - Effect.sync(() => { - shellFetches.push(threadId); - return Option.some(makeDefaultOrchestrationThreadShell({ id: threadId })); - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ - afterSequence: 0, - requestCompletionMarker: true, - }).pipe(Stream.take(3), Stream.runCollect), - ), - ); - - const collected = Array.from(items); - const upsertedIds = collected.flatMap((item) => - item.kind === "thread-upserted" ? [item.thread.id] : [], - ); - // Both threads surface, and the busy thread's 20-event burst collapses to - // a single shell refetch (not 20). The new thread is not stuck behind it. - assert.include(upsertedIds, busyThreadId); - assert.include(upsertedIds, newThreadId); - assert.equal(collected[2]?.kind, "synchronized"); - assert.equal(shellFetches.filter((id) => id === busyThreadId).length, 1); - assert.equal(replayLimit, 50); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell coalesces live bursts after the synchronization marker", () => - Effect.gen(function* () { - const busyThreadId = ThreadId.make("thread-live-busy"); - const newThreadId = ThreadId.make("thread-live-new"); - const now = "2026-01-01T00:00:00.000Z"; - const liveEvents = yield* PubSub.unbounded(); - const synchronized = yield* Deferred.make(); - const shellFetches: Array = []; - const observedLiveThreadIds = new Set(); - - const messageEvent = (sequence: number): OrchestrationEvent => - ({ - sequence, - eventId: EventId.make(`event-live-${sequence}`), - aggregateKind: "thread", - aggregateId: busyThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.message-sent", - payload: {} as never, - }) satisfies OrchestrationEvent; - - const createdEvent: OrchestrationEvent = { - sequence: 50, - eventId: EventId.make("event-live-created"), - aggregateKind: "thread", - aggregateId: newThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.created", - payload: {} as never, - }; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - streamDomainEvents: Stream.fromPubSub(liveEvents), - }, - projectionSnapshotQuery: { - getThreadShellById: (threadId) => - Effect.sync(() => { - shellFetches.push(threadId); - return Option.some(makeDefaultOrchestrationThreadShell({ id: threadId })); - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - Effect.gen(function* () { - const itemsFiber = yield* withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ - requestCompletionMarker: true, - }).pipe( - Stream.tap((item) => - item.kind === "synchronized" - ? Deferred.succeed(synchronized, undefined).pipe(Effect.ignore) - : Effect.void, - ), - Stream.takeUntil((item) => { - if (item.kind === "thread-upserted") { - observedLiveThreadIds.add(item.thread.id); - } - return ( - observedLiveThreadIds.has(busyThreadId) && observedLiveThreadIds.has(newThreadId) - ); - }), - Stream.runCollect, - ), - ).pipe(Effect.forkScoped); - - yield* Deferred.await(synchronized); - for (const event of [ - ...Array.from({ length: 20 }, (_unused, index) => messageEvent(index + 1)), - createdEvent, - ]) { - yield* PubSub.publish(liveEvents, event); - } - - return yield* Fiber.join(itemsFiber); - }), - ).pipe(Effect.timeout("2 seconds")); - - assert.equal(items[0]?.kind, "snapshot"); - assert.equal(items[1]?.kind, "synchronized"); - const liveUpsertedIds = Array.from(items) - .slice(2) - .flatMap((item) => (item.kind === "thread-upserted" ? [item.thread.id] : [])); - assert.include(liveUpsertedIds, busyThreadId); - assert.include(liveUpsertedIds, newThreadId); - assert.isBelow(shellFetches.filter((id) => id === busyThreadId).length, 20); - }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive), - ); - - it.effect("subscribeShell coalescing still emits a removal for a deleted thread", () => - Effect.gen(function* () { - const goneThreadId = ThreadId.make("thread-gone"); - const now = "2026-01-01T00:00:00.000Z"; - - const makeThreadEvent = ( - sequence: number, - type: "thread.deleted" | "thread.message-sent", - ): OrchestrationEvent => - ({ - sequence, - eventId: EventId.make(`event-${sequence}`), - aggregateKind: "thread", - aggregateId: goneThreadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type, - payload: type === "thread.deleted" ? { threadId: goneThreadId, deletedAt: now } : {}, - }) as OrchestrationEvent; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(2), - // A thread.deleted followed, within the same coalescing window, by a - // later refetchable event for the same thread. The later event wins - // coalescing; its shell refetch returns none (the row is gone), which - // must still surface a removal rather than be swallowed. - readEvents: () => - Stream.fromIterable([ - makeThreadEvent(1, "thread.deleted"), - makeThreadEvent(2, "thread.message-sent"), - ]), - }, - projectionSnapshotQuery: { - getThreadShellById: () => Effect.succeed(Option.none()), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ afterSequence: 0 }).pipe( - Stream.take(1), - Stream.runCollect, - ), - ), - ); - - const [first] = Array.from(items); - assert.equal(first?.kind, "thread-removed"); - assert.equal(first?.kind === "thread-removed" ? first.threadId : null, goneThreadId); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell retries a transient shell projection refetch failure", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-transient-refetch"); - const now = "2026-01-01T00:00:00.000Z"; - let attempts = 0; - - const event: OrchestrationEvent = { - sequence: 1, - eventId: EventId.make("event-transient-refetch"), - aggregateKind: "thread", - aggregateId: threadId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type: "thread.message-sent", - payload: {} as never, - }; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(1), - readEvents: () => Stream.make(event), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.suspend(() => { - attempts += 1; - return attempts === 1 - ? Effect.fail( - new PersistenceSqlError({ - operation: "test.shell-refetch", - detail: "transient failure", - }), - ) - : Effect.succeed( - Option.some(makeDefaultOrchestrationThreadShell({ id: threadId })), - ); - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ afterSequence: 0 }).pipe( - Stream.take(1), - Stream.runCollect, - ), - ), - ); - - const [first] = Array.from(items); - assert.equal(first?.kind, "thread-upserted"); - assert.equal(first?.kind === "thread-upserted" ? first.thread.id : null, threadId); - assert.equal(attempts, 2); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("subscribeShell coalescing still removes a project after a trailing update", () => - Effect.gen(function* () { - const projectId = ProjectId.make("project-gone"); - const now = "2026-01-01T00:00:00.000Z"; - - const makeProjectEvent = ( - sequence: number, - type: "project.deleted" | "project.meta-updated", - ): OrchestrationEvent => - ({ - sequence, - eventId: EventId.make(`event-project-${sequence}`), - aggregateKind: "project", - aggregateId: projectId, - occurredAt: now, - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - type, - payload: - type === "project.deleted" - ? { projectId, deletedAt: now } - : { projectId, title: "Still deleted", updatedAt: now }, - }) as OrchestrationEvent; - - yield* buildAppUnderTest({ - layers: { - orchestrationEngine: { - latestSequence: Effect.succeed(2), - readEvents: () => - Stream.fromIterable([ - makeProjectEvent(1, "project.deleted"), - makeProjectEvent(2, "project.meta-updated"), - ]), - }, - projectionSnapshotQuery: { - getProjectShellById: () => Effect.succeed(Option.none()), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const items = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.subscribeShell]({ afterSequence: 0 }).pipe( - Stream.take(1), - Stream.runCollect, - ), - ), - ); - - const [first] = Array.from(items); - assert.equal(first?.kind, "project-removed"); - assert.equal(first?.kind === "project-removed" ? first.projectId : null, projectId); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("stops the provider session and closes thread terminals after archive", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - const now = "2026-01-01T00:00:00.000Z"; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - return { sequence: dispatchedCommands.length }; - }), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some( - makeDefaultOrchestrationThreadShell({ - id: threadId, - updatedAt: now, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }), - ), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, [ - "dispatch:thread.archive", - "dispatch:thread.session.stop", - `terminal.close:${threadId}`, - ]); - const sessionStopCommand = dispatchedCommands[1]; - assert.equal(sessionStopCommand?.type, "thread.session.stop"); - if (sessionStopCommand?.type === "thread.session.stop") { - assert.equal(sessionStopCommand.threadId, threadId); - } - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("checks session status before archiving removes the thread from active lookups", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive-precheck"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - const now = "2026-01-01T00:00:00.000Z"; - let archived = false; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - if (command.type === "thread.archive") { - archived = true; - } - return { sequence: dispatchedCommands.length }; - }), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.sync(() => { - effects.push(`query:thread-shell:${archived ? "archived" : "active"}`); - return archived - ? Option.none() - : Option.some( - makeDefaultOrchestrationThreadShell({ - id: threadId, - updatedAt: now, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }), - ); - }), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive-precheck"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, [ - "query:thread-shell:active", - "dispatch:thread.archive", - "dispatch:thread.session.stop", - `terminal.close:${threadId}`, - ]); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.archive", "thread.session.stop"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("archives without dispatching session stop when the thread has no session", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive-no-session"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - return { sequence: dispatchedCommands.length }; - }), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some(makeDefaultOrchestrationThreadShell({ id: threadId, session: null })), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive-no-session"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, ["dispatch:thread.archive", `terminal.close:${threadId}`]); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.archive"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "archives without dispatching session stop when the thread session is already stopped", - () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive-stopped-session"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - const now = "2026-01-01T00:00:00.000Z"; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - return { sequence: dispatchedCommands.length }; - }), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some( - makeDefaultOrchestrationThreadShell({ - id: threadId, - updatedAt: now, - session: { - threadId, - status: "stopped", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }), - ), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive-stopped-session"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, ["dispatch:thread.archive", `terminal.close:${threadId}`]); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.archive"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("stops the provider session after settle without closing terminals", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-settle"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - const now = "2026-01-01T00:00:00.000Z"; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - return { sequence: dispatchedCommands.length }; - }), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some( - makeDefaultOrchestrationThreadShell({ - id: threadId, - updatedAt: now, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }), - ), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.settle", - commandId: CommandId.make("cmd-thread-settle"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, ["dispatch:thread.settle", "dispatch:thread.session.stop"]); - const sessionStopCommand = dispatchedCommands[1]; - assert.equal(sessionStopCommand?.type, "thread.session.stop"); - if (sessionStopCommand?.type === "thread.session.stop") { - assert.equal(sessionStopCommand.threadId, threadId); - assert.equal(sessionStopCommand.commandId, "session-stop-for-settle:cmd-thread-settle"); - assert.equal(sessionStopCommand.onlyIfSettled, true); - } - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("settles without dispatching session stop when the thread has no session", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-settle-no-session"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - return { sequence: dispatchedCommands.length }; - }), - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some(makeDefaultOrchestrationThreadShell({ id: threadId, session: null })), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.settle", - commandId: CommandId.make("cmd-thread-settle-no-session"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, ["dispatch:thread.settle"]); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.settle"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("archives and still closes terminals when session stop fails", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive-stop-failure"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - const now = "2026-01-01T00:00:00.000Z"; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - if (command.type === "thread.session.stop") { - return Effect.fail( - new OrchestrationListenerCallbackError({ - listener: "domain-event", - detail: "simulated archive stop failure", - }), - ); - } - return Effect.succeed({ sequence: dispatchedCommands.length }); - }, - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some( - makeDefaultOrchestrationThreadShell({ - id: threadId, - updatedAt: now, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }), - ), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive-stop-failure"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, [ - "dispatch:thread.archive", - "dispatch:thread.session.stop", - `terminal.close:${threadId}`, - ]); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.archive", "thread.session.stop"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("archives and still closes terminals when session stop defects", () => - Effect.gen(function* () { - const threadId = ThreadId.make("thread-archive-stop-defect"); - const effects: string[] = []; - const dispatchedCommands: Array = []; - const now = "2026-01-01T00:00:00.000Z"; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - close: (input) => - Effect.sync(() => { - effects.push(`terminal.close:${input.threadId}`); - }), - }, - orchestrationEngine: { - dispatch: (command) => { - dispatchedCommands.push(command); - effects.push(`dispatch:${command.type}`); - if (command.type === "thread.session.stop") { - return Effect.die(new Error("simulated archive stop defect")); - } - return Effect.succeed({ sequence: dispatchedCommands.length }); - }, - }, - projectionSnapshotQuery: { - getThreadShellById: () => - Effect.succeed( - Option.some( - makeDefaultOrchestrationThreadShell({ - id: threadId, - updatedAt: now, - session: { - threadId, - status: "ready", - providerName: "claudeAgent", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: now, - }, - }), - ), - ), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const dispatchResult = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.archive", - commandId: CommandId.make("cmd-thread-archive-stop-defect"), - threadId, - }), - ), - ); - - assert.equal(dispatchResult.sequence, 1); - assert.deepEqual(effects, [ - "dispatch:thread.archive", - "dispatch:thread.session.stop", - `terminal.close:${threadId}`, - ]); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.archive", "thread.session.stop"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect( - "bootstraps first-send worktree turns on the server before dispatching turn start", - () => - Effect.gen(function* () { - const dispatchedCommands: Array = []; - const bootstrapGitOperations: string[] = []; - const refreshStatus = vi.fn((_: string) => - Effect.succeed({ - isRepo: true, - hasPrimaryRemote: true, - isDefaultRef: false, - refName: "t3code/bootstrap-refName", - hasWorkingTreeChanges: false, - workingTree: { - files: [], - insertions: 0, - deletions: 0, - }, - hasUpstream: true, - aheadCount: 0, - behindCount: 0, - pr: null, - }), - ); - const fetchRemote = vi.fn( - (_: Parameters[0]) => - Effect.sync(() => { - bootstrapGitOperations.push("fetch"); - }), - ); - const fetchedOriginCommit = "0123456789abcdef0123456789abcdef01234567"; - const resolveRemoteTrackingCommit = vi.fn( - (_: Parameters[0]) => - Effect.sync(() => { - bootstrapGitOperations.push("resolve-remote-commit"); - return { - commitSha: fetchedOriginCommit, - remoteRefName: "origin/main", - }; - }), - ); - const createWorktree = vi.fn( - (_: Parameters[0]) => - Effect.sync(() => { - bootstrapGitOperations.push("create-worktree"); - return { - worktree: { - refName: "t3code/bootstrap-refName", - path: "/tmp/bootstrap-worktree", - }, - }; - }), - ); - const runForThread = vi.fn( - ( - _: Parameters< - ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"] - >[0], - ) => - Effect.succeed({ - status: "started" as const, - scriptId: "setup", - scriptName: "Setup", - terminalId: "setup-setup", - cwd: "/tmp/bootstrap-worktree", - }), - ); - - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - fetchRemote, - resolveRemoteTrackingCommit, - createWorktree, - }, - vcsStatusBroadcaster: { - refreshStatus, - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - return { sequence: dispatchedCommands.length }; - }), - readEvents: () => Stream.empty, - }, - projectSetupScriptRunner: { - runForThread, - }, - }, - }); - - const createdAt = "2026-01-01T00:00:00.000Z"; - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-bootstrap-turn-start"), - threadId: ThreadId.make("thread-bootstrap"), - message: { - messageId: MessageId.make("msg-bootstrap"), - role: "user", - text: "hello", - attachments: [], - }, - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - bootstrap: { - createThread: { - projectId: defaultProjectId, - title: "Bootstrap Thread", - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - createdAt, - }, - prepareWorktree: { - projectCwd: "/tmp/project", - baseBranch: "main", - branch: "t3code/bootstrap-refName", - startFromOrigin: true, - }, - runSetupScript: true, - }, - createdAt, - }), - ), - ); - - assert.equal(response.sequence, 5); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - [ - "thread.create", - "thread.meta.update", - "thread.activity.append", - "thread.activity.append", - "thread.turn.start", - ], - ); - assert.deepEqual(createWorktree.mock.calls[0]?.[0], { - cwd: "/tmp/project", - refName: fetchedOriginCommit, - newRefName: "t3code/bootstrap-refName", - baseRefName: "main", - path: null, - }); - assert.deepEqual(fetchRemote.mock.calls[0]?.[0], { - cwd: "/tmp/project", - remoteName: "origin", - }); - assert.deepEqual(resolveRemoteTrackingCommit.mock.calls[0]?.[0], { - cwd: "/tmp/project", - refName: "main", - fallbackRemoteName: "origin", - }); - assert.deepEqual(bootstrapGitOperations, [ - "fetch", - "resolve-remote-commit", - "create-worktree", - ]); - assert.deepEqual(runForThread.mock.calls[0]?.[0], { - threadId: ThreadId.make("thread-bootstrap"), - projectId: defaultProjectId, - projectCwd: "/tmp/project", - worktreePath: "/tmp/bootstrap-worktree", - }); - assert.deepEqual(refreshStatus.mock.calls[0]?.[0], "/tmp/bootstrap-worktree"); - - const setupActivities = dispatchedCommands.filter( - (command): command is Extract => - command.type === "thread.activity.append", - ); - assert.deepEqual( - setupActivities.map((command) => command.activity.kind), - ["setup-script.requested", "setup-script.started"], - ); - const finalCommand = dispatchedCommands[4]; - assertTrue(finalCommand?.type === "thread.turn.start"); - if (finalCommand?.type === "thread.turn.start") { - assert.equal(finalCommand.bootstrap, undefined); - } - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("records setup-script failures without aborting bootstrap turn start", () => - Effect.gen(function* () { - const dispatchedCommands: Array = []; - const createWorktree = vi.fn( - (_: Parameters[0]) => - Effect.succeed({ - worktree: { - refName: "t3code/bootstrap-refName", - path: "/tmp/bootstrap-worktree", - }, - }), - ); - const runForThread = vi.fn( - ( - input: Parameters< - ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"] - >[0], - ) => - Effect.fail( - new ProjectSetupScriptRunner.ProjectSetupScriptOperationError({ - threadId: input.threadId, - worktreePath: input.worktreePath, - operation: "openTerminal", - cause: { message: "pty unavailable" }, - }), - ), - ); - - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - createWorktree, - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - return { sequence: dispatchedCommands.length }; - }), - readEvents: () => Stream.empty, - }, - projectSetupScriptRunner: { - runForThread, - }, - }, - }); - - const createdAt = "2026-01-01T00:00:00.000Z"; - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-bootstrap-turn-start-setup-failure"), - threadId: ThreadId.make("thread-bootstrap-setup-failure"), - message: { - messageId: MessageId.make("msg-bootstrap-setup-failure"), - role: "user", - text: "hello", - attachments: [], - }, - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - bootstrap: { - createThread: { - projectId: defaultProjectId, - title: "Bootstrap Thread", - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - createdAt, - }, - prepareWorktree: { - projectCwd: "/tmp/project", - baseBranch: "main", - branch: "t3code/bootstrap-refName", - }, - runSetupScript: true, - }, - createdAt, - }), - ), - ); - - assert.equal(response.sequence, 4); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"], - ); - const setupFailureActivity = dispatchedCommands.find( - (command): command is Extract => - command.type === "thread.activity.append", - ); - assert.equal(setupFailureActivity?.activity.kind, "setup-script.failed"); - assert.deepEqual(setupFailureActivity?.activity.payload, { - detail: "pty unavailable", - worktreePath: "/tmp/bootstrap-worktree", - }); - assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete")); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("does not misattribute setup activity dispatch failures as setup launch failures", () => - Effect.gen(function* () { - const dispatchedCommands: Array = []; - const createWorktree = vi.fn( - (_: Parameters[0]) => - Effect.succeed({ - worktree: { - refName: "t3code/bootstrap-refName", - path: "/tmp/bootstrap-worktree", - }, - }), - ); - const runForThread = vi.fn( - ( - _: Parameters< - ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"] - >[0], - ) => - Effect.succeed({ - status: "started" as const, - scriptId: "setup", - scriptName: "Setup", - terminalId: "setup-setup", - cwd: "/tmp/bootstrap-worktree", - }), - ); - let setupActivityAppendAttempt = 0; - - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - createWorktree, - }, - orchestrationEngine: { - dispatch: (command) => { - if ( - command.type === "thread.activity.append" && - command.activity.kind.startsWith("setup-script.") - ) { - setupActivityAppendAttempt += 1; - if (setupActivityAppendAttempt === 2) { - return Effect.fail( - new OrchestrationListenerCallbackError({ - listener: "domain-event", - detail: "failed to append setup-script.started activity", - }), - ); - } - } - - return Effect.sync(() => { - dispatchedCommands.push(command); - return { sequence: dispatchedCommands.length }; - }); - }, - readEvents: () => Stream.empty, - }, - projectSetupScriptRunner: { - runForThread, - }, - }, - }); - - const createdAt = "2026-01-01T00:00:00.000Z"; - const wsUrl = yield* getWsServerUrl("/ws"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-bootstrap-turn-start-setup-activity-failure"), - threadId: ThreadId.make("thread-bootstrap-setup-activity-failure"), - message: { - messageId: MessageId.make("msg-bootstrap-setup-activity-failure"), - role: "user", - text: "hello", - attachments: [], - }, - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - bootstrap: { - createThread: { - projectId: defaultProjectId, - title: "Bootstrap Thread", - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - createdAt, - }, - prepareWorktree: { - projectCwd: "/tmp/project", - baseBranch: "main", - branch: "t3code/bootstrap-refName", - }, - runSetupScript: true, - }, - createdAt, - }), - ), - ); - - assert.equal(response.sequence, 4); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.create", "thread.meta.update", "thread.activity.append", "thread.turn.start"], - ); - const setupActivities = dispatchedCommands.filter( - (command): command is Extract => - command.type === "thread.activity.append", - ); - assert.deepEqual( - setupActivities.map((command) => command.activity.kind), - ["setup-script.requested"], - ); - assertTrue( - setupActivities.every((command) => command.activity.kind !== "setup-script.failed"), - ); - assertTrue(dispatchedCommands.every((command) => command.type !== "thread.delete")); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("cleans up created bootstrap threads when worktree creation defects", () => - Effect.gen(function* () { - const dispatchedCommands: Array = []; - const createWorktree = vi.fn( - (_: Parameters[0]) => - Effect.die(new Error("worktree exploded")), - ); - - yield* buildAppUnderTest({ - layers: { - gitVcsDriver: { - createWorktree, - }, - orchestrationEngine: { - dispatch: (command) => - Effect.sync(() => { - dispatchedCommands.push(command); - return { sequence: dispatchedCommands.length }; - }), - readEvents: () => Stream.empty, - }, - }, - }); - - const createdAt = "2026-01-01T00:00:00.000Z"; - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[ORCHESTRATION_WS_METHODS.dispatchCommand]({ - type: "thread.turn.start", - commandId: CommandId.make("cmd-bootstrap-turn-start-defect"), - threadId: ThreadId.make("thread-bootstrap-defect"), - message: { - messageId: MessageId.make("msg-bootstrap-defect"), - role: "user", - text: "hello", - attachments: [], - }, - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - bootstrap: { - createThread: { - projectId: defaultProjectId, - title: "Bootstrap Thread", - modelSelection: defaultModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - createdAt, - }, - prepareWorktree: { - projectCwd: "/tmp/project", - baseBranch: "main", - branch: "t3code/bootstrap-refName", - }, - runSetupScript: false, - }, - createdAt, - }), - ).pipe(Effect.result), - ); - - assertTrue(result._tag === "Failure"); - assertTrue(result.failure._tag === "OrchestrationDispatchCommandError"); - assert.include(result.failure.message, "worktree exploded"); - assert.deepEqual( - dispatchedCommands.map((command) => command.type), - ["thread.create", "thread.delete"], - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc terminal methods", () => - Effect.gen(function* () { - const snapshot = { - threadId: "thread-1", - terminalId: "default", - cwd: "/tmp/project", - worktreePath: null, - status: "running" as const, - pid: 1234, - history: "", - exitCode: null, - exitSignal: null, - label: "Primary", - updatedAt: "2026-01-01T00:00:00.000Z", - }; - - yield* buildAppUnderTest({ - layers: { - terminalManager: { - open: () => Effect.succeed(snapshot), - write: () => Effect.void, - resize: () => Effect.void, - clear: () => Effect.void, - restart: () => Effect.succeed(snapshot), - close: () => Effect.void, - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - - const opened = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalOpen]({ - threadId: "thread-1", - terminalId: "default", - cwd: "/tmp/project", - }), - ), - ); - assert.equal(opened.terminalId, "default"); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalWrite]({ - threadId: "thread-1", - terminalId: "default", - data: "echo hi\n", - }), - ), - ); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalResize]({ - threadId: "thread-1", - terminalId: "default", - cols: 120, - rows: 40, - }), - ), - ); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalClear]({ - threadId: "thread-1", - terminalId: "default", - }), - ), - ); - - const restarted = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalRestart]({ - threadId: "thread-1", - terminalId: "default", - cwd: "/tmp/project", - cols: 120, - rows: 40, - }), - ), - ); - assert.equal(restarted.terminalId, "default"); - - yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalClose]({ - threadId: "thread-1", - terminalId: "default", - }), - ), - ); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - - it.effect("routes websocket rpc terminal.write errors", () => - Effect.gen(function* () { - const terminalError = new TerminalNotRunningError({ - threadId: "thread-1", - terminalId: "default", - }); - yield* buildAppUnderTest({ - layers: { - terminalManager: { - write: () => Effect.fail(terminalError), - }, - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws"); - const result = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.terminalWrite]({ - threadId: "thread-1", - terminalId: "default", - data: "echo fail\n", - }), - ).pipe(Effect.result), - ); - - assertFailure(result, terminalError); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); -}); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 5bcd6c1aa2..d218490f8b 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -101,11 +101,6 @@ import { } from "./orchestration-v2/runtimeLayer.ts"; import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupService.ts"; import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts"; -import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts"; -import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts"; -import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts"; -import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts"; -import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; import { clearPersistedServerRuntimeState, makePersistedServerRuntimeState, @@ -429,10 +424,7 @@ export const makeRoutesLayer = Layer.mergeAll( Layer.provide(authHttpApiLayer), Layer.provide(connectHttpApiLayer), Layer.provide(orchestrationHttpApiLayer), -<<<<<<< HEAD Layer.provide(pullRequestHttpApiLayer), -======= ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) Layer.provide(projectHttpApiLayer), Layer.provide(serverEnvironmentHttpApiLayer), Layer.provide(environmentAuthenticatedAuthLayer), @@ -442,7 +434,6 @@ export const makeRoutesLayer = Layer.mergeAll( staticAndDevRouteLayer, websocketRpcRouteLayer, ), -<<<<<<< HEAD // The MCP session registry is provided globally (shared with V2 provider // sessions) rather than inline here. McpHttpServer.layer, @@ -450,10 +441,6 @@ export const makeRoutesLayer = Layer.mergeAll( // Both transports consume the same service instance, so caches single-flight across clients // and mutations observed on WebSocket invalidate patches subsequently read over HTTP. Layer.provide(PullRequestServiceLive), -======= - McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)), -).pipe( ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) Layer.provide(PreviewAutomationBroker.layer), Layer.provide(ServerSelfUpdate.layer), Layer.provide(commandReadinessLayer), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index d7487e4ad0..c57ebd44eb 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -418,6 +418,8 @@ const makeWsRpcLayer = ( ); const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService; + const pullRequests = yield* PullRequestService.PullRequestService; + const usage = yield* UsageService.UsageService; const projectService = yield* ProjectService.ProjectService; const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery; const keybindings = yield* Keybindings.Keybindings; diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 2677551675..365f4de512 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -14,13 +14,9 @@ import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalSt import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; import { cn, isMacPlatform } from "../lib/utils"; import { primaryServerKeybindingsAtom } from "../state/server"; -<<<<<<< HEAD import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings"; import LegacyThreadSidebar from "./LegacySidebar"; -======= -import { useEnvironmentIdentificationMode, useSidebarV2Enabled } from "../hooks/useSettings"; import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration"; ->>>>>>> 844dad005a (feat(orchestration): track provider retries and thread visits) import ThreadSidebar from "./Sidebar"; import { SettingsSidebarNav } from "./settings/SettingsSidebarNav"; import { SidebarChromeHeader } from "./sidebar/SidebarChrome"; @@ -143,18 +139,11 @@ function ProjectProjectionRetention() { export function AppSidebarLayout({ children }: { children: ReactNode }) { const navigate = useNavigate(); -<<<<<<< HEAD const legacySidebarEnabled = useLegacySidebarEnabled(); // Settings routes show the settings nav in place of whichever thread // sidebar is active. -======= - const sidebarV2Enabled = useSidebarV2Enabled(); // Seeds server-side visited tracking from this browser's localStorage the - // first time each thread shell loads (no-op on already-seeded servers). useThreadVisitedMigration(); - // Settings routes render the settings nav, which lives in the v1 component - // and is identical for both sidebars — so v1 stays mounted there. ->>>>>>> 844dad005a (feat(orchestration): track provider retries and thread visits) const pathname = useLocation({ select: (location) => location.pathname }); const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/"); const isMacosDesktop = isElectron && isMacPlatform(navigator.platform); diff --git a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx index c223ac3a2e..6e7240cffc 100644 --- a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx +++ b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx @@ -68,26 +68,11 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe ); if (envLocked) { -<<<<<<< HEAD - return ( - - {activeWorktreePath ? ( - <> - - {resolveLockedWorkspaceLabel(activeWorktreePath)} - - ) : ( - <> - - {resolveLockedWorkspaceLabel(activeWorktreePath)} - -======= const lockedRow = ( >>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar) )} > {activeWorktreePath ? ( diff --git a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx index 024ec960b1..ceb41fa8dd 100644 --- a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx +++ b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx @@ -55,16 +55,12 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir // only thing in the strip. if (envLocked || onEnvironmentChange === undefined) { return ( -<<<<<<< HEAD - -======= ->>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar) {activeEnvironment?.isPrimary ? ( selectActiveRightPanelSurface(state.byThreadKey, activeThreadRef), ); + const [pullRequestTabStatuses, setPullRequestTabStatuses] = useState< + Record + >({}); + const handlePullRequestTabStatusChange = useCallback((status: PullRequestTabStatus) => { + const id = pullRequestSurfaceId(status); + setPullRequestTabStatuses((current) => + current[id]?.state === status.state && current[id]?.isDraft === status.isDraft + ? current + : { ...current, [id]: status }, + ); + }, []); const activeFileSurface = activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null; const activePreviewState = useThreadPreviewState(activeThreadRef); @@ -2054,6 +2069,8 @@ function ChatViewContent(props: ChatViewProps) { const serverConfig = activeThread ? (activeEnvironment?.serverConfig ?? null) : (primaryEnvironment?.serverConfig ?? null); + const pullRequestsCapabilityKnown = serverConfig !== null; + const supportsPullRequests = serverConfig?.environment.capabilities.pullRequests === true; const versionMismatch = resolveServerConfigVersionMismatch(serverConfig); const versionMismatchDismissKey = versionMismatch && activeThread @@ -3288,6 +3305,27 @@ function ChatViewContent(props: ChatViewProps) { }, [activeProject, activeThreadRef], ); + // The thread's own change request, placed against the project it belongs to. Without a + // project there is nothing to resolve it against, so the caller falls back to the browser. + const threadRepository = activeProject?.repositoryIdentity?.displayName ?? null; + const openThreadPullRequest = useCallback( + (number: number) => { + if ( + !supportsPullRequests || + !activeThreadRef || + !activeProject || + threadRepository === null + ) { + return; + } + useRightPanelStore.getState().openPullRequest(activeThreadRef, { + projectId: activeProject.id, + repository: threadRepository, + number, + }); + }, + [activeProject, activeThreadRef, supportsPullRequests, threadRepository], + ); const togglePreviewPanel = useCallback(() => { if (!activeThreadRef || !isPreviewSupportedInRuntime()) return; if (previewPanelOpen) { @@ -4233,6 +4271,14 @@ function ChatViewContent(props: ChatViewProps) { threadBranch: activeThread?.branch ?? null, gitStatus: gitStatusQuery.data ?? null, }); + // The right panel offers the thread's own change request, so it can only offer it once the + // branch has one; until then the picker says so rather than opening an empty panel. + const addPullRequestSurface = useCallback(() => { + if (activeThreadPr === null) return; + openThreadPullRequest(activeThreadPr.number); + }, [activeThreadPr, openThreadPullRequest]); + const pullRequestSurfaceAvailable = + supportsPullRequests && activeThreadPr !== null && threadRepository !== null; const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true; const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true; const nowMinute = useNowMinute(); @@ -6083,6 +6129,35 @@ function ChatViewContent(props: ChatViewProps) { initialGitScope={initialDiffPanelGitScope} /> + ) : activeRightPanelSurface?.kind === "pull-request" && !pullRequestsCapabilityKnown ? ( + + ) : activeRightPanelSurface?.kind === "pull-request" && !supportsPullRequests ? ( + + ) : activeRightPanelSurface?.kind === "pull-request" ? ( + // No onClose: the surface tab's own X owns closing here, and a second X in the header + // would be the same action twice. The thread context also drops the checkout button, so it + // is only right for the thread's own pull request, whose branch is already under the + // reader's feet. A link the agent wrote can open any other one here, and that one has to be + // checkable out like it is anywhere else. + ) : activeRightPanelSurface?.kind === "agents" ? ( @@ -6657,10 +6756,16 @@ function ChatViewContent(props: ChatViewProps) { onAddTerminal={addTerminalSurface} onAddDiff={addDiffSurface} onAddFiles={addFilesSurface} + onAddPullRequest={addPullRequestSurface} onAddAgents={addAgentsSurface} browserAvailable={isPreviewSupportedInRuntime()} + terminalAvailable={activeProject !== null} diffAvailable={isServerThread && isGitRepo} filesAvailable={activeProject !== null} + pullRequestAvailable={pullRequestSurfaceAvailable} + agentsAvailable + pullRequestStatuses={pullRequestTabStatuses} + liveAgentCount={agentPanelModel.liveCount} > {rightPanelContent} @@ -6686,10 +6791,16 @@ function ChatViewContent(props: ChatViewProps) { onAddTerminal={addTerminalSurface} onAddDiff={addDiffSurface} onAddFiles={addFilesSurface} + onAddPullRequest={addPullRequestSurface} onAddAgents={addAgentsSurface} browserAvailable={isPreviewSupportedInRuntime()} + terminalAvailable={activeProject !== null} diffAvailable={isServerThread && isGitRepo} filesAvailable={activeProject !== null} + pullRequestAvailable={pullRequestSurfaceAvailable} + agentsAvailable + pullRequestStatuses={pullRequestTabStatuses} + liveAgentCount={agentPanelModel.liveCount} > {rightPanelContent} diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index e5fd5ba6c4..b2e36e73c9 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -323,13 +323,7 @@ export default function DiffPanel({ headRef: selectedGitSource.headRef, cacheKey: selectedGitSource.diffHash, }); - }, [ - activeThread, - branchDiffPreview.data, - getDiffFileContents, - selectedGitSource, - selectedTurnId, - ]); + }, [activeThread, branchDiffPreview.data, getDiffFileContents, selectedGitSource, selectedRunId]); const localBranchRefs = useEnvironmentQuery( selectedRunId === null && selectedGitScope === "branch" && diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 4c1623f351..6980533f1e 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -36,6 +36,7 @@ import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "~/compon import { RadioGroup } from "~/components/ui/radio-group"; import { Spinner } from "~/components/ui/spinner"; import { cn } from "~/lib/utils"; +import { openPullRequestLink } from "~/lib/openPullRequestLink"; import { buildMenuItems, formatGitActionElapsed, diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx index e7436c0a75..a56fcd1350 100644 --- a/apps/web/src/components/LegacySidebar.tsx +++ b/apps/web/src/components/LegacySidebar.tsx @@ -448,7 +448,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr [discoveredPorts, navigateToThread, openPreview, threadRef], ); const isThreadRunning = - thread.session?.status === "running" && thread.session.activeTurnId != null; + thread.runtime?.status === "running" && thread.runtime.activeRunId != null; const threadStatus = resolveThreadStatusPill({ thread: { ...thread, @@ -1793,7 +1793,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec return threadRef && thread ? [{ threadKey, threadRef, thread }] : []; }); const hasRunningThread = selectedThreadEntries.some( - ({ thread }) => thread.session?.status === "running" && thread.session.activeTurnId != null, + ({ thread }) => thread.runtime?.status === "running" && thread.runtime.activeRunId != null, ); const clicked = await api.contextMenu.show( @@ -1803,7 +1803,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec if (clicked === "mark-unread") { for (const { threadKey, thread } of selectedThreadEntries) { - markThreadUnread(threadKey, thread.latestTurn?.completedAt); + markThreadUnread(threadKey, thread.latestRun?.completedAt); } clearSelection(); return; @@ -2181,7 +2181,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec } if (clicked === "mark-unread") { - markThreadUnread(threadKey, thread.latestTurn?.completedAt); + markThreadUnread(threadKey, thread.latestRun?.completedAt); return; } if (clicked === "copy-path") { diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx index a40c531a52..a76ea0662b 100644 --- a/apps/web/src/components/ProjectScriptsControl.tsx +++ b/apps/web/src/components/ProjectScriptsControl.tsx @@ -7,8 +7,8 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import { ChevronDownIcon, DownloadIcon, PlusIcon, SettingsIcon } from "lucide-react"; -import { useCallback, useMemo, useState } from "react"; +import { ChevronDownIcon, DownloadIcon, PlusIcon, SettingsIcon, WrenchIcon } from "lucide-react"; +import React, { useCallback, useMemo, useState } from "react"; import { commandForProjectScript, primaryProjectScript } from "~/projectScripts"; import { shortcutLabelForCommand } from "~/keybindings"; @@ -77,14 +77,11 @@ export default function ProjectScriptsControl({ onUpdateScript, onDeleteScript, }: ProjectScriptsControlProps) { -<<<<<<< HEAD -======= const isPanel = displayMode === "panel"; const ActionGroup = isPanel ? "div" : Group; const panelAnchorRef = React.useRef(null); const addScriptFormId = React.useId(); const [editingScriptId, setEditingScriptId] = useState(null); ->>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar) const [actionsMenuOpen, setActionsMenuOpen] = useState({ scripts: false, imports: false, diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 3ab98f5a67..c48a0c1773 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -42,14 +42,11 @@ import { PierreEntryIcon } from "./chat/PierreEntryIcon"; interface RightPanelTabsProps { mode: PreviewPanelMode; maximized?: boolean; -<<<<<<< HEAD /** Forwarded to PreviewPanelShell so this surface persists its own width. */ widthStorageKey?: string; /** Forwarded to PreviewPanelShell as the initial width before a user resize. */ defaultWidth?: number; -======= inlineSize?: PreviewPanelInlineSize; ->>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar) layoutControls?: ReactNode; surfaces: readonly RightPanelSurface[]; activeSurfaceId: string | null; @@ -603,12 +600,9 @@ export function RightPanelTabs(props: RightPanelTabsProps) { >>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar) >
{ }); describe("resolveSidebarThreadStatus", () => { - const session = { - threadId: ThreadId.make("thread-1"), -describe("resolveSidebarV2Status", () => { const runtime = { status: "running" as const, activeRunId: null, @@ -735,20 +729,16 @@ describe("resolveSidebarV2Status", () => { const idle = { hasPendingApprovals: false, hasPendingUserInput: false, runtime: null }; - it("prioritizes approval over a running session", () => { - expect(resolveSidebarThreadStatus({ ...idle, hasPendingApprovals: true, session })).toBe( it("prioritizes approval over a running runtime", () => { - expect(resolveSidebarV2Status({ ...idle, hasPendingApprovals: true, runtime })).toBe( + expect(resolveSidebarThreadStatus({ ...idle, hasPendingApprovals: true, runtime })).toBe( "approval", ); }); - it("prioritizes awaiting input over a running session, below approval", () => { - expect(resolveSidebarThreadStatus({ ...idle, hasPendingUserInput: true, session })).toBe( + it("prioritizes awaiting input over a running runtime, below approval", () => { + expect(resolveSidebarThreadStatus({ ...idle, hasPendingUserInput: true, runtime })).toBe( "input", ); - it("prioritizes awaiting input over a running runtime, below approval", () => { - expect(resolveSidebarV2Status({ ...idle, hasPendingUserInput: true, runtime })).toBe("input"); expect( resolveSidebarThreadStatus({ ...idle, @@ -759,10 +749,8 @@ describe("resolveSidebarV2Status", () => { ).toBe("approval"); }); - it("reports working for running and starting sessions", () => { - expect(resolveSidebarThreadStatus({ ...idle, session })).toBe("working"); it("reports working for running and starting runtimes", () => { - expect(resolveSidebarV2Status({ ...idle, runtime })).toBe("working"); + expect(resolveSidebarThreadStatus({ ...idle, runtime })).toBe("working"); expect( resolveSidebarThreadStatus({ ...idle, @@ -792,10 +780,8 @@ describe("resolveSidebarV2Status", () => { ).toBe("waiting"); }); - it("defaults to ready with no session", () => { - expect(resolveSidebarThreadStatus({ ...idle, session: null })).toBe("ready"); it("defaults to ready with no runtime", () => { - expect(resolveSidebarV2Status(idle)).toBe("ready"); + expect(resolveSidebarThreadStatus(idle)).toBe("ready"); }); it("keeps a waiting runtime visible ahead of unread and woke presentation", () => { @@ -856,136 +842,6 @@ describe("sortThreadsForSidebar", () => { }); }); -describe("pinOrderKeyBetween", () => { - it("produces keys that sort between their bounds", () => { - const middle = pinOrderKeyBetween(null, null)!; - const top = pinOrderKeyBetween(null, middle)!; - const bottom = pinOrderKeyBetween(middle, null)!; - expect(top < middle).toBe(true); - expect(middle < bottom).toBe(true); - - const between = pinOrderKeyBetween(top, middle)!; - expect(top < between && between < middle).toBe(true); - }); - - it("extends into new digits when bounds are adjacent", () => { - const key = pinOrderKeyBetween("g", "h")!; - expect("g" < key && key < "h").toBe(true); - }); - - it("stays strictly ordered under repeated top insertion", () => { - // Every new pin lands at the head of the arranged run; keys must keep - // sorting before the previous head without ever bottoming out. - let head: string | null = null; - const keys: string[] = []; - for (let i = 0; i < 100; i += 1) { - const key: string = pinOrderKeyBetween(null, head)!; - expect(key).not.toBeNull(); - if (head !== null) expect(key < head).toBe(true); - keys.push(key); - head = key; - } - expect(new Set(keys).size).toBe(100); - }); - - it("stays strictly ordered under repeated middle insertion", () => { - let low = pinOrderKeyBetween(null, null)!; - let high = pinOrderKeyBetween(low, null)!; - for (let i = 0; i < 100; i += 1) { - const key: string = pinOrderKeyBetween(low, high)!; - expect(low < key && key < high).toBe(true); - if (i % 2 === 0) low = key; - else high = key; - } - }); - - it("returns null for corrupt or out-of-order bounds instead of throwing", () => { - expect(pinOrderKeyBetween("z", "a")).toBeNull(); - expect(pinOrderKeyBetween("A!", null)).toBeNull(); - expect(pinOrderKeyBetween(null, "ma")).toBeNull(); - expect(pinOrderKeyBetween("m", "m")).toBeNull(); - }); -}); - -describe("planPinnedReorder", () => { - it("writes only the moved thread when neighbors are keyed", () => { - const assignments = planPinnedReorder({ - orderedIds: ["a", "c", "b"], - keysById: new Map([ - ["a", "f"], - ["b", "m"], - ["c", "t"], - ]), - movedId: "c", - }); - expect(assignments).toHaveLength(1); - expect(assignments[0]!.id).toBe("c"); - expect(assignments[0]!.orderKey > "f" && assignments[0]!.orderKey < "m").toBe(true); - }); - - it("treats list edges as open bounds", () => { - const assignments = planPinnedReorder({ - orderedIds: ["b", "a"], - keysById: new Map([ - ["a", "m"], - ["b", null], - ]), - movedId: "b", - }); - expect(assignments).toHaveLength(1); - expect(assignments[0]!.orderKey < "m").toBe(true); - }); - - it("materializes keys for the whole section when a neighbor is keyless", () => { - const assignments = planPinnedReorder({ - orderedIds: ["b", "a", "c"], - keysById: new Map([ - ["a", null], - ["b", "m"], - ["c", null], - ]), - movedId: "b", - }); - expect(assignments.map((entry) => entry.id)).toEqual(["b", "a", "c"]); - const keys = assignments.map((entry) => entry.orderKey); - expect([...keys].sort()).toEqual(keys); - expect(new Set(keys).size).toBe(keys.length); - }); -}); - -describe("sortPinnedThreadsForSidebar", () => { - const pinnable = (input: { id: string; createdAt: string; pinOrderKey?: string | null }) => ({ - id: input.id, - createdAt: input.createdAt, - pinOrderKey: input.pinOrderKey ?? null, - }); - - it("sorts keyed threads by key ahead of keyless threads in creation order", () => { - const sorted = sortPinnedThreadsForSidebar([ - pinnable({ id: "keyless-old", createdAt: "2026-03-09T08:00:00.000Z" }), - pinnable({ id: "second", createdAt: "2026-03-09T09:00:00.000Z", pinOrderKey: "t" }), - pinnable({ id: "keyless-new", createdAt: "2026-03-09T12:00:00.000Z" }), - pinnable({ id: "first", createdAt: "2026-03-09T07:00:00.000Z", pinOrderKey: "g" }), - ]); - - expect(sorted.map((thread) => thread.id)).toEqual([ - "first", - "second", - "keyless-new", - "keyless-old", - ]); - }); - - it("breaks equal keys by id so raced writes render identically everywhere", () => { - const sorted = sortPinnedThreadsForSidebar([ - pinnable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z", pinOrderKey: "m" }), - pinnable({ id: "a", createdAt: "2026-03-09T11:00:00.000Z", pinOrderKey: "m" }), - ]); - - expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]); - }); -}); - describe("sortSettledThreadsForSidebar", () => { const settled = (input: { id: string; @@ -1876,3 +1732,133 @@ describe("resolveThreadLastVisitedAt", () => { expect(resolveThreadLastVisitedAt(null, "2026-07-30T10:00:00.000Z")).toBeUndefined(); }); }); + +describe("pinOrderKeyBetween", () => { + it("produces keys that sort between their bounds", () => { + const middle = pinOrderKeyBetween(null, null)!; + const top = pinOrderKeyBetween(null, middle)!; + const bottom = pinOrderKeyBetween(middle, null)!; + expect(top < middle).toBe(true); + expect(middle < bottom).toBe(true); + + const between = pinOrderKeyBetween(top, middle)!; + expect(top < between && between < middle).toBe(true); + }); + + it("extends into new digits when bounds are adjacent", () => { + const key = pinOrderKeyBetween("g", "h")!; + expect("g" < key && key < "h").toBe(true); + }); + + it("stays strictly ordered under repeated top insertion", () => { + // Every new pin lands at the head of the arranged run; keys must keep + // sorting before the previous head without ever bottoming out. + let head: string | null = null; + const keys: string[] = []; + for (let i = 0; i < 100; i += 1) { + const key: string = pinOrderKeyBetween(null, head)!; + expect(key).not.toBeNull(); + if (head !== null) expect(key < head).toBe(true); + keys.push(key); + head = key; + } + expect(new Set(keys).size).toBe(100); + }); + + it("stays strictly ordered under repeated middle insertion", () => { + let low = pinOrderKeyBetween(null, null)!; + let high = pinOrderKeyBetween(low, null)!; + for (let i = 0; i < 100; i += 1) { + const key: string = pinOrderKeyBetween(low, high)!; + expect(low < key && key < high).toBe(true); + if (i % 2 === 0) low = key; + else high = key; + } + }); + + it("returns null for corrupt or out-of-order bounds instead of throwing", () => { + expect(pinOrderKeyBetween("z", "a")).toBeNull(); + expect(pinOrderKeyBetween("A!", null)).toBeNull(); + expect(pinOrderKeyBetween(null, "ma")).toBeNull(); + expect(pinOrderKeyBetween("m", "m")).toBeNull(); + }); +}); + +describe("planPinnedReorder", () => { + it("writes only the moved thread when neighbors are keyed", () => { + const assignments = planPinnedReorder({ + orderedIds: ["a", "c", "b"], + keysById: new Map([ + ["a", "f"], + ["b", "m"], + ["c", "t"], + ]), + movedId: "c", + }); + expect(assignments).toHaveLength(1); + expect(assignments[0]!.id).toBe("c"); + expect(assignments[0]!.orderKey > "f" && assignments[0]!.orderKey < "m").toBe(true); + }); + + it("treats list edges as open bounds", () => { + const assignments = planPinnedReorder({ + orderedIds: ["b", "a"], + keysById: new Map([ + ["a", "m"], + ["b", null], + ]), + movedId: "b", + }); + expect(assignments).toHaveLength(1); + expect(assignments[0]!.orderKey < "m").toBe(true); + }); + + it("materializes keys for the whole section when a neighbor is keyless", () => { + const assignments = planPinnedReorder({ + orderedIds: ["b", "a", "c"], + keysById: new Map([ + ["a", null], + ["b", "m"], + ["c", null], + ]), + movedId: "b", + }); + expect(assignments.map((entry) => entry.id)).toEqual(["b", "a", "c"]); + const keys = assignments.map((entry) => entry.orderKey); + expect([...keys].sort()).toEqual(keys); + expect(new Set(keys).size).toBe(keys.length); + }); +}); + +describe("sortPinnedThreadsForSidebar", () => { + const pinnable = (input: { id: string; createdAt: string; pinOrderKey?: string | null }) => ({ + id: input.id, + createdAt: input.createdAt, + pinOrderKey: input.pinOrderKey ?? null, + }); + + it("sorts keyed threads by key ahead of keyless threads in creation order", () => { + const sorted = sortPinnedThreadsForSidebar([ + pinnable({ id: "keyless-old", createdAt: "2026-03-09T08:00:00.000Z" }), + pinnable({ id: "second", createdAt: "2026-03-09T09:00:00.000Z", pinOrderKey: "t" }), + pinnable({ id: "keyless-new", createdAt: "2026-03-09T12:00:00.000Z" }), + pinnable({ id: "first", createdAt: "2026-03-09T07:00:00.000Z", pinOrderKey: "g" }), + ]); + + expect(sorted.map((thread) => thread.id)).toEqual([ + "first", + "second", + "keyless-new", + "keyless-old", + ]); + }); + + it("breaks equal keys by id so raced writes render identically everywhere", () => { + const sorted = sortPinnedThreadsForSidebar([ + pinnable({ id: "b", createdAt: "2026-03-09T10:00:00.000Z", pinOrderKey: "m" }), + pinnable({ id: "a", createdAt: "2026-03-09T11:00:00.000Z", pinOrderKey: "m" }), + ]); + + expect(sorted.map((thread) => thread.id)).toEqual(["a", "b"]); + }); +}); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 8513910157..fdbd87b56e 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -495,8 +495,6 @@ export function resolveThreadRowClassName(input: { ); } -// ── Sidebar thread status model ───────────────────────────────────── -// Five visual states, three colors: color is reserved for "act now" // ── Sidebar v2 status model ───────────────────────────────────────── // Six visual states, three colors: color is reserved for "act now" // (approval), "in motion" (working), and "broken" (failed). Ready is the @@ -507,14 +505,7 @@ export function resolveThreadRowClassName(input: { // false Done. // Unread completion is tracked separately: it describes whether a ready // thread needs attention, not what the thread is currently doing. -export type SidebarThreadStatus = - | "approval" - | "input" - | "working" - | "monitoring" - | "failed" - | "ready"; -export type SidebarV2Status = "approval" | "input" | "working" | "waiting" | "failed" | "ready"; +export type SidebarThreadStatus = "approval" | "input" | "working" | "waiting" | "failed" | "ready"; type SidebarThreadStatusInput = Pick< SidebarThreadSummary, @@ -553,7 +544,7 @@ export type SidebarV2TopStatusKind = | "working"; export function resolveSidebarV2TopStatus(input: { - readonly status: SidebarV2Status; + readonly status: SidebarThreadStatus; readonly isUnread: boolean; readonly isWoke: boolean; }): SidebarV2TopStatusKind | null { @@ -578,7 +569,7 @@ export function resolveSidebarV2TopStatus(input: { return input.isUnread ? "done" : null; } -export function shouldShowSidebarV2Duration(status: SidebarV2Status): boolean { +export function shouldShowSidebarV2Duration(status: SidebarThreadStatus): boolean { return status === "working"; } @@ -615,7 +606,7 @@ export function firstValidTimestamp( return null; } -// Sidebar sort: static creation order, newest thread on top. Activity NEVER +// v2 sort: static creation order, newest thread on top. Activity NEVER // reorders the list — a row holds its position from open until settled, so // the screen only moves at lifecycle transitions. Status (including pending // approval) is carried by each card's edge strip, not by position. diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index cff457aad5..faf24e12f6 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,29 +1,3 @@ -import { - ArchiveIcon, - ArrowUpDownIcon, - ChevronRightIcon, - CloudIcon, - ContainerIcon, - FolderPlusIcon, - GitForkIcon, - Globe2Icon, - LoaderIcon, - SearchIcon, - SquarePenIcon, - TerminalIcon, - TriangleAlertIcon, -} from "lucide-react"; -import { - ChangeRequestStatusIcon, - prStatusIndicator, - PrStatusTooltipContent, - resolveThreadPr, - terminalStatusFromRunningIds, - ThreadStatusLabel, - ThreadWorktreeIndicator, -} from "./ThreadStatusIndicators"; -import { ProjectFavicon } from "./ProjectFavicon"; -import { useAtomValue } from "@effect/atom-react"; import { autoAnimate } from "@formkit/auto-animate"; import { useAtomValue } from "@effect/atom-react"; import * as Schema from "effect/Schema"; @@ -133,14 +107,6 @@ import { useNowMinute } from "../hooks/useNowMinute"; import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; import { useProjects, useThreadShells } from "../state/entities"; import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server"; -import { useComposerDraftStore } from "../composerDraftStore"; -import { useNewThreadHandler } from "../hooks/useHandleNewThread"; -import { useDesktopUpdateState } from "../state/desktopUpdate"; - -import { useMarkThreadUnread, useThreadActions } from "../hooks/useThreadActions"; -import { projectEnvironment } from "../state/projects"; -import { useEnvironmentQuery } from "../state/query"; -import { threadEnvironment, useEnvironmentThread } from "../state/threads"; import { vcsEnvironment } from "../state/vcs"; import { threadEnvironment } from "../state/threads"; import { useEnvironmentQuery } from "../state/query"; @@ -150,91 +116,12 @@ import { resolveActiveThreadRouteRef, resolveThreadRouteTarget, } from "../threadRoutes"; -import { stackedThreadToast, toastManager } from "./ui/toast"; -import { formatRelativeTimeLabel } from "../timestampFormat"; -import { SettingsSidebarNav } from "./settings/SettingsSidebarNav"; -import { Kbd } from "./ui/kbd"; -import { - getArm64IntelBuildWarningDescription, - getDesktopUpdateActionError, - getDesktopUpdateInstallConfirmationMessage, - isDesktopUpdateButtonDisabled, - resolveDesktopUpdateButtonAction, - shouldShowArm64IntelBuildWarning, - shouldToastDesktopUpdateActionResult, -} from "./desktopUpdate.logic"; -import { showDesktopUpdateDownloadedToast } from "./desktopUpdate.toast"; -import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert"; -import { Button } from "./ui/button"; -import { - Dialog, - DialogDescription, - DialogFooter, - DialogHeader, - DialogPanel, - DialogPopup, - DialogTitle, -} from "./ui/dialog"; -import { Input } from "./ui/input"; -import { Menu, MenuGroup, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu"; -import { - NumberField, - NumberFieldDecrement, - NumberFieldGroup, - NumberFieldIncrement, - NumberFieldInput, -} from "./ui/number-field"; -import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; -import { - SidebarContent, - SidebarGroup, - SidebarMenu, - SidebarMenuButton, - SidebarMenuItem, - SidebarMenuSub, - SidebarMenuSubButton, - SidebarMenuSubItem, - useSidebar, -} from "./ui/sidebar"; -import { useThreadSelectionStore } from "../threadSelectionStore"; -import { openCommandPalette } from "../commandPaletteBus"; -import { - archiveSelectedThreadEntries, - buildMultiSelectThreadContextMenuItems, - getSidebarForkParentThreadId, - getSidebarThreadIdsToPrewarm, - isSidebarSubagentThread, - resolveAdjacentThreadId, - isContextMenuPointerDown, - isTrailingDoubleClick, - resolveProjectStatusIndicator, - resolveThreadLastVisitedAt, - resolveThreadRowClassName, - resolveThreadStatusPill, - orderItemsByPreferredIds, - shouldClearThreadSelectionOnMouseDown, - sortProjectsForSidebar, - useThreadJumpHintVisibility, - ThreadStatusPill, -} from "./Sidebar.logic"; -import { sortThreads } from "../lib/threadSort"; -import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; -import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; -import { useIsMobile } from "~/hooks/useMediaQuery"; -import { CommandDialogTrigger } from "./ui/command"; -import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings"; -import { primaryServerKeybindingsAtom } from "../state/server"; -import { - derivePhysicalProjectKey, - deriveProjectGroupingOverrideKey, - getProjectOrderKey, - selectProjectGroupingSettings, -} from "../logicalProject"; +import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat"; import type { SidebarThreadSummary } from "../types"; import { cn } from "~/lib/utils"; import { buildThreadActionMenuItems } from "./threadActionMenu.logic"; import { + filterSidebarV2VisibleThreads, buildBulkTitleRegenerationContextMenuItem, formatWorkingDurationLabel, firstValidTimestampMs, @@ -431,7 +318,7 @@ function SidebarThreadTooltip({
{modelLabel}
@@ -448,7 +335,7 @@ function SidebarThreadTooltip({
) : null} - {thread.session?.lastError ? ( + {thread.runtime?.lastError ? (
Error occurred
@@ -847,9 +734,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { [thread.environmentId, thread.id], ); const threadKey = scopedThreadKey(threadRef); - const forkParentThreadId = getSidebarForkParentThreadId(thread); - const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); - const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt); + const isRegeneratingTitle = thread.titleRegeneration != null; + const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); const openPrLink = useOpenPrLink(); const runningTerminalIds = useThreadRunningTerminalIds({ @@ -868,40 +754,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { }) : null, ); - const isHighlighted = isActive || isSelected; - const handleOpenDiscoveredPort = useCallback( - (event: React.MouseEvent) => { - const port = discoveredPorts[0]; - if (!port) return; - event.preventDefault(); - event.stopPropagation(); - navigateToThread(threadRef); - void (async () => { - const result = await openDiscoveredPort({ threadRef, port, openPreview }); - if (result._tag === "Success" || isAtomCommandInterrupted(result)) { - return; - } - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Unable to open preview", - description: - error instanceof Error ? error.message : "The preview could not be opened.", - }), - ); - })(); - }, - [discoveredPorts, navigateToThread, openPreview, threadRef], - ); - const isThreadRunning = - thread.runtime?.status === "running" && thread.runtime.activeRunId != null; - const threadStatus = resolveThreadStatusPill({ - thread: { - ...thread, - lastVisitedAt, - }, - }); const pr = resolveThreadPr({ threadBranch: thread.branch, gitStatus: gitStatus.data, @@ -932,8 +784,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { // findable. In-flight rows recede the same as read-ready ones (inbox-zero: // working threads aren't your problem yet) — only the colored status label // stands out. - const isInFlight = - status === "working" || status === "monitoring" || status === "approval" || status === "input"; + const isInFlight = status === "working" || status === "approval" || status === "input"; const shouldRecede = (status === "ready" || isInFlight) && !isUnread && !isWoke && !props.isActive && !isSelected; // Status hues follow the system-wide convention set by sidebar v1 and the @@ -951,13 +802,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { // the label at full strength. className: cn("text-sky-600 dark:text-sky-400", !props.isActive && "opacity-75"), } - : status === "monitoring" + : status === "waiting" ? { - // Monitoring is calm background presence, not active progress - // (monitoring-pill D6), so it keeps the label at full strength. - label: "Monitoring", + // Waiting is calm background presence (post-settle background + // roster), not active progress, so the label keeps full strength. + label: "Waiting", icon: null, - className: "text-sky-600 dark:text-sky-400", + className: "text-muted-foreground", } : status === "approval" ? { @@ -1006,7 +857,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { onChangeRequestState(threadKey, prState); }, [onChangeRequestState, prState, threadKey]); - const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId; + const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; const driverKind = providerEntry?.driverKind ?? null; const selectedModel = providerEntry?.models.find( @@ -1077,40 +928,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { }, [isRenaming, onStartRename, thread.title, threadRef], ); - const handlePrClick = useCallback( - (event: React.MouseEvent) => { - if (!prStatus) return; - openPrLink(event, prStatus.url); - }, - [openPrLink, prStatus], - ); - const handleOpenForkParentClick = useCallback( - (event: React.MouseEvent) => { - if (forkParentThreadId === null) return; - event.preventDefault(); - event.stopPropagation(); - navigateToThread(scopeThreadRef(thread.environmentId, forkParentThreadId)); - }, - [forkParentThreadId, navigateToThread, thread.environmentId], - ); - const handleRenameInputRef = useCallback( - (element: HTMLInputElement | null) => { - if (element && renamingInputRef.current !== element) { - renamingInputRef.current = element; - element.focus(); - element.select(); - } - }, - [renamingInputRef], - ); - const handleRenameInputChange = useCallback( - (event: React.ChangeEvent) => { - setRenamingTitle(event.target.value); - }, - [setRenamingTitle], - ); - const handleRenameInputKeyDown = useCallback( - (event: React.KeyboardEvent) => { + const renameCommittedRef = useRef(false); + useEffect(() => { + if (isRenaming) renameCommittedRef.current = false; + }, [isRenaming]); + const handleRenameKeyDown = useCallback( + (event: ReactKeyboardEvent) => { event.stopPropagation(); if (event.nativeEvent.isComposing || event.keyCode === 229) return; if (event.key === "Enter") { @@ -1430,7 +1253,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { ); } - const diff = latestTurnDiff(thread); + const diff = latestRunDiff(thread); const sortable = props.sortable; return ( @@ -1641,7 +1464,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { @@ -1657,7 +1480,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { ); }); -function latestTurnDiff( +function latestRunDiff( thread: SidebarThreadSummary, ): { insertions: number; deletions: number } | null { // Shells don't carry checkpoint summaries; diff stats render only when the @@ -1697,7 +1520,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: { activeThreadBranch: thread.branch, currentGitBranch: gitStatus.data?.refName ?? null, }); - const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId; + const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; const driverKind = providerEntry?.driverKind ?? null; const selectedModel = providerEntry?.models.find( @@ -1797,43 +1620,6 @@ export default function Sidebar() { }); const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({ onCopy: ({ path }) => { - const updateSettings = useUpdateClientSettings(); - const sidebarThreadPreviewCount = useClientSettings( - (settings) => settings.sidebarThreadPreviewCount, - ); - const router = useRouter(); - const { isMobile, setOpenMobile } = useSidebar(); - const markThreadUnread = useMarkThreadUnread(); - const setProjectExpanded = useUiStateStore((state) => state.setProjectExpanded); - const toggleThreadSelection = useThreadSelectionStore((state) => state.toggleThread); - const rangeSelectTo = useThreadSelectionStore((state) => state.rangeSelectTo); - const clearSelection = useThreadSelectionStore((state) => state.clearSelection); - const removeFromSelection = useThreadSelectionStore((state) => state.removeFromSelection); - const setSelectionAnchor = useThreadSelectionStore((state) => state.setAnchor); - const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ - threadId: ThreadId; - }>({ - onCopy: (ctx) => { - toastManager.add({ - type: "success", - title: "Thread ID copied", - description: ctx.threadId, - }); - }, - onError: (error) => { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to copy thread ID", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - }, - }); - const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ - path: string; - }>({ - onCopy: (ctx) => { toastManager.add({ type: "success", title: "Path copied", @@ -1893,7 +1679,41 @@ export default function Sidebar() { () => openCommandPalette({ open: "add-project" }), [], ); - const sidebarThreadByKey = useMemo( + const { environments } = useEnvironments(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const clearSelection = useThreadSelectionStore((s) => s.clearSelection); + const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); + const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread); + const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo); + const markThreadUnread = useUiStateStore((s) => s.markThreadUnread); + const markThreadVisited = useUiStateStore((s) => s.markThreadVisited); + const acknowledgeWoke = useCallback( + (threadRef: ScopedThreadRef, visitedAt: string) => { + markThreadVisited(scopedThreadKey(threadRef), visitedAt); + }, + [markThreadVisited], + ); + const routeTarget = useParams({ + strict: false, + select: (params) => resolveThreadRouteTarget(params), + }); + const routeDraftThread = useComposerDraftStore((store) => + routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null, + ); + const routeThreadRef = useMemo( + () => resolveActiveThreadRouteRef(routeTarget, routeDraftThread), + [routeDraftThread, routeTarget], + ); + const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; + const routeTargetRef = useRef(routeTarget); + routeTargetRef.current = routeTarget; + // Post-settle navigation validates against the CURRENT route, not the one + // captured when the settle started: if the user navigated elsewhere while + // the command was in flight, completing it must not yank them away. + const routeThreadKeyRef = useRef(routeThreadKey); + routeThreadKeyRef.current = routeThreadKey; + + const environmentLabelById = useMemo( () => new Map( environments.map((environment) => [environment.environmentId, environment.label] as const), @@ -2098,12 +1918,9 @@ export default function Sidebar() { // memo exactly at the next wake boundary. void snoozeWakeTick; const preciseNow = new Date().toISOString(); - const visible = threads.filter( - (thread) => - thread.archivedAt === null && - (scopedProjectKeys === null || - scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)), - ); + // Subagent child threads live in the parent's Agents surface, not the + // sidebar roster (v2 models them as real threads with lineage). + const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys); const pinned: EnvironmentThreadShell[] = []; const active: EnvironmentThreadShell[] = []; const snoozed: EnvironmentThreadShell[] = []; @@ -2334,45 +2151,16 @@ export default function Sidebar() { ), [orderedThreads], ); - // Keep a ref so callbacks can read the latest map without appearing in - // dependency arrays (avoids invalidating every thread-row memo on each - // thread-list change). - const sidebarThreadByKeyRef = useRef(sidebarThreadByKey); - sidebarThreadByKeyRef.current = sidebarThreadByKey; - const projectThreads = visibleSidebarThreads; - const projectPreferenceKeys = useMemo(() => projectExpansionPreferenceKeys(project), [project]); - const projectExpanded = useUiStateStore((state) => - resolveProjectExpanded(state.projectExpandedById, projectPreferenceKeys), - ); - const threadLastVisitedAts = useUiStateStore( - useShallow((state) => - projectThreads.map( - (thread) => - resolveThreadLastVisitedAt( - thread.lastVisitedAt, - state.threadLastVisitedAtById[ - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) - ], - ) ?? null, - ), - ), - ); - const [renamingThreadKey, setRenamingThreadKey] = useState(null); - const [renamingTitle, setRenamingTitle] = useState(""); - const [confirmingArchiveThreadKey, setConfirmingArchiveThreadKey] = useState(null); - const [projectRenameTarget, setProjectRenameTarget] = useState( - null, - ); - const [projectRenameTitle, setProjectRenameTitle] = useState(""); - const [projectGroupingTarget, setProjectGroupingTarget] = - useState(null); - const [projectGroupingSelection, setProjectGroupingSelection] = useState< - SidebarProjectGroupingMode | "inherit" - >("inherit"); - const renamingCommittedRef = useRef(false); - const renamingInputRef = useRef(null); - const confirmArchiveButtonRefs = useRef(new Map()); - const memberProjectByScopedKey = useMemo( + // Handlers read these through refs: depending on per-update Map/Set + // identities would give every row a fresh callback prop on each shell + // event and defeat row memoization during streaming. + const threadByKeyRef = useRef(threadByKey); + threadByKeyRef.current = threadByKey; + // handleNewThread is inherently unstable (depends on the projects list); + // a ref keeps it out of attemptSettle's dependency array. + const handleNewThreadRef = useRef(newThreadContext.handleNewThread); + handleNewThreadRef.current = newThreadContext.handleNewThread; + const settledThreadKeys = useMemo( () => new Set( settledThreads.map((thread) => @@ -2552,7 +2340,6 @@ export default function Sidebar() { [navigateToThread, rangeSelectTo, toggleThreadSelection], ); -<<<<<<< HEAD // A settle per thread at a time: double clicks and repeated menu picks // must not dispatch a second settle that fails and toasts a false error. const settlingThreadKeysRef = useRef(new Set()); @@ -2585,32 +2372,37 @@ export default function Sidebar() { }, [navigateToThread, router], ); -======= - const handleMultiSelectContextMenu = useCallback( - async (position: { x: number; y: number }) => { - const api = readLocalApi(); - if (!api) return; - const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys]; - if (threadKeys.length === 0) return; - const count = threadKeys.length; - const selectedThreadEntries = threadKeys.flatMap((threadKey) => { - const threadRef = parseScopedThreadKey(threadKey); - const thread = threadRef ? readThreadShell(threadRef) : null; - return threadRef && thread ? [{ threadKey, threadRef, thread }] : []; - }); - const hasRunningThread = selectedThreadEntries.some( - ({ thread }) => thread.runtime?.status === "running" && thread.runtime.activeRunId !== null, - ); ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) - const clicked = await api.contextMenu.show( - buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }), - position, - ); - - if (clicked === "mark-unread") { - for (const { threadRef } of selectedThreadEntries) { - markThreadUnread(threadRef); + const attemptSettle = useCallback( + (threadRef: ScopedThreadRef, opts: { coSettlingKeys?: ReadonlySet } = {}) => { + void (async () => { + const threadKey = scopedThreadKey(threadRef); + if (settlingThreadKeysRef.current.has(threadKey)) return; + settlingThreadKeysRef.current.add(threadKey); + try { + const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys); + const result = await settleThread(threadRef); + if (result._tag === "Failure") { + // Never navigate away from a thread that did not settle. + if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to settle thread", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + return; + } + // Only move forward if the user is still on the settled thread — + // a navigation made during the await wins over ours. + if (routeThreadKeyRef.current === threadKey) { + navigateAfterSettle?.(); + } + } finally { + settlingThreadKeysRef.current.delete(threadKey); } })(); }, @@ -3067,7 +2859,7 @@ export default function Sidebar() { if (clicked.value === "mark-unread") { for (const threadKey of threadKeys) { const thread = threadByKeyRef.current.get(threadKey); - markThreadUnread(threadKey, thread?.latestTurn?.completedAt); + markThreadUnread(threadKey, thread?.latestRun?.completedAt); } clearSelection(); return; @@ -3130,73 +2922,14 @@ export default function Sidebar() { ); const handleThreadContextMenu = useCallback( - async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { - const api = readLocalApi(); - if (!api) return; - const threadKey = scopedThreadKey(threadRef); - const thread = sidebarThreadByKeyRef.current.get(threadKey) ?? null; - if (!thread) return; - const threadProject = memberProjectByScopedKey.get( - scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), - ); - const threadWorkspacePath = - thread.worktreePath ?? threadProject?.workspaceRoot ?? project.workspaceRoot ?? null; - const clicked = await api.contextMenu.show( - [ - ...(thread.branch - ? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }] - : []), - { id: "rename", label: "Rename thread" }, - { id: "mark-unread", label: "Mark unread" }, - { id: "copy-path", label: "Copy Path" }, - { id: "copy-thread-id", label: "Copy Thread ID" }, - { id: "delete", label: "Delete", destructive: true, icon: "trash" }, - ], - position, - ); - - if (clicked === "new-thread-on-branch") { - // Explicit branch carry-over: reuse the thread's worktree when it - // has one, otherwise its branch on the local checkout. - const result = await settlePromise(() => - handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), { - branch: thread.branch, - worktreePath: thread.worktreePath, - envMode: thread.worktreePath ? "worktree" : "local", - startFromOrigin: false, - }), - ); - if (result._tag === "Failure") { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not create thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - return; - } - - if (clicked === "rename") { - startThreadRename(threadKey, thread.title); - return; - } - - if (clicked === "mark-unread") { - markThreadUnread(scopeThreadRef(thread.environmentId, thread.id)); - return; - } - if (clicked === "copy-path") { - if (!threadWorkspacePath) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Path unavailable", - description: "This thread does not have a workspace path to copy.", - }), - ); + (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { + void (async () => { + const api = readLocalApi(); + if (!api) return; + const threadKey = scopedThreadKey(threadRef); + const selectionState = useThreadSelectionStore.getState(); + if (selectionState.hasSelection() && selectionState.selectedThreadKeys.has(threadKey)) { + await handleMultiSelectContextMenu(position); return; } const thread = threadByKeyRef.current.get(threadKey); @@ -3314,7 +3047,7 @@ export default function Sidebar() { return; } case "mark-unread": - markThreadUnread(threadKey, thread.latestTurn?.completedAt); + markThreadUnread(threadKey, thread.latestRun?.completedAt); return; case "copy-path": if (!threadWorkspacePath) { @@ -3398,390 +3131,6 @@ export default function Sidebar() { ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen : false, ); - const keybindings = useAtomValue(primaryServerKeybindingsAtom); - const openAddProjectCommandPalette = useCallback( - () => openCommandPalette({ open: "add-project" }), - [], - ); - const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState< - ReadonlySet - >(() => new Set()); - const { showThreadJumpHints, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility(); - const dragInProgressRef = useRef(false); - const suppressProjectClickAfterDragRef = useRef(false); - const suppressProjectClickForContextMenuRef = useRef(false); - const desktopUpdateState = useDesktopUpdateState(); - const clearSelection = useThreadSelectionStore((s) => s.clearSelection); - const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); - const platform = navigator.platform; - const shortcutModifiers = useShortcutModifierState(); - const { environments } = useEnvironments(); - const primaryEnvironmentId = usePrimaryEnvironmentId(); - const environmentLabelById = useMemo( - () => - new Map( - environments.map((environment) => [environment.environmentId, environment.label] as const), - ), - [environments], - ); - const desktopLocalEnvironmentIds = useMemo( - () => - new Set( - environments - .filter((environment) => isDesktopLocalConnectionTarget(environment.entry.target)) - .map((environment) => environment.environmentId), - ), - [environments], - ); - const orderedProjects = useMemo(() => { - return orderItemsByPreferredIds({ - items: projects, - preferredIds: projectOrder, - getId: getProjectOrderKey, - getPreferenceIds: (project) => [ - getProjectOrderKey(project), - legacyProjectCwdPreferenceKey(project.workspaceRoot), - ], - }); - }, [projectOrder, projects]); - - // Build a mapping from physical project key → logical project key for - // cross-environment grouping. Projects that share a repositoryIdentity - // canonicalKey are treated as one logical project in the sidebar. - const physicalToLogicalKey = useMemo(() => { - return buildPhysicalToLogicalProjectKeyMap({ - projects: orderedProjects, - settings: projectGroupingSettings, - primaryEnvironmentId, - }); - }, [orderedProjects, projectGroupingSettings, primaryEnvironmentId]); - const projectPhysicalKeyByScopedRef = useMemo( - () => - new Map( - orderedProjects.map((project) => [ - scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), - derivePhysicalProjectKey(project), - ]), - ), - [orderedProjects], - ); - - const sidebarProjects = useMemo(() => { - return buildSidebarProjectSnapshots({ - projects: orderedProjects, - settings: projectGroupingSettings, - primaryEnvironmentId, - resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null, - isDesktopLocalEnvironment: (environmentId) => desktopLocalEnvironmentIds.has(environmentId), - }); - }, [ - environmentLabelById, - desktopLocalEnvironmentIds, - orderedProjects, - projectGroupingSettings, - primaryEnvironmentId, - ]); - - const sidebarProjectByKey = useMemo( - () => new Map(sidebarProjects.map((project) => [project.projectKey, project] as const)), - [sidebarProjects], - ); - const sidebarThreadByKey = useMemo( - () => - new Map( - sidebarThreads.map( - (thread) => - [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const, - ), - ), - [sidebarThreads], - ); - // Resolve the active route's project key to a logical key so it matches the - // sidebar's grouped project entries. - const activeRouteProjectKey = useMemo(() => { - if (!routeThreadKey) { - return null; - } - const activeThread = sidebarThreadByKey.get(routeThreadKey); - if (!activeThread) return null; - const physicalKey = - projectPhysicalKeyByScopedRef.get( - scopedProjectKey(scopeProjectRef(activeThread.environmentId, activeThread.projectId)), - ) ?? scopedProjectKey(scopeProjectRef(activeThread.environmentId, activeThread.projectId)); - return physicalToLogicalKey.get(physicalKey) ?? physicalKey; - }, [routeThreadKey, sidebarThreadByKey, physicalToLogicalKey, projectPhysicalKeyByScopedRef]); - - // Group threads by logical project key so all threads from grouped projects - // are displayed together. - const threadsByProjectKey = useMemo(() => { - const next = new Map(); - for (const thread of sidebarThreads) { - if (isSidebarSubagentThread(thread)) { - continue; - } - const physicalKey = - projectPhysicalKeyByScopedRef.get( - scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), - ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)); - const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey; - const existing = next.get(logicalKey); - if (existing) { - existing.push(thread); - } else { - next.set(logicalKey, [thread]); - } - } - return next; - }, [sidebarThreads, physicalToLogicalKey, projectPhysicalKeyByScopedRef]); - const getCurrentSidebarShortcutContext = useCallback( - () => ({ - terminalFocus: isTerminalFocused(), - terminalOpen: routeTerminalOpen, - modelPickerOpen: isModelPickerOpen(), - }), - [routeTerminalOpen], - ); - const newThreadShortcutLabelOptions = useMemo( - () => ({ - platform, - context: { - terminalFocus: false, - terminalOpen: false, - }, - }), - [platform], - ); - const newThreadShortcutLabel = - shortcutLabelForCommand(keybindings, "chat.newLocal", newThreadShortcutLabelOptions) ?? - shortcutLabelForCommand(keybindings, "chat.new", newThreadShortcutLabelOptions); - - const navigateToThread = useCallback( - (threadRef: ScopedThreadRef) => { - if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) { - clearSelection(); - } - setSelectionAnchor(scopedThreadKey(threadRef)); - if (isMobile) { - setOpenMobile(false); - } - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(threadRef), - }); - }, - [clearSelection, isMobile, navigate, setOpenMobile, setSelectionAnchor], - ); - - const projectDnDSensors = useSensors( - useSensor(PointerSensor, { - activationConstraint: { distance: 6 }, - }), - ); - const projectCollisionDetection = useCallback((args) => { - const pointerCollisions = pointerWithin(args); - if (pointerCollisions.length > 0) { - return pointerCollisions; - } - - return closestCorners(args); - }, []); - - const handleProjectDragEnd = useCallback( - (event: DragEndEvent) => { - if (sidebarProjectSortOrder !== "manual") { - dragInProgressRef.current = false; - return; - } - dragInProgressRef.current = false; - const { active, over } = event; - if (!over || active.id === over.id) return; - const activeProject = sidebarProjects.find((project) => project.projectKey === active.id); - const overProject = sidebarProjects.find((project) => project.projectKey === over.id); - if (!activeProject || !overProject) return; - const activeMemberKeys = activeProject.memberProjects.map( - (member) => member.physicalProjectKey, - ); - const overMemberKeys = overProject.memberProjects.map((member) => member.physicalProjectKey); - reorderProjects(orderedProjects.map(getProjectOrderKey), activeMemberKeys, overMemberKeys); - }, - [orderedProjects, sidebarProjectSortOrder, reorderProjects, sidebarProjects], - ); - - const handleProjectDragStart = useCallback( - (_event: DragStartEvent) => { - if (sidebarProjectSortOrder !== "manual") { - return; - } - dragInProgressRef.current = true; - suppressProjectClickAfterDragRef.current = true; - }, - [sidebarProjectSortOrder], - ); - - const handleProjectDragCancel = useCallback((_event: DragCancelEvent) => { - dragInProgressRef.current = false; - }, []); - - const animatedProjectListsRef = useRef(new WeakSet()); - const attachProjectListAutoAnimateRef = useCallback((node: HTMLElement | null) => { - if (!node || animatedProjectListsRef.current.has(node)) { - return; - } - autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS); - animatedProjectListsRef.current.add(node); - }, []); - - const animatedThreadListsRef = useRef(new WeakSet()); - const attachThreadListAutoAnimateRef = useCallback((node: HTMLElement | null) => { - if (!node || animatedThreadListsRef.current.has(node)) { - return; - } - autoAnimate(node, SIDEBAR_LIST_ANIMATION_OPTIONS); - animatedThreadListsRef.current.add(node); - }, []); - - const visibleThreads = useMemo( - () => - sidebarThreads.filter( - (thread) => thread.archivedAt === null && !isSidebarSubagentThread(thread), - ), - [sidebarThreads], - ); - const sortedProjects = useMemo(() => { - const sortableProjects = sidebarProjects.map((project) => ({ - ...project, - id: project.projectKey, - })); - const sortableThreads = visibleThreads.map((thread) => { - const physicalKey = - projectPhysicalKeyByScopedRef.get( - scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), - ) ?? scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)); - return { - ...thread, - projectId: (physicalToLogicalKey.get(physicalKey) ?? physicalKey) as ProjectId, - }; - }); - return sortProjectsForSidebar( - sortableProjects, - sortableThreads, - sidebarProjectSortOrder, - ).flatMap((project) => { - const resolvedProject = sidebarProjectByKey.get(project.id); - return resolvedProject ? [resolvedProject] : []; - }); - }, [ - sidebarProjectSortOrder, - physicalToLogicalKey, - projectPhysicalKeyByScopedRef, - sidebarProjectByKey, - sidebarProjects, - visibleThreads, - ]); - const isManualProjectSorting = sidebarProjectSortOrder === "manual"; - const visibleSidebarThreadKeys = useMemo( - () => - sortedProjects.flatMap((project) => { - const projectThreads = sortThreads( - (threadsByProjectKey.get(project.projectKey) ?? []).filter( - (thread) => thread.archivedAt === null, - ), - sidebarThreadSortOrder, - ); - const projectExpanded = resolveProjectExpanded( - projectExpandedById, - projectExpansionPreferenceKeys(project), - ); - const activeThreadKey = routeThreadKey ?? undefined; - const pinnedCollapsedThread = - !projectExpanded && activeThreadKey - ? (projectThreads.find( - (thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === - activeThreadKey, - ) ?? null) - : null; - const shouldShowThreadPanel = projectExpanded || pinnedCollapsedThread !== null; - if (!shouldShowThreadPanel) { - return []; - } - const isThreadListExpanded = expandedThreadListsByProject.has(project.projectKey); - const hasOverflowingThreads = projectThreads.length > sidebarThreadPreviewCount; - const previewThreads = - isThreadListExpanded || !hasOverflowingThreads - ? projectThreads - : projectThreads.slice(0, sidebarThreadPreviewCount); - const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : previewThreads; - return renderedThreads.map((thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), - ); - }), - [ - sidebarThreadSortOrder, - sidebarThreadPreviewCount, - expandedThreadListsByProject, - projectExpandedById, - routeThreadKey, - sortedProjects, - threadsByProjectKey, - ], - ); - const threadJumpCommandByKey = useMemo(() => { - const mapping = new Map>>(); - for (const [visibleThreadIndex, threadKey] of visibleSidebarThreadKeys.entries()) { - const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex); - if (!jumpCommand) { - return mapping; - } - mapping.set(threadKey, jumpCommand); - } - - return mapping; - }, [visibleSidebarThreadKeys]); - const threadJumpThreadKeys = useMemo( - () => [...threadJumpCommandByKey.keys()], - [threadJumpCommandByKey], - ); - const sidebarShortcutContext = { - terminalFocus: false, - terminalOpen: routeTerminalOpen, - modelPickerOpen: isModelPickerOpen(), - }; - const threadJumpLabelByKey = useMemo( - () => - buildThreadJumpLabelMap({ - keybindings, - platform, - terminalOpen: sidebarShortcutContext.terminalOpen, - threadJumpCommandByKey, - }), - [keybindings, platform, sidebarShortcutContext.terminalOpen, threadJumpCommandByKey], - ); - const shouldShowThreadJumpHintsNow = shouldShowThreadJumpHintsForModifiers( - shortcutModifiers, - keybindings, - { - platform, - context: sidebarShortcutContext, - }, - ); - const visibleThreadJumpLabelByKey = showThreadJumpHints - ? threadJumpLabelByKey - : EMPTY_THREAD_JUMP_LABELS; - const orderedSidebarThreadKeys = visibleSidebarThreadKeys; - const prewarmedSidebarThreadKeys = useMemo( - () => getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys), - [visibleSidebarThreadKeys], - ); - const prewarmedSidebarThreadRefs = useMemo( - () => - prewarmedSidebarThreadKeys.flatMap((threadKey) => { - const ref = parseScopedThreadKey(threadKey); - return ref ? [ref] : []; - }), - [prewarmedSidebarThreadKeys], - ); - useEffect(() => { const onWindowKeyDown = (event: KeyboardEvent) => { if (event.defaultPrevented || event.repeat) return; diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsx deleted file mode 100644 index d1dd2b30fe..0000000000 --- a/apps/web/src/components/SidebarV2.tsx +++ /dev/null @@ -1,3346 +0,0 @@ -import { autoAnimate } from "@formkit/auto-animate"; -import { useAtomValue } from "@effect/atom-react"; -import { - canSnooze, - effectiveSettled, - effectiveSnoozed, - threadWokeAt, -} from "@t3tools/client-runtime/state/thread-settled"; -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; -import { - scopeProjectRef, - scopeThreadRef, - scopedThreadKey, -} from "@t3tools/client-runtime/environment"; -import type { - ScopedThreadRef, - SidebarProjectGroupingMode, - TimestampFormat, -} from "@t3tools/contracts"; -import { - AlarmClockIcon, - AlarmClockOffIcon, - CheckIcon, - ChevronDownIcon, - CircleAlertIcon, - CircleCheckIcon, - CircleDashedIcon, - ClockIcon, - CopyIcon, - FolderIcon, - FolderPlusIcon, - GitBranchIcon, - EllipsisIcon, - MessageSquareIcon, - PinIcon, - PlusIcon, - SearchIcon, - ServerIcon, - SquarePenIcon, - TerminalIcon, - Trash2Icon, - Undo2Icon, - XIcon, -} from "lucide-react"; -import { - memo, - useCallback, - useEffect, - useMemo, - useRef, - useState, - type KeyboardEvent as ReactKeyboardEvent, - type MouseEvent as ReactMouseEvent, - type ReactNode, -} from "react"; -import { useParams, useRouter } from "@tanstack/react-router"; - -import { - isAtomCommandInterrupted, - settlePromise, - squashAtomCommandFailure, -} from "@t3tools/client-runtime/state/runtime"; -import { isElectron } from "../env"; -import { - resolveShortcutCommand, - shortcutLabelForCommand, - shouldShowThreadJumpHintsForModifiers, - threadJumpCommandForIndex, - threadJumpIndexFromCommand, - threadTraversalDirectionFromCommand, -} from "../keybindings"; -import { useShortcutModifierState } from "../shortcutModifierState"; -import { isTerminalFocused } from "../lib/terminalFocus"; -import { isModelPickerOpen } from "../modelPickerVisibility"; -import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; -import { isMacPlatform } from "~/lib/utils"; -import { useOpenPrLink } from "../lib/openPullRequestLink"; -import { readLocalApi } from "../localApi"; -import { - deriveProjectGroupingOverrideKey, - getProjectOrderKey, - selectProjectGroupingSettings, -} from "../logicalProject"; -import { - buildSidebarProjectSnapshots, - type SidebarProjectGroupMember, - type SidebarProjectSnapshot, -} from "../sidebarProjectGrouping"; -import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; -import { useThreadSelectionStore } from "../threadSelectionStore"; -import { useMarkThreadUnread, useThreadActions } from "../hooks/useThreadActions"; -import { useHandleNewThread } from "../hooks/useHandleNewThread"; -import { openCommandPalette } from "../commandPaletteBus"; -import { startNewThreadFromContext } from "../lib/chatThreadActions"; -import { useClientSettings, useUpdateClientSettings } from "../hooks/useSettings"; -import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; -import { useNowMinute } from "../hooks/useNowMinute"; -import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; -import { useProjects, useThreadShells } from "../state/entities"; -import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server"; -import { vcsEnvironment } from "../state/vcs"; -import { threadEnvironment } from "../state/threads"; -import { projectEnvironment } from "../state/projects"; -import { useEnvironmentQuery } from "../state/query"; -import { useAtomCommand } from "../state/use-atom-command"; -import { - buildThreadRouteParams, - resolveActiveThreadRouteRef, - resolveThreadRouteTarget, -} from "../threadRoutes"; -import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat"; -import type { SidebarThreadSummary } from "../types"; -import { cn } from "~/lib/utils"; -import { - buildBulkTitleRegenerationContextMenuItem, - formatWorkingDurationLabel, - filterSidebarV2VisibleThreads, - firstValidTimestampMs, - hasUnseenCompletion, - isTrailingDoubleClick, - orderItemsByPreferredIds, - resolveAdjacentThreadId, - resolveSettledTimestamp, - resolveSidebarV2Status, - resolveSidebarV2TopStatus, - resolveThreadLastVisitedAt, - resolveWorkingStartedAt, - searchSidebarThreadsByTitle, - shouldShowSidebarV2Duration, - shouldNavigateAfterProjectRemoval, - sortSidebarV2ProjectGroups, - sortSettledThreadsForSidebarV2, - sortThreadsForSidebarV2, -} from "./Sidebar.logic"; -import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic"; -import { - prStatusIndicator, - resolveThreadPr, - settledPrHoverColorClass, - terminalStatusFromRunningIds, - type TerminalStatusIndicator, -} from "./ThreadStatusIndicators"; -import { - resolveSnoozePresets, - snoozeWakeDescription, - snoozeWakeLabel, - type SnoozePreset, -} from "./Sidebar.snooze"; -import { ProjectFavicon } from "./ProjectFavicon"; -import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon"; -import { getTriggerDisplayModelLabel } from "./chat/providerIconUtils"; -import { deriveProviderInstanceEntries, type ProviderInstanceEntry } from "../providerInstances"; -import { primaryServerProvidersAtom } from "../state/server"; -import { useThreadRunningTerminalIds } from "../state/terminalSessions"; -import { stackedThreadToast, toastManager } from "./ui/toast"; -import { Button } from "./ui/button"; -import { - Dialog, - DialogDescription, - DialogFooter, - DialogHeader, - DialogPanel, - DialogPopup, - DialogTitle, -} from "./ui/dialog"; -import { Input } from "./ui/input"; -import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu"; -import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; -import { SidebarContent, SidebarGroup, SidebarMenuButton, useSidebar } from "./ui/sidebar"; -import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; -import { Popover, PopoverPopup, PopoverTrigger } from "./ui/popover"; -import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip"; -import { useComposerDraftStore } from "../composerDraftStore"; - -// Settled-tail paging: recent history is the common lookup; the deep tail -// stays behind an explicit Show more. -const SETTLED_TAIL_INITIAL_COUNT = 10; -const SETTLED_TAIL_PAGE_COUNT = 25; -const PROJECT_GROUPING_MODE_LABELS: Record = { - repository: "Group by repository", - repository_path: "Group by repository path", - separate: "Keep separate", -}; -const SIDEBAR_V2_TOP_STATUS = { - approval: { - label: "Approval", - icon: null, - className: "text-amber-700 dark:text-amber-300", - }, - done: { - label: "Done", - icon: "done", - className: "text-emerald-700 dark:text-emerald-300", - }, - failed: { - label: "Failed", - icon: null, - className: "text-red-700 dark:text-red-300", - }, - input: { - label: "Input", - icon: null, - className: "text-indigo-600 dark:text-indigo-300", - }, - waiting: { - label: "Waiting", - icon: null, - className: "text-muted-foreground", - }, - woke: { - label: "Woke", - icon: "woke", - className: "text-amber-700 dark:text-amber-300", - }, - working: { - label: "Working", - icon: "working", - className: - "animate-sidebar-working-text text-sky-600 motion-reduce:animate-none dark:text-sky-400", - }, -} as const; - -function compactSidebarTimeLabel(label: string): string { - if (label === "just now") return "now"; - return label.endsWith(" ago") ? label.slice(0, -4) : label; -} - -function threadTimeLabel(thread: SidebarThreadSummary): string { - const timestamp = thread.latestUserMessageAt ?? thread.updatedAt; - return compactSidebarTimeLabel(formatRelativeTimeLabel(timestamp)); -} - -// Settled rows read "how long ago did this wrap up", matching their sort -// key: both go through resolveSettledTimestamp so label and order can't -// disagree. -function settledTimeLabel(thread: SidebarThreadSummary): string { - const timestamp = resolveSettledTimestamp(thread); - return timestamp === null ? "" : compactSidebarTimeLabel(formatRelativeTimeLabel(timestamp)); -} - -// Floats at the row's right edge, vertically centered, while the jump -// modifier is held. An overlay pill instead of an inline slot: the hint -// must neither displace the status/time label (holding ⌘ used to blank -// out "Working") nor shift any layout when it appears. pointer-events-none -// so it never swallows clicks meant for the settle/un-settle buttons it -// can overlap. -function JumpHintBadge(props: { label: string }) { - return ( - - {props.label} - - ); -} - -// Self-ticking so only this span re-renders each second, not the whole row. -function WorkingDuration(props: { startedAt: string | null }) { - const startedMs = props.startedAt !== null ? Date.parse(props.startedAt) : Number.NaN; - const [, setTick] = useState(0); - useEffect(() => { - if (Number.isNaN(startedMs)) return; - const id = window.setInterval(() => setTick((tick) => tick + 1), 1_000); - return () => window.clearInterval(id); - }, [startedMs]); - if (Number.isNaN(startedMs)) return null; - return ( - - {formatWorkingDurationLabel(Date.now() - startedMs)} - - ); -} - -function terminalProcessLabel(count: number): string { - return `${count} terminal ${count === 1 ? "process" : "processes"} running`; -} - -function SidebarV2ThreadTooltip({ - thread, - projectTitle, - projectCwd, - environmentLabel, - driverKind, - modelInstanceId, - modelLabel, - branchMismatch, - terminalStatus, - terminalProcessCount, -}: { - thread: SidebarThreadSummary; - projectTitle: string | null; - projectCwd: string | null; - environmentLabel: string | null; - driverKind: ProviderInstanceEntry["driverKind"] | null; - modelInstanceId: string; - modelLabel: string; - branchMismatch: { - threadBranch: string; - currentBranch: string; - } | null; - terminalStatus: TerminalStatusIndicator | null; - terminalProcessCount: number; -}) { - return ( - -
-
- {thread.title} -
-
- {projectTitle ? ( -
- -
{projectTitle}
-
- ) : null} - {environmentLabel ? ( -
- -
{environmentLabel}
-
- ) : null} - {thread.branch ? ( -
- -
{thread.branch}
-
- ) : null} - {branchMismatch ? ( -
- -
- You're currently checked out on another branch. -
-
- ) : null} - {driverKind ? ( -
- -
{modelLabel}
-
- ) : null} - {terminalStatus ? ( -
- -
- {terminalProcessLabel(terminalProcessCount)} -
-
- ) : null} - {thread.runtime?.lastError ? ( -
- -
Error occurred
-
- ) : null} -
-
-
- ); -} - -/** - * Hover entry point for snooze: a clock button opening the preset menu. - * Controlled by the row (which also uses the open state to pin its hover - * actions while the menu is up). - */ -function SnoozePopoverButton(props: { - open: boolean; - onOpenChange: (open: boolean) => void; - onSnooze: (preset: SnoozePreset) => void; - timestampFormat: TimestampFormat; -}) { - const { open, onOpenChange, onSnooze, timestampFormat } = props; - // Presets resolve at open time so "In 1 hour" is relative to the click, - // not to when the row mounted. - const presets = useMemo( - () => (open ? resolveSnoozePresets(new Date(), timestampFormat) : []), - [open, timestampFormat], - ); - return ( - - event.stopPropagation()} - onDoubleClick={(event) => event.stopPropagation()} - className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground" - /> - } - > - - - - {presets.map((preset) => ( - - ))} - - - ); -} - -const SidebarV2Row = memo(function SidebarV2Row(props: { - thread: SidebarThreadSummary; - variant: "card" | "slim"; - // Slim rows are either settled (action: un-settle) or merely quiet - // (seen Ready threads — action: settle). - variantAction: "settle" | "unsettle" | "unsnooze"; - // False on environments whose server predates thread.settle/unsettle: - // the lifecycle affordances hide entirely rather than fail on click. - settlementSupported: boolean; - // Same contract for thread.snooze/unsnooze. - snoozeSupported: boolean; - // Renders the pin glyph. Pinned cards keep the full settle/snooze quick - // actions: settling clears the pin server-side, and snoozing hides the - // card until wake with the pin intact underneath. Pin/unpin themselves - // live in the context menu only. - isPinned: boolean; - // Compact wake countdown ("2h") for rows in the snoozed shelf. - snoozeWakeLabelText: string | null; - // When a snooze ended (timer or early wake); drives the Woke pill until - // the user visits the thread. - wokeAt: string | null; - isActive: boolean; - jumpLabel: string | null; - currentEnvironmentId: string | null; - environmentLabel: string | null; - projectCwd: string | null; - projectTitle: string | null; - providerEntryByInstanceId: ReadonlyMap; - onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void; - onThreadActivate: (threadRef: ScopedThreadRef) => void; - onStartRename: (threadRef: ScopedThreadRef, title: string) => void; - onRenameTitleChange: (title: string) => void; - onCommitRename: (threadRef: ScopedThreadRef, title: string, originalTitle: string) => void; - onCancelRename: () => void; - isRenaming: boolean; - renamingTitle: string; - onContextMenu: (threadRef: ScopedThreadRef, position: { x: number; y: number }) => void; - onSettle: (threadRef: ScopedThreadRef) => void; - onUnsettle: (threadRef: ScopedThreadRef) => void; - onSnooze: (threadRef: ScopedThreadRef, preset: SnoozePreset) => void; - onUnsnooze: (threadRef: ScopedThreadRef) => void; - onChangeRequestState: (threadKey: string, state: "open" | "closed" | "merged" | null) => void; -}) { - const rowTimestampFormat = useClientSettings((s) => s.timestampFormat); - const { - isRenaming, - onChangeRequestState, - onCancelRename, - onCommitRename, - onContextMenu, - onRenameTitleChange, - onSettle, - onSnooze, - onStartRename, - onThreadActivate, - onThreadClick, - onUnsettle, - onUnsnooze, - renamingTitle, - thread, - variant, - variantAction, - } = props; - const threadRef = useMemo( - () => scopeThreadRef(thread.environmentId, thread.id), - [thread.environmentId, thread.id], - ); - const threadKey = scopedThreadKey(threadRef); - const isRegeneratingTitle = thread.titleRegeneration != null; - const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); - const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt); - const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); - const openPrLink = useOpenPrLink(); - const runningTerminalIds = useThreadRunningTerminalIds({ - environmentId: thread.environmentId, - threadId: thread.id, - }); - const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds); - const terminalProcessCount = runningTerminalIds.length; - - // Same semantics as v1 (never-visited counts as read): flipping the beta - // flag must not light up every historical thread as unread. - const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt }); - const status = resolveSidebarV2Status(thread); - // A woken thread reappears at its original position (the sort is - // deliberately static), so the pill has to carry the weight. Snoozing is - // an explicit act, so unlike Done, a never-visited woke thread still - // shows the pill; visiting clears it. An unparseable visit timestamp - // counts as never-visited — corrupt local data must not eat the wake - // signal. - const lastVisitedDate = lastVisitedAt === undefined ? null : parseTimestampDate(lastVisitedAt); - const wokeAtDate = props.wokeAt === null ? null : parseTimestampDate(props.wokeAt); - const isWoke = wokeAtDate !== null && (lastVisitedDate === null || lastVisitedDate < wokeAtDate); - // In-flight rows (working, or waiting on approval/input) fade as a whole: - // there is nothing for the user to do yet, so prominence is reserved for - // rows that need a human — done (unread), read-but-unsettled, failed, and - // freshly woken. The status label keeps its hue, so waiting rows stay - // findable. In-flight rows recede the same as read-ready ones (inbox-zero: - // working threads aren't your problem yet) — only the colored status label - // stands out. - const isInFlight = status === "working" || status === "approval" || status === "input"; - const shouldRecede = - (status === "ready" || isInFlight) && !isUnread && !isWoke && !props.isActive && !isSelected; - // Status hues follow the system-wide convention set by sidebar v1 and the - // mobile Live Activity/widgets (amber approval, indigo input, sky working) - // so a thread reads the same color everywhere it surfaces. - const topStatusKind = resolveSidebarV2TopStatus({ status, isUnread, isWoke }); - const topStatus = topStatusKind === null ? null : SIDEBAR_V2_TOP_STATUS[topStatusKind]; - - const gitCwd = thread.worktreePath ?? props.projectCwd; - const gitStatus = useEnvironmentQuery( - (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null - ? vcsEnvironment.status({ - environmentId: thread.environmentId, - input: { cwd: gitCwd }, - }) - : null, - ); - const branchMismatch = resolveLocalCheckoutBranchMismatch({ - effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree", - activeWorktreePath: thread.worktreePath, - activeThreadBranch: thread.branch, - currentGitBranch: gitStatus.data?.refName ?? null, - }); - const pr = resolveThreadPr({ - threadBranch: thread.branch, - gitStatus: gitStatus.data, - }); - const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider); - const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined; - // Report the PR state up: the parent partitions rows with effectiveSettled, - // and a merged/closed PR auto-settles a thread — data only rows have. - const prState = pr?.state ?? null; - useEffect(() => { - onChangeRequestState(threadKey, prState); - }, [onChangeRequestState, prState, threadKey]); - - const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; - const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; - const driverKind = providerEntry?.driverKind ?? null; - const selectedModel = providerEntry?.models.find( - (model) => model.slug === thread.modelSelection.model, - ); - const modelLabel = selectedModel - ? getTriggerDisplayModelLabel(selectedModel) - : thread.modelSelection.model; - - const isRemote = - props.currentEnvironmentId !== null && thread.environmentId !== props.currentEnvironmentId; - - const detailsTooltip = ( - - ); - - const handleClick = useCallback( - (event: ReactMouseEvent) => { - onThreadClick(event, threadRef); - }, - [onThreadClick, threadRef], - ); - const handleContextMenu = useCallback( - (event: ReactMouseEvent) => { - event.preventDefault(); - onContextMenu(threadRef, { x: event.clientX, y: event.clientY }); - }, - [onContextMenu, threadRef], - ); - const handleKeyDown = useCallback( - (event: ReactKeyboardEvent) => { - if (event.target !== event.currentTarget) return; - if (event.key !== "Enter" && event.key !== " ") return; - event.preventDefault(); - onThreadActivate(threadRef); - }, - [onThreadActivate, threadRef], - ); - const handleDoubleClick = useCallback( - (event: ReactMouseEvent) => { - if (isRenaming || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { - return; - } - if ((event.target as HTMLElement).closest("button, a, input")) return; - event.preventDefault(); - onStartRename(threadRef, thread.title); - }, - [isRenaming, onStartRename, thread.title, threadRef], - ); - const renameCommittedRef = useRef(false); - useEffect(() => { - if (isRenaming) renameCommittedRef.current = false; - }, [isRenaming]); - const handleRenameKeyDown = useCallback( - (event: ReactKeyboardEvent) => { - event.stopPropagation(); - if (event.key === "Enter") { - event.preventDefault(); - renameCommittedRef.current = true; - onCommitRename(threadRef, renamingTitle, thread.title); - } else if (event.key === "Escape") { - event.preventDefault(); - renameCommittedRef.current = true; - onCancelRename(); - } - }, - [onCancelRename, onCommitRename, renamingTitle, thread.title, threadRef], - ); - const handleRenameBlur = useCallback(() => { - if (!renameCommittedRef.current) { - onCommitRename(threadRef, renamingTitle, thread.title); - } - }, [onCommitRename, renamingTitle, thread.title, threadRef]); - const handleSettleClick = useCallback( - (event: ReactMouseEvent) => { - event.preventDefault(); - event.stopPropagation(); - onSettle(threadRef); - }, - [onSettle, threadRef], - ); - const handleUnsettleClick = useCallback( - (event: ReactMouseEvent) => { - event.preventDefault(); - event.stopPropagation(); - onUnsettle(threadRef); - }, - [onUnsettle, threadRef], - ); - const handleUnsnoozeClick = useCallback( - (event: ReactMouseEvent) => { - event.preventDefault(); - event.stopPropagation(); - onUnsnooze(threadRef); - }, - [onUnsnooze, threadRef], - ); - const handleSnoozePreset = useCallback( - (preset: SnoozePreset) => { - onSnooze(threadRef, preset); - }, - [onSnooze, threadRef], - ); - // While the snooze popover is open the pointer leaves the row, which - // would fade the hover actions out from under the open menu; pin them. - const [snoozeMenuOpenRaw, setSnoozeMenuOpen] = useState(false); - // Snooze is offered only where it can succeed: capability-gated and never - // on blocked-on-you work or queued turns (the server rejects both). - const showSnoozeButton = - props.snoozeSupported && canSnooze(thread, { now: new Date().toISOString() }); - // If the thread becomes blocked while the popover is open, the button - // unmounts without firing onOpenChange(false). Deriving the flag keeps a - // stale true from permanently hiding the status label / pinning the - // hover actions, and the effect clears the raw state so the popover - // doesn't resurrect if the button later remounts. - const snoozeMenuOpen = snoozeMenuOpenRaw && showSnoozeButton; - useEffect(() => { - if (!showSnoozeButton) setSnoozeMenuOpen(false); - }, [showSnoozeButton]); - const handlePrClick = useCallback( - (event: ReactMouseEvent) => { - if (pr?.url) openPrLink(event, pr.url); - }, - [openPrLink, pr], - ); - - // All Sidebar V2 rows share one surface model. Live threads used to look - // like elevated cards while settled threads were plain rows, leaving neither - // a useful hierarchy nor a reliable hover cue. Status now lives in the row - // content; surface is reserved for interaction (hover, multi-select, route). - const rowSurfaceClassName = cn( - "group/v2-row relative w-full cursor-pointer overflow-hidden rounded-md text-left outline-none select-none", - props.isActive - ? "bg-sidebar-row-active text-sidebar-foreground" - : isSelected - ? "bg-sidebar-row-selected text-sidebar-foreground" - : shouldRecede - ? "text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground" - : "bg-transparent text-sidebar-foreground hover:bg-sidebar-row-hover", - isInFlight && - !props.isActive && - !isSelected && - "opacity-70 transition-opacity hover:opacity-100", - ); - - const title = isRenaming ? ( - onRenameTitleChange(event.target.value)} - onFocus={(event) => event.currentTarget.select()} - onKeyDown={handleRenameKeyDown} - onBlur={handleRenameBlur} - onClick={(event) => event.stopPropagation()} - onDoubleClick={(event) => event.stopPropagation()} - className="min-w-0 flex-1 rounded-sm border border-input bg-card px-1 text-sm font-medium text-card-foreground outline-none focus:border-foreground" - /> - ) : ( - - {thread.title} - - ); - - const prBadge = - prStatus && pr ? ( - - ) : null; - const terminalStatusIcon = terminalStatus ? ( - - - - ) : null; - - if (variant === "slim") { - return ( -
  • - - - } - > - {/* Settled history recedes: dimmed favicon at rest, restored on - hover so the tail stays scannable when you're hunting. */} - - - - {title} - {terminalStatusIcon} - {isRegeneratingTitle ? ( - - Regenerating title - - ) : null} - {/* The PR badge stays outside the hover-fading slot: it must - remain visible AND clickable while the row is hovered. Only - the time/jump label yields to the settle affordance. */} - {prBadge} - - - {variantAction === "unsnooze" && props.snoozeWakeLabelText !== null ? ( - // Snoozed rows show when they come BACK, not when they were - // last touched — the return ticket is the row's whole story. - - {props.snoozeWakeLabelText} - - ) : isWoke ? ( - // A wake can land straight in the settled tail (e.g. PR - // merged while snoozed); the signal must survive the trip. - - - Woke - - ) : ( - - {variantAction === "unsettle" - ? settledTimeLabel(thread) - : threadTimeLabel(thread)} - - )} - - {variantAction === "unsnooze" ? ( - !props.snoozeSupported ? null : ( - - ) - ) : !props.settlementSupported ? null : variantAction === "unsettle" ? ( - - ) : ( - - )} - - {props.jumpLabel ? : null} - - {detailsTooltip} - -
  • - ); - } - - const diff = latestTurnDiff(thread); - - return ( -
  • - - - } - > -
    -
    - - {props.projectTitle ? ( - - {props.projectTitle} - - ) : ( - - )} - {props.isPinned ? ( - - ) : null} - {/* The visible state owns this slot's width: status at rest, - actions on hover/keyboard focus or while the popover is open. Keeping - the hidden state out of flow lets the project label reclaim - space without either state overlapping it. */} - - {/* pointer-events-none: while hovered this label is absolute - + opacity-0, which paints it ABOVE the in-flow settle/snooze - buttons; without it the invisible label eats their clicks. */} - - {topStatus ? ( - - {topStatus.icon === "working" ? ( - - ) : topStatus.icon === "done" ? ( - - ) : topStatus.icon === "woke" ? ( - - ) : null} - {/* The label alone is the live region: a role="status" - wrapper around the ticking duration would make - screen readers announce every second. */} - {topStatus.label} - {shouldShowSidebarV2Duration(status) ? ( - - - - ) : null} - - ) : ( - threadTimeLabel(thread) - )} - - {props.settlementSupported || showSnoozeButton ? ( - - {showSnoozeButton ? ( - - ) : null} - {props.settlementSupported ? ( - - ) : null} - - ) : null} - -
    -
    - {title} - {isRegeneratingTitle ? ( - - Regenerating title - - ) : null} -
    -
    - {thread.branch ? ( - {thread.branch} - ) : ( - - )} - {terminalStatusIcon} - {prBadge} - {diff ? ( - - +{diff.insertions}{" "} - −{diff.deletions} - - ) : null} - - {isRemote ? ( - - - - ) : null} - {driverKind ? ( - - - - ) : null} - -
    -
    - {props.jumpLabel ? : null} -
    - {detailsTooltip} -
    -
  • - ); -}); - -function latestTurnDiff( - thread: SidebarThreadSummary, -): { insertions: number; deletions: number } | null { - // Shells don't carry checkpoint summaries; diff stats render only when the - // shell projection grows them. Kept as a seam so the row layout is ready. - void thread; - return null; -} - -const SidebarV2SearchResultRow = memo(function SidebarV2SearchResultRow(props: { - thread: SidebarThreadSummary; - projectCwd: string | null; - projectTitle: string | null; - environmentLabel: string | null; - providerEntryByInstanceId: ReadonlyMap; - isHighlighted: boolean; - isRouteActive: boolean; - resultId: string; - onHighlight: () => void; - onSelect: () => void; -}) { - const { thread } = props; - // Same details tooltip as the regular rows: a search hit is still a thread, - // and the hover card is how you disambiguate identically-titled results. - const gitCwd = thread.worktreePath ?? props.projectCwd; - const gitStatus = useEnvironmentQuery( - (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null - ? vcsEnvironment.status({ - environmentId: thread.environmentId, - input: { cwd: gitCwd }, - }) - : null, - ); - const branchMismatch = resolveLocalCheckoutBranchMismatch({ - effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree", - activeWorktreePath: thread.worktreePath, - activeThreadBranch: thread.branch, - currentGitBranch: gitStatus.data?.refName ?? null, - }); - const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; - const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; - const driverKind = providerEntry?.driverKind ?? null; - const selectedModel = providerEntry?.models.find( - (model) => model.slug === thread.modelSelection.model, - ); - const modelLabel = selectedModel - ? getTriggerDisplayModelLabel(selectedModel) - : thread.modelSelection.model; - const runningTerminalIds = useThreadRunningTerminalIds({ - environmentId: thread.environmentId, - threadId: thread.id, - }); - const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds); - return ( -
  • - - - } - > - - {thread.title} - - {threadTimeLabel(thread)} - - - - -
  • - ); -}); - -export default function SidebarV2() { - const projects = useProjects(); - const projectOrder = useUiStateStore((store) => store.projectOrder); - const threads = useThreadShells(); - const router = useRouter(); - const { isMobile, setOpenMobile } = useSidebar(); - const keybindings = useAtomValue(primaryServerKeybindingsAtom); - const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays); - const timestampFormat = useClientSettings((s) => s.timestampFormat); - const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete); - const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder); - const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); - const { - settleThread, - unsettleThread, - snoozeThread, - unsnoozeThread, - pinThread, - unpinThread, - deleteThread, - } = useThreadActions(); - const markThreadUnread = useMarkThreadUnread(); - const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { - reportFailure: false, - }); - const deleteProject = useAtomCommand(projectEnvironment.delete, { - reportFailure: false, - }); - const updateProject = useAtomCommand(projectEnvironment.update, { - reportFailure: false, - }); - const updateSettings = useUpdateClientSettings(); - const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({ - onCopy: ({ path }) => { - toastManager.add({ - type: "success", - title: "Path copied", - description: path, - }); - }, - onError: (error) => { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to copy path", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - }, - }); - const { copyToClipboard: copyBranchToClipboard } = useCopyToClipboard<{ branch: string }>({ - target: "branch name", - onCopy: ({ branch }) => { - toastManager.add({ - type: "success", - title: "Branch copied", - description: branch, - }); - }, - onError: (error) => { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to copy branch", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - }, - }); - const [projectActionsTarget, setProjectActionsTarget] = useState( - null, - ); - const [projectScopeMenuOpen, setProjectScopeMenuOpen] = useState(false); - const newThreadContext = useHandleNewThread(); - const openAddProjectCommandPalette = useCallback( - () => openCommandPalette({ open: "add-project" }), - [], - ); - const { environments } = useEnvironments(); - const primaryEnvironmentId = usePrimaryEnvironmentId(); - const clearSelection = useThreadSelectionStore((s) => s.clearSelection); - const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); - const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread); - const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo); - const routeTarget = useParams({ - strict: false, - select: (params) => resolveThreadRouteTarget(params), - }); - const routeDraftThread = useComposerDraftStore((store) => - routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null, - ); - const routeThreadRef = useMemo( - () => resolveActiveThreadRouteRef(routeTarget, routeDraftThread), - [routeDraftThread, routeTarget], - ); - const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; - const routeTargetRef = useRef(routeTarget); - routeTargetRef.current = routeTarget; - // Post-settle navigation validates against the CURRENT route, not the one - // captured when the settle started: if the user navigated elsewhere while - // the command was in flight, completing it must not yank them away. - const routeThreadKeyRef = useRef(routeThreadKey); - routeThreadKeyRef.current = routeThreadKey; - - const environmentLabelById = useMemo( - () => - new Map( - environments.map((environment) => [environment.environmentId, environment.label] as const), - ), - [environments], - ); - const orderedProjects = useMemo( - () => - orderItemsByPreferredIds({ - items: projects, - preferredIds: projectOrder, - getId: getProjectOrderKey, - getPreferenceIds: (project) => [ - getProjectOrderKey(project), - legacyProjectCwdPreferenceKey(project.workspaceRoot), - ], - }), - [projectOrder, projects], - ); - const unsortedProjectGroups = useMemo( - () => - buildSidebarProjectSnapshots({ - projects: sidebarProjectSortOrder === "manual" ? orderedProjects : projects, - settings: projectGroupingSettings, - primaryEnvironmentId, - resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null, - }), - [ - environmentLabelById, - orderedProjects, - primaryEnvironmentId, - projectGroupingSettings, - projects, - sidebarProjectSortOrder, - ], - ); - const projectGroups = useMemo( - () => sortSidebarV2ProjectGroups(unsortedProjectGroups, threads, sidebarProjectSortOrder), - [sidebarProjectSortOrder, threads, unsortedProjectGroups], - ); - const serverProviders = useAtomValue(primaryServerProvidersAtom); - const providerEntryByInstanceId = useMemo( - () => - new Map( - deriveProviderInstanceEntries(serverProviders).map( - (entry) => [entry.instanceId as string, entry] as const, - ), - ), - [serverProviders], - ); - const projectCwdByKey = useMemo( - () => - new Map( - projects.map((project) => [ - `${project.environmentId}:${project.id}`, - project.workspaceRoot, - ]), - ), - [projects], - ); - const projectDisplayNameByKey = useMemo( - () => - new Map( - projectGroups.flatMap((group) => - group.memberProjects.map( - (project) => [`${project.environmentId}:${project.id}`, group.displayName] as const, - ), - ), - ), - [projectGroups], - ); - - // now is quantized to the minute so effectiveSettled memoization doesn't - // churn on every render; auto-settle thresholds are day-granular anyway. - const nowMinute = useNowMinute(); - // Snooze wake times are second-precise, so classifying with the quantized - // minute would hold a woken thread on the shelf for up to a minute. The - // tick is a plain counter bumped exactly at the next wake boundary (armed - // below, after the partition knows the boundary); the partition reads a - // fresh clock whenever it recomputes. - const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0); - - // PR states stream in per-row (rows own the VCS subscriptions); a merged or - // closed PR auto-settles its thread on the next partition. - const [changeRequestStateByKey, setChangeRequestStateByKey] = useState< - ReadonlyMap - >(() => new Map()); - const handleChangeRequestState = useCallback( - (threadKey: string, state: "open" | "closed" | "merged" | null) => { - setChangeRequestStateByKey((current) => { - if ((current.get(threadKey) ?? null) === state) return current; - const next = new Map(current); - if (state === null) { - next.delete(threadKey); - } else { - next.set(threadKey, state); - } - return next; - }); - }, - [], - ); - - // Project scope: one menu above the list. Scoping filters the list without - // making the header width depend on the number or length of project names. - const [projectScopeKey, setProjectScopeKey] = useState(null); - const scopedProjectGroup = useMemo( - () => - projectScopeKey === null - ? null - : (projectGroups.find((project) => project.projectKey === projectScopeKey) ?? null), - [projectGroups, projectScopeKey], - ); - const scopedProjectKeys = useMemo( - () => - scopedProjectGroup === null - ? null - : new Set( - scopedProjectGroup.memberProjectRefs.map( - (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`, - ), - ), - [scopedProjectGroup], - ); - useEffect(() => { - if (projectScopeKey !== null && scopedProjectGroup === null) { - setProjectScopeKey(null); - } - }, [projectScopeKey, scopedProjectGroup]); - // Scope flips drop the selection: rows selected under the old scope may be - // hidden now, and bulk actions must never count or touch invisible rows. - useEffect(() => { - clearSelection(); - }, [clearSelection, projectScopeKey]); - - const handleRemoveProjectMembers = useCallback( - async (projectGroup: SidebarProjectSnapshot, members: readonly SidebarProjectGroupMember[]) => { - const api = readLocalApi(); - if (!api) return; - - const memberKeys = new Set(members.map((member) => `${member.environmentId}:${member.id}`)); - const projectThreads = threads.filter((thread) => - memberKeys.has(`${thread.environmentId}:${thread.projectId}`), - ); - const isWholeGroup = members.length === projectGroup.memberProjects.length; - const singleMember = members.length === 1 ? members[0]! : null; - const targetLabel = singleMember?.title ?? projectGroup.displayName; - const confirmed = await settlePromise(() => - api.dialogs.confirm( - projectThreads.length > 0 - ? [ - `Remove project "${targetLabel}" and delete its ${projectThreads.length} thread${projectThreads.length === 1 ? "" : "s"}?`, - ...(singleMember - ? [ - `Path: ${singleMember.workspaceRoot}`, - ...(singleMember.environmentLabel - ? [`Environment: ${singleMember.environmentLabel}`] - : []), - ] - : [`This removes ${members.length} grouped project entries.`]), - "This permanently clears conversation history for those threads.", - isWholeGroup - ? "This removes only the project entries, not the files on disk." - : "Other entries in this grouped project are unaffected.", - "This action cannot be undone.", - ].join("\n") - : [ - `Remove project "${targetLabel}"?`, - ...(singleMember - ? [ - `Path: ${singleMember.workspaceRoot}`, - ...(singleMember.environmentLabel - ? [`Environment: ${singleMember.environmentLabel}`] - : []), - ] - : [`This removes ${members.length} grouped project entries.`]), - isWholeGroup - ? "This removes only the project entries, not the files on disk." - : "Other entries in this grouped project are unaffected.", - ].join("\n"), - ), - ); - if (confirmed._tag === "Failure" || !confirmed.value) return; - - const draftStore = useComposerDraftStore.getState(); - let shouldNavigate = false; - for (const project of members) { - const memberThreads = projectThreads.filter( - (thread) => - thread.environmentId === project.environmentId && thread.projectId === project.id, - ); - const projectRef = scopeProjectRef(project.environmentId, project.id); - const projectDraftThread = draftStore.getDraftThreadByProjectRef(projectRef); - const memberRemovalNeedsNavigation = shouldNavigateAfterProjectRemoval({ - routeTarget: routeTargetRef.current, - projectThreads: memberThreads, - projectDraftId: projectDraftThread?.draftId ?? null, - }); - - const result = await deleteProject({ - environmentId: project.environmentId, - input: { - projectId: project.id, - ...(memberThreads.length > 0 ? { force: true } : {}), - }, - }); - if (result._tag === "Failure") { - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: `Failed to remove "${project.title}"`, - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - if (shouldNavigate) { - void router.navigate({ to: "/" }); - } - return; - } - - shouldNavigate ||= memberRemovalNeedsNavigation; - if (projectDraftThread) { - draftStore.clearDraftThread(projectDraftThread.draftId); - } - draftStore.clearProjectDraftThreadId(projectRef); - } - - if (shouldNavigate) { - void router.navigate({ to: "/" }); - } - }, - [deleteProject, router, threads], - ); - - const renameProjectMember = useCallback( - async (member: SidebarProjectGroupMember, nextTitle: string) => { - const title = nextTitle.trim(); - if (!title) { - toastManager.add({ type: "warning", title: "Project title cannot be empty" }); - return; - } - if (title === member.title) return; - const result = await updateProject({ - environmentId: member.environmentId, - input: { projectId: member.id, title }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to rename project", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - }, - [updateProject], - ); - - const updateProjectGroupingPreference = useCallback( - (member: SidebarProjectGroupMember, selection: SidebarProjectGroupingMode | "inherit") => { - const overrideKey = deriveProjectGroupingOverrideKey(member); - const nextOverrides = { ...projectGroupingSettings.sidebarProjectGroupingOverrides }; - if (selection === "inherit") { - delete nextOverrides[overrideKey]; - } else { - nextOverrides[overrideKey] = selection; - } - updateSettings({ sidebarProjectGroupingOverrides: nextOverrides }); - }, - [projectGroupingSettings.sidebarProjectGroupingOverrides, updateSettings], - ); - - const handleProjectActions = useCallback( - (event: ReactMouseEvent, projectGroup: SidebarProjectSnapshot) => { - event.preventDefault(); - event.stopPropagation(); - setProjectScopeMenuOpen(false); - window.requestAnimationFrame(() => setProjectActionsTarget(projectGroup)); - }, - [], - ); - - // Settled threads stay in the live shell stream (settled ≠ archived), so - // the partition works directly off live shells: no archived-snapshot - // merging, no optimistic holds. Archived threads remain hidden here — - // archive keeps its original "remove from sidebar" meaning. - const serverConfigs = useAtomValue(environmentServerConfigsAtom); - const { pinnedThreads, activeThreads, snoozedThreads, settledThreads, snoozeNow } = - useMemo(() => { - const now = `${nowMinute}:00.000Z`; - // Snooze classification uses a REAL clock, not the quantized minute: - // wake times are second-precise and a woken thread must not linger on - // the shelf for the rest of the minute. snoozeWakeTick re-runs this - // memo exactly at the next wake boundary. - void snoozeWakeTick; - const preciseNow = new Date().toISOString(); - const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys); - const pinned: EnvironmentThreadShell[] = []; - const active: EnvironmentThreadShell[] = []; - const snoozed: EnvironmentThreadShell[] = []; - const settled: EnvironmentThreadShell[] = []; - for (const thread of visible) { - // Threads on servers without the settlement capability (old server, - // or descriptor not loaded yet) never classify as settled: the user - // could neither un-settle nor pin them, so auto-settling them would - // strand rows in a tail with no working affordances. - const supportsSettlement = - serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === - true; - const supportsSnooze = - serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true; - const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); - const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null; - // Snooze outranks everything, including a pin: "hide until Tuesday" - // temporarily suspends "keep on top". The pin survives underneath — - // pinned cards are creation-ordered, so on wake the thread reappears - // at its original spot in the pinned block. (For unpinned threads - // this is also the snooze-beats-auto-settle rule: the wake time is a - // stronger statement about when the thread matters again.) - if (supportsSnooze && effectiveSnoozed(thread, { now: preciseNow })) { - snoozed.push(thread); - // A pin otherwise overrides the lifecycle: pinned threads never - // auto-settle out of sight. (The decider clears settled state on - // pin and the pin on settle, so pin-vs-settled conflicts only - // arise from stale or raced writes.) - } else if (thread.pinnedAt != null) { - pinned.push(thread); - } else if ( - supportsSettlement && - effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState }) - ) { - settled.push(thread); - } else { - active.push(thread); - } - } - return { - // Same static creation order as the inbox: a pin freezes prominence, - // it does not introduce a new ordering scheme. - pinnedThreads: sortThreadsForSidebarV2(pinned), - activeThreads: sortThreadsForSidebarV2(active), - // Soonest wake first: "what comes back next" is the shelf's question. - snoozedThreads: snoozed.toSorted( - (left, right) => - firstValidTimestampMs(left.snoozedUntil ?? null) - - firstValidTimestampMs(right.snoozedUntil ?? null), - ), - settledThreads: sortSettledThreadsForSidebarV2(settled), - snoozeNow: preciseNow, - }; - }, [ - autoSettleAfterDays, - changeRequestStateByKey, - nowMinute, - scopedProjectKeys, - serverConfigs, - snoozeWakeTick, - threads, - ]); - - const threadSearchInputRef = useRef(null); - const [threadSearchQuery, setThreadSearchQuery] = useState(""); - const [activeSearchResultIndex, setActiveSearchResultIndex] = useState(0); - const isSearchingThreads = threadSearchQuery.trim().length > 0; - const searchableThreads = useMemo( - () => [...pinnedThreads, ...activeThreads, ...snoozedThreads, ...settledThreads], - [activeThreads, pinnedThreads, settledThreads, snoozedThreads], - ); - const threadSearchResults = useMemo( - () => searchSidebarThreadsByTitle(searchableThreads, threadSearchQuery), - [searchableThreads, threadSearchQuery], - ); - const threadSearchResultOrderKey = threadSearchResults - .map((thread) => scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))) - .join("\0"); - - useEffect(() => { - setActiveSearchResultIndex(0); - }, [threadSearchResultOrderKey]); - - useEffect(() => { - if (!isSearchingThreads) return; - document - .getElementById(`sidebar-thread-search-result-${activeSearchResultIndex}`) - ?.scrollIntoView({ block: "nearest" }); - }, [activeSearchResultIndex, isSearchingThreads, threadSearchResultOrderKey]); - - // Arm a timeout for the earliest upcoming wake so the shelf empties the - // moment a snooze expires instead of on the next minute tick. Sorted - // soonest-first, so entry 0 is the boundary. - useEffect(() => { - const nextWakeAtMs = - snoozedThreads.length > 0 && snoozedThreads[0]?.snoozedUntil != null - ? Date.parse(snoozedThreads[0].snoozedUntil) - : Number.NaN; - if (Number.isNaN(nextWakeAtMs)) return; - // setTimeout delays are signed 32-bit: anything larger overflows and - // fires immediately, turning a far-future wake (event-condition snoozes - // synced from elsewhere) into a tight re-arm loop. Clamped, the timer - // just re-arms every ~24.8 days until the wake is in range. - const delayMs = Math.min(Math.max(0, nextWakeAtMs - Date.now()) + 50, 2_147_483_647); - const id = window.setTimeout(() => bumpSnoozeWakeTick((tick) => tick + 1), delayMs); - return () => window.clearTimeout(id); - }, [snoozedThreads]); - - // The settled tail renders in pages: history shouldn't dominate the - // sidebar, and the common lookups are recent. Expansion resets when the - // filter context changes so a scope/search flip never inherits a deep - // page state. - const [settledVisibleCount, setSettledVisibleCount] = useState(SETTLED_TAIL_INITIAL_COUNT); - const settledResetKey = projectScopeKey ?? "all"; - const lastSettledResetKeyRef = useRef(settledResetKey); - if (lastSettledResetKeyRef.current !== settledResetKey) { - lastSettledResetKeyRef.current = settledResetKey; - setSettledVisibleCount(SETTLED_TAIL_INITIAL_COUNT); - } - const visibleSettledThreads = useMemo(() => { - if (settledThreads.length <= settledVisibleCount) return settledThreads; - const visible = settledThreads.slice(0, settledVisibleCount); - // The open thread must never hide under "Show more": navigating into a - // deep settled thread (search, deep link) pulls its row into the visible - // tail so the highlight and the un-settle affordance stay reachable. - if (routeThreadKey !== null) { - const routeThread = settledThreads - .slice(settledVisibleCount) - .find( - (thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey, - ); - if (routeThread !== undefined) visible.push(routeThread); - } - return visible; - }, [routeThreadKey, settledThreads, settledVisibleCount]); - const hiddenSettledCount = settledThreads.length - visibleSettledThreads.length; - const showMoreSettled = useCallback( - () => setSettledVisibleCount((count) => count + SETTLED_TAIL_PAGE_COUNT), - [], - ); - const [settledShelfExpanded, setSettledShelfExpanded] = useState(true); - const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []); - const renderedSettledThreads = useMemo(() => { - if (settledShelfExpanded) return visibleSettledThreads; - if (routeThreadKey === null) return []; - const routeThread = visibleSettledThreads.find( - (thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey, - ); - return routeThread === undefined ? [] : [routeThread]; - }, [routeThreadKey, settledShelfExpanded, visibleSettledThreads]); - - // The snoozed shelf is collapsed by default: out of the way, never gone. - // Collapsed threads don't render (and so don't participate in jump - // shortcuts or multi-select), matching the settled tail's paging model. - const [snoozedShelfExpanded, setSnoozedShelfExpanded] = useState(false); - const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []); - const visibleSnoozedThreads = useMemo(() => { - if (snoozedShelfExpanded) return snoozedThreads; - // The open thread must never vanish behind the collapsed shelf: a - // snoozed thread reached by route (deep link, open before snoozing - // elsewhere) keeps its row — with highlight and wake affordance — same - // exception the settled tail's "Show more" makes. - if (routeThreadKey === null) return []; - const routeThread = snoozedThreads.find( - (thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey, - ); - return routeThread === undefined ? [] : [routeThread]; - }, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]); - - const orderedThreads = useMemo( - () => [...pinnedThreads, ...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads], - [pinnedThreads, activeThreads, visibleSnoozedThreads, renderedSettledThreads], - ); - const orderedThreadKeys = useMemo( - () => - orderedThreads.map((thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), - ), - [orderedThreads], - ); - // Rows call back into the click handler without carrying the ordered list as - // a prop — a fresh array identity per shell update would defeat every row's - // memoization. The ref keeps shift-range-select working against the list as - // rendered at click time. - const orderedThreadKeysRef = useRef(orderedThreadKeys); - orderedThreadKeysRef.current = orderedThreadKeys; - const threadByKey = useMemo( - () => - new Map( - orderedThreads.map( - (thread) => - [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const, - ), - ), - [orderedThreads], - ); - // Handlers read these through refs: depending on per-update Map/Set - // identities would give every row a fresh callback prop on each shell - // event and defeat row memoization during streaming. - const threadByKeyRef = useRef(threadByKey); - threadByKeyRef.current = threadByKey; - // handleNewThread is inherently unstable (depends on the projects list); - // a ref keeps it out of attemptSettle's dependency array. - const handleNewThreadRef = useRef(newThreadContext.handleNewThread); - handleNewThreadRef.current = newThreadContext.handleNewThread; - const settledThreadKeys = useMemo( - () => - new Set( - settledThreads.map((thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), - ), - ), - [settledThreads], - ); - const settledThreadKeysRef = useRef(settledThreadKeys); - settledThreadKeysRef.current = settledThreadKeys; - const snoozedThreadKeys = useMemo( - () => - new Set( - snoozedThreads.map((thread) => - scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), - ), - ), - [snoozedThreads], - ); - const snoozedThreadKeysRef = useRef(snoozedThreadKeys); - snoozedThreadKeysRef.current = snoozedThreadKeys; - - const jumpLabelByKey = useMemo(() => { - const mapping = new Map(); - for (const [index, threadKey] of orderedThreadKeys.entries()) { - const jumpCommand = threadJumpCommandForIndex(index); - if (!jumpCommand) break; - const label = shortcutLabelForCommand(keybindings, jumpCommand); - if (label) mapping.set(threadKey, label); - } - return mapping; - }, [keybindings, orderedThreadKeys]); - const [showJumpHints, setShowJumpHints] = useState(false); - - // Settled threads are live shells, so opening one is plain navigation: - // history stays readable without un-settling, and sending a message or - // starting a session un-settles server-side. - const navigateToThread = useCallback( - (threadRef: ScopedThreadRef) => { - if (useThreadSelectionStore.getState().selectedThreadKeys.size > 0) { - clearSelection(); - } - setSelectionAnchor(scopedThreadKey(threadRef)); - if (isMobile) { - setOpenMobile(false); - } - void router.navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(threadRef), - }); - }, - [clearSelection, isMobile, router, setOpenMobile, setSelectionAnchor], - ); - - const clearThreadSearch = useCallback(() => { - setThreadSearchQuery(""); - setActiveSearchResultIndex(0); - }, []); - const selectThreadSearchResult = useCallback( - (thread: EnvironmentThreadShell) => { - clearThreadSearch(); - navigateToThread(scopeThreadRef(thread.environmentId, thread.id)); - }, - [clearThreadSearch, navigateToThread], - ); - const handleThreadSearchKeyDown = useCallback( - (event: ReactKeyboardEvent) => { - // IME composition (Japanese/Chinese input) uses the same keys; committing - // a candidate must not move the highlight or navigate away mid-compose. - if (event.nativeEvent.isComposing || event.keyCode === 229) return; - if (event.key === "Escape" && isSearchingThreads) { - event.preventDefault(); - event.stopPropagation(); - clearThreadSearch(); - return; - } - if (threadSearchResults.length === 0) return; - if (event.key === "ArrowDown") { - event.preventDefault(); - setActiveSearchResultIndex((index) => (index + 1) % threadSearchResults.length); - return; - } - if (event.key === "ArrowUp") { - event.preventDefault(); - setActiveSearchResultIndex( - (index) => (index - 1 + threadSearchResults.length) % threadSearchResults.length, - ); - return; - } - if (event.key === "Enter") { - event.preventDefault(); - const result = threadSearchResults[activeSearchResultIndex]; - if (result) selectThreadSearchResult(result); - } - }, - [ - activeSearchResultIndex, - clearThreadSearch, - isSearchingThreads, - selectThreadSearchResult, - threadSearchResults, - ], - ); - - const [renamingThreadKey, setRenamingThreadKey] = useState(null); - const [renamingTitle, setRenamingTitle] = useState(""); - const startThreadRename = useCallback((threadRef: ScopedThreadRef, title: string) => { - setRenamingThreadKey(scopedThreadKey(threadRef)); - setRenamingTitle(title); - }, []); - const cancelThreadRename = useCallback(() => setRenamingThreadKey(null), []); - const commitThreadRename = useCallback( - (threadRef: ScopedThreadRef, title: string, originalTitle: string) => { - void (async () => { - const trimmed = title.trim(); - setRenamingThreadKey(null); - if (trimmed.length === 0) { - toastManager.add({ type: "warning", title: "Thread title cannot be empty" }); - return; - } - if (trimmed === originalTitle) return; - const result = await updateThreadMetadata({ - environmentId: threadRef.environmentId, - input: { threadId: threadRef.threadId, title: trimmed }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to rename thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - })(); - }, - [updateThreadMetadata], - ); - - const handleThreadClick = useCallback( - (event: ReactMouseEvent, threadRef: ScopedThreadRef) => { - const isMac = isMacPlatform(navigator.platform); - const isModClick = isMac ? event.metaKey : event.ctrlKey; - const threadKey = scopedThreadKey(threadRef); - if (isModClick) { - event.preventDefault(); - toggleThreadSelection(threadKey); - return; - } - if (event.shiftKey) { - event.preventDefault(); - rangeSelectTo(threadKey, orderedThreadKeysRef.current); - return; - } - if (isTrailingDoubleClick(event.detail)) { - return; - } - navigateToThread(threadRef); - }, - [navigateToThread, rangeSelectTo, toggleThreadSelection], - ); - - // A settle per thread at a time: double clicks and repeated menu picks - // must not dispatch a second settle that fails and toasts a false error. - const settlingThreadKeysRef = useRef(new Set()); - // Parking the thread you're looking at (settle or snooze) moves you - // forward: the next remaining card (never a settled or snoozed row, never - // one leaving in the same batch), or a fresh draft in this project when it - // was the last active one. Callers snapshot the plan BEFORE the command - // mutates the partition; background parks never navigate (null plan). - const planForwardNavigation = useCallback( - (threadKey: string, coParkingKeys?: ReadonlySet): (() => void) | null => { - if (routeThreadKeyRef.current !== threadKey) return null; - const shell = threadByKeyRef.current.get(threadKey); - const orderedKeys = orderedThreadKeysRef.current; - const settledKeys = settledThreadKeysRef.current; - const snoozedKeys = snoozedThreadKeysRef.current; - const currentIndex = orderedKeys.indexOf(threadKey); - const nextCardKey = - currentIndex === -1 - ? null - : ([...orderedKeys.slice(currentIndex + 1), ...orderedKeys.slice(0, currentIndex)].find( - (key) => !settledKeys.has(key) && !snoozedKeys.has(key) && !coParkingKeys?.has(key), - ) ?? null); - const nextThread = nextCardKey ? threadByKeyRef.current.get(nextCardKey) : null; - return nextThread - ? () => navigateToThread(scopeThreadRef(nextThread.environmentId, nextThread.id)) - : shell - ? () => - void handleNewThreadRef.current(scopeProjectRef(shell.environmentId, shell.projectId)) - : () => void router.navigate({ to: "/" }); - }, - [navigateToThread, router], - ); - - const attemptSettle = useCallback( - (threadRef: ScopedThreadRef, opts: { coSettlingKeys?: ReadonlySet } = {}) => { - void (async () => { - const threadKey = scopedThreadKey(threadRef); - if (settlingThreadKeysRef.current.has(threadKey)) return; - settlingThreadKeysRef.current.add(threadKey); - try { - const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys); - const result = await settleThread(threadRef); - if (result._tag === "Failure") { - // Never navigate away from a thread that did not settle. - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to settle thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - return; - } - // Only move forward if the user is still on the settled thread — - // a navigation made during the await wins over ours. - if (routeThreadKeyRef.current === threadKey) { - navigateAfterSettle?.(); - } - } finally { - settlingThreadKeysRef.current.delete(threadKey); - } - })(); - }, - [planForwardNavigation, settleThread], - ); - const attemptUnsettle = useCallback( - (threadRef: ScopedThreadRef) => { - void (async () => { - const result = await unsettleThread(threadRef); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to un-settle thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - })(); - }, - [unsettleThread], - ); - const attemptUnsnooze = useCallback( - (threadRef: ScopedThreadRef) => { - void (async () => { - const result = await unsnoozeThread(threadRef); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to wake thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - })(); - }, - [unsnoozeThread], - ); - const attemptPin = useCallback( - (threadRef: ScopedThreadRef) => { - void (async () => { - const result = await pinThread(threadRef); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to pin thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - })(); - }, - [pinThread], - ); - const attemptUnpin = useCallback( - (threadRef: ScopedThreadRef) => { - void (async () => { - const result = await unpinThread(threadRef); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to unpin thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - })(); - }, - [unpinThread], - ); - // One snooze per thread at a time — same double-dispatch guard as settle. - const snoozingThreadKeysRef = useRef(new Set()); - const attemptSnooze = useCallback( - ( - threadRef: ScopedThreadRef, - preset: SnoozePreset, - opts: { coSnoozingKeys?: ReadonlySet } = {}, - ) => { - void (async () => { - const threadKey = scopedThreadKey(threadRef); - if (snoozingThreadKeysRef.current.has(threadKey)) return; - snoozingThreadKeysRef.current.add(threadKey); - try { - // Snoozing the open thread moves you forward, same as settle — - // both park the thread you're done with for now. - const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys); - const result = await snoozeThread(threadRef, preset.snoozedUntil); - if (result._tag === "Failure") { - // Never navigate away from a thread that did not snooze. - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to snooze thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - return; - } - // Snooze hides the row, so the toast is the only confirmation — - // and the Undo is the escape hatch for a mis-click. - toastManager.add( - stackedThreadToast({ - type: "success", - title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date(), timestampFormat)}`, - timeout: 5_000, - actionProps: { - children: "Undo", - onClick: () => attemptUnsnooze(threadRef), - }, - }), - ); - // Only move forward if the user is still on the snoozed thread — - // a navigation made during the await wins over ours. - if (routeThreadKeyRef.current === threadKey) { - navigateAfterSnooze?.(); - } - } finally { - snoozingThreadKeysRef.current.delete(threadKey); - } - })(); - }, - [attemptUnsnooze, planForwardNavigation, snoozeThread], - ); - - const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection); - const handleMultiSelectContextMenu = useCallback( - async (position: { x: number; y: number }) => { - const api = readLocalApi(); - if (!api) return; - // One exact actionable set: keys whose rows are actually rendered - // right now. Selections can outlive their rows (settled-tail paging, - // thread deletion elsewhere) and the menu labels must count only what - // the actions will touch. - const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys].filter( - (threadKey) => threadByKeyRef.current.has(threadKey), - ); - if (threadKeys.length === 0) return; - const count = threadKeys.length; - // Snooze (N) is offered when every selected thread can actually take - // it — a mixed selection with blocked-on-you work would half-apply. - const selectionNow = new Date(); - const selectedThreads = threadKeys.flatMap((threadKey) => { - const thread = threadByKeyRef.current.get(threadKey); - return thread ? [thread] : []; - }); - const canSnoozeSelection = selectedThreads.every( - (thread) => - serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true && - canSnooze(thread, { now: selectionNow.toISOString() }), - ); - const titleRegenerationThreads = selectedThreads.filter( - (thread) => - serverConfigs.get(thread.environmentId)?.environment.capabilities - .threadTitleRegeneration === true, - ); - const regeneratableTitleThreads = titleRegenerationThreads.filter( - (thread) => thread.titleRegeneration == null, - ); - const titleRegenerationMenuItem = buildBulkTitleRegenerationContextMenuItem({ - supportedCount: titleRegenerationThreads.length, - actionableCount: regeneratableTitleThreads.length, - }); - const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat); - const clicked = await settlePromise(() => - api.contextMenu.show( - [ - { id: "settle", label: `Settle (${count})` }, - ...(canSnoozeSelection - ? [ - { - id: "snooze", - label: `Snooze (${count})`, - children: snoozePresets.map((preset) => ({ - id: `snooze:${preset.id}`, - label: `${preset.label} (${preset.whenLabel})`, - })), - }, - ] - : []), - ...(titleRegenerationMenuItem ? [titleRegenerationMenuItem] : []), - { id: "mark-unread", label: `Mark unread (${count})` }, - { id: "delete", label: `Delete (${count})`, destructive: true }, - ], - position, - ), - ); - if (clicked._tag === "Failure") return; - if (clicked.value?.startsWith("snooze:")) { - const preset = snoozePresets.find( - (candidate) => `snooze:${candidate.id}` === clicked.value, - ); - if (preset) { - // Post-snooze navigation must skip threads snoozing in this same - // batch — they are all leaving the card block together. - const coSnoozingKeys = new Set(threadKeys); - for (const thread of selectedThreads) { - attemptSnooze(scopeThreadRef(thread.environmentId, thread.id), preset, { - coSnoozingKeys, - }); - } - clearSelection(); - } - return; - } - if (clicked.value === "regenerate-title") { - for (const thread of regeneratableTitleThreads) { - const result = await updateThreadMetadata({ - environmentId: thread.environmentId, - input: { threadId: thread.id, regenerateTitle: true }, - }); - if (result._tag === "Success") continue; - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to regenerate thread titles", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - return; - } - clearSelection(); - return; - } - if (clicked.value === "settle") { - // Post-settle navigation must skip threads settling in this same - // batch — they are all leaving the card block together. Rows that - // are already explicitly settled are skipped: nothing to do on a - // valid mixed selection. Pinned rows ARE included: the decider - // clears the pin as part of settling, so they park like the rest. - const coSettlingKeys = new Set(threadKeys); - for (const threadKey of threadKeys) { - const thread = threadByKeyRef.current.get(threadKey); - if (!thread || thread.settledOverride === "settled") continue; - attemptSettle(scopeThreadRef(thread.environmentId, thread.id), { coSettlingKeys }); - } - clearSelection(); - return; - } - if (clicked.value === "mark-unread") { - for (const threadKey of threadKeys) { - const thread = threadByKeyRef.current.get(threadKey); - if (!thread) continue; - markThreadUnread(scopeThreadRef(thread.environmentId, thread.id)); - } - clearSelection(); - return; - } - if (clicked.value !== "delete") return; - if (confirmThreadDelete) { - const confirmed = await settlePromise(() => - api.dialogs.confirm( - [ - `Delete ${count} thread${count === 1 ? "" : "s"}?`, - "This permanently clears conversation history for these threads.", - ].join("\n"), - ), - ); - if (confirmed._tag === "Failure" || !confirmed.value) return; - } - // Grown as deletions actually land, never seeded with the whole batch: - // orphaned-worktree detection must only discount threads that are - // really gone, or the first delete would treat still-alive batch mates - // as deleted and remove a worktree they still point at. - const deletedThreadKeys = new Set(); - for (const threadKey of threadKeys) { - const thread = threadByKeyRef.current.get(threadKey); - if (!thread) continue; - const result = await deleteThread(scopeThreadRef(thread.environmentId, thread.id), { - deletedThreadKeys, - }); - if (result._tag === "Failure") { - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to delete threads", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - return; - } - deletedThreadKeys.add(threadKey); - } - removeFromSelection(threadKeys); - }, - [ - attemptSettle, - attemptSnooze, - clearSelection, - confirmThreadDelete, - deleteThread, - markThreadUnread, - removeFromSelection, - serverConfigs, - updateThreadMetadata, - ], - ); - - const handleThreadContextMenu = useCallback( - (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { - void (async () => { - const api = readLocalApi(); - if (!api) return; - const threadKey = scopedThreadKey(threadRef); - const selectionState = useThreadSelectionStore.getState(); - if (selectionState.hasSelection() && selectionState.selectedThreadKeys.has(threadKey)) { - await handleMultiSelectContextMenu(position); - return; - } - const thread = threadByKeyRef.current.get(threadKey); - if (!thread) return; - const threadWorkspacePath = - thread.worktreePath ?? - projectCwdByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? - null; - // Un-settle works on every settled row: for explicit settles it - // clears the override, for auto-settled rows it pins the thread - // active until real activity clears the pin. Environments without - // the settlement capability get no lifecycle items at all. - const supportsSettlement = - serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === - true; - const supportsSnooze = - serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true; - const supportsPinning = - serverConfigs.get(thread.environmentId)?.environment.capabilities.threadPinning === true; - const supportsTitleRegeneration = - serverConfigs.get(thread.environmentId)?.environment.capabilities - .threadTitleRegeneration === true; - const isRegeneratingTitle = thread.titleRegeneration != null; - const isSettled = settledThreadKeysRef.current.has(threadKey); - const isSnoozed = snoozedThreadKeysRef.current.has(threadKey); - const isPinned = thread.pinnedAt != null; - // Presets resolve at menu-open time (same as the popover). - const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat); - const clicked = await settlePromise(() => - api.contextMenu.show( - [ - ...(thread.branch - ? [ - { - id: "new-thread-on-branch", - label: `New thread on ${thread.branch}`, - }, - ] - : []), - ...(supportsPinning - ? [ - isPinned - ? { id: "unpin", label: "Unpin thread" } - : { id: "pin", label: "Pin thread" }, - ] - : []), - // Both lifecycle actions stay available on pinned threads: - // settling clears the pin ("done" beats "keep on top"), and - // snoozing hides the card until wake with the pin intact. - ...(supportsSettlement - ? [ - isSettled - ? { id: "unsettle", label: "Un-settle thread" } - : { id: "settle", label: "Settle thread" }, - ] - : []), - ...(supportsSnooze - ? [ - isSnoozed - ? { id: "unsnooze", label: "Wake thread" } - : { - id: "snooze", - label: "Snooze", - disabled: !canSnooze(thread, { now: new Date().toISOString() }), - children: snoozePresets.map((preset) => ({ - id: `snooze:${preset.id}`, - label: `${preset.label} (${preset.whenLabel})`, - })), - }, - ] - : []), - { id: "rename", label: "Rename thread" }, - ...(supportsTitleRegeneration - ? [ - { - id: "regenerate-title", - label: isRegeneratingTitle ? "Regenerating…" : "Regenerate title", - disabled: isRegeneratingTitle, - }, - ] - : []), - { id: "mark-unread", label: "Mark unread" }, - { id: "copy-path", label: "Copy path", icon: "copy" }, - ...(thread.branch ? [{ id: "copy-branch", label: "Copy branch", icon: "copy" }] : []), - { id: "delete", label: "Delete", destructive: true, icon: "trash" }, - ], - position, - ), - ); - if (clicked._tag === "Failure") return; - if (clicked.value?.startsWith("snooze:")) { - const preset = snoozePresets.find( - (candidate) => `snooze:${candidate.id}` === clicked.value, - ); - if (preset) attemptSnooze(threadRef, preset); - return; - } - switch (clicked.value) { - case "new-thread-on-branch": { - // Explicit branch carry-over: reuse the thread's worktree when it - // has one, otherwise its branch on the local checkout. - const result = await settlePromise(() => - handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId), { - branch: thread.branch, - worktreePath: thread.worktreePath, - envMode: thread.worktreePath ? "worktree" : "local", - startFromOrigin: false, - }), - ); - if (result._tag === "Failure") { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not create thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - return; - } - case "settle": - attemptSettle(threadRef); - return; - case "unsettle": - attemptUnsettle(threadRef); - return; - case "unsnooze": - attemptUnsnooze(threadRef); - return; - case "pin": - attemptPin(threadRef); - return; - case "unpin": - attemptUnpin(threadRef); - return; - case "rename": - startThreadRename(threadRef, thread.title); - return; - case "regenerate-title": { - if (isRegeneratingTitle) return; - const result = await updateThreadMetadata({ - environmentId: threadRef.environmentId, - input: { threadId: threadRef.threadId, regenerateTitle: true }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to regenerate thread title", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - return; - } - case "mark-unread": - markThreadUnread(threadRef); - return; - case "copy-path": - if (!threadWorkspacePath) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Path unavailable", - description: "This thread does not have a workspace path to copy.", - }), - ); - return; - } - copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath }); - return; - case "copy-branch": - if (thread.branch) { - copyBranchToClipboard(thread.branch, { branch: thread.branch }); - } - return; - case "delete": { - if (confirmThreadDelete) { - const confirmed = await settlePromise(() => - api.dialogs.confirm( - [ - `Delete thread "${thread.title}"?`, - "This permanently clears conversation history for this thread.", - ].join("\n"), - ), - ); - if (confirmed._tag === "Failure" || !confirmed.value) return; - } - const result = await deleteThread(threadRef); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to delete thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - return; - } - return; - } - default: - return; - } - })(); - }, - [ - attemptPin, - attemptSettle, - attemptSnooze, - attemptUnpin, - attemptUnsettle, - attemptUnsnooze, - confirmThreadDelete, - copyBranchToClipboard, - copyPathToClipboard, - deleteThread, - handleMultiSelectContextMenu, - markThreadUnread, - projectCwdByKey, - serverConfigs, - startThreadRename, - updateThreadMetadata, - ], - ); - - // Thread jump (cmd+1..9) and prev/next traversal reuse the same commands as - // v1 — the keybinding layer is shared, only the ordered list differs. - const routeTerminalOpen = useTerminalUiStateStore((state) => - routeThreadRef - ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen - : false, - ); - useEffect(() => { - const onWindowKeyDown = (event: KeyboardEvent) => { - if (event.defaultPrevented || event.repeat) return; - const command = resolveShortcutCommand(event, keybindings, { - platform: navigator.platform, - context: { - terminalFocus: isTerminalFocused(), - terminalOpen: routeTerminalOpen, - modelPickerOpen: isModelPickerOpen(), - }, - }); - const navigateToThreadKey = (targetThreadKey: string | null) => { - if (!targetThreadKey) return false; - const targetThread = threadByKey.get(targetThreadKey); - if (!targetThread) return false; - event.preventDefault(); - event.stopPropagation(); - navigateToThread(scopeThreadRef(targetThread.environmentId, targetThread.id)); - return true; - }; - const traversalDirection = threadTraversalDirectionFromCommand(command); - if (traversalDirection !== null) { - navigateToThreadKey( - resolveAdjacentThreadId({ - threadIds: orderedThreadKeys, - currentThreadId: routeThreadKey, - direction: traversalDirection, - }), - ); - return; - } - const jumpIndex = threadJumpIndexFromCommand(command ?? ""); - if (jumpIndex === null) return; - navigateToThreadKey(orderedThreadKeys[jumpIndex] ?? null); - }; - window.addEventListener("keydown", onWindowKeyDown); - return () => window.removeEventListener("keydown", onWindowKeyDown); - }, [ - keybindings, - navigateToThread, - orderedThreadKeys, - routeTerminalOpen, - routeThreadKey, - threadByKey, - ]); - - // Same predicate as v1: hints show only while the held modifiers exactly - // match a thread-jump binding. Adding Shift (screenshots) or Alt no - // longer matches ⌘1..9, so the overlay hides for chords like ⌘⇧4. - const shortcutModifiers = useShortcutModifierState(); - const shouldShowJumpHintsNow = shouldShowThreadJumpHintsForModifiers( - shortcutModifiers, - keybindings, - { platform: navigator.platform }, - ); - useEffect(() => { - setShowJumpHints(shouldShowJumpHintsNow); - }, [shouldShowJumpHintsNow]); - - const attachListAutoAnimateRef = useCallback((node: HTMLUListElement | null) => { - if (!node) return; - autoAnimate(node, { duration: 150, easing: "ease-out" }); - }, []); - - // New thread defaults to the project you're in (active thread's project, - // falling back to the top project) — same resolution the command palette - // uses. The command palette already offers a "New thread in..." submenu - // for multi-project setups. - const handleNewThreadClick = useCallback(() => { - // One project: nothing to pick, create immediately. - if (projectGroups.length <= 1) { - if (isMobile) setOpenMobile(false); - void startNewThreadFromContext({ - activeDraftThread: newThreadContext.activeDraftThread, - activeThread: newThreadContext.activeThread ?? undefined, - defaultProjectRef: newThreadContext.defaultProjectRef, - handleNewThread: newThreadContext.handleNewThread, - }); - return; - } - if (isMobile) setOpenMobile(false); - openCommandPalette({ open: "new-thread-in" }); - }, [isMobile, newThreadContext, projectGroups.length, setOpenMobile]); - - // Same resolution as v1: prefer the local-thread binding, fall back to - // chat.new, no platform gating — web users have working shortcuts too. - const newThreadShortcutLabel = - shortcutLabelForCommand(keybindings, "chat.newLocal") ?? - shortcutLabelForCommand(keybindings, "chat.new"); - return ( - <> - - -
    -
    - - { - setThreadSearchQuery(event.currentTarget.value); - setActiveSearchResultIndex(0); - }} - onKeyDown={handleThreadSearchKeyDown} - placeholder="Search" - aria-label="Search threads" - role="combobox" - aria-autocomplete="list" - aria-expanded={isSearchingThreads && threadSearchResults.length > 0} - aria-controls={ - isSearchingThreads && threadSearchResults.length > 0 - ? "sidebar-thread-search-results" - : undefined - } - aria-activedescendant={ - isSearchingThreads && threadSearchResults[activeSearchResultIndex] - ? `sidebar-thread-search-result-${activeSearchResultIndex}` - : undefined - } - className="min-w-0 flex-1 [&_[data-slot=input]]:h-auto [&_[data-slot=input]]:p-0 [&_[data-slot=input]]:leading-normal [&_[data-slot=input]]:text-sm [&_[data-slot=input]]:font-medium [&_[data-slot=input]]:text-sidebar-foreground [&_[data-slot=input]]:placeholder:text-sidebar-muted-foreground" - /> - {isSearchingThreads ? ( - - ) : null} -
    -
    - - - } - > - - - - {newThreadShortcutLabel - ? `New thread (${newThreadShortcutLabel})` - : "New thread"} - - -
    -
    - {projectGroups.length > 0 ? ( -
    - - - } - > - {scopedProjectGroup ? ( - - ) : ( - - )} - - {scopedProjectGroup?.displayName ?? "All projects"} - - - - - - setProjectScopeKey(value === "all" ? null : (value as string)) - } - > - - - All projects - - {projectGroups.map((project) => { - const scopeKey = project.projectKey; - return ( - - - {project.displayName} - - - ); - })} - - - - - - } - > - - - New project - -
    - ) : null} - - } - > - - {isSearchingThreads ? ( - threadSearchResults.length > 0 ? ( - - - - ) : ( -

    - No threads found -

    - ) - ) : null} - {!isSearchingThreads ? ( - -
      - {(() => { - const renderThreadRow = ( - thread: EnvironmentThreadShell, - section: "pinned" | "active" | "snoozed" | "settled", - ) => { - const threadKey = scopedThreadKey( - scopeThreadRef(thread.environmentId, thread.id), - ); - // Settled and snoozed are the ONLY things that collapse a - // row: every other thread is a full card. Density comes - // from users (or the auto rules) actually parking work, - // not from the sidebar second-guessing what still matters. - const isCard = section === "active" || section === "pinned"; - const rowVariant = isCard ? "card" : "slim"; - return ( - - ); - }; - // Pinned block: full cards above the inbox, closed by a - // thin divider (the pin glyphs carry the meaning, so no - // header text). Vanishes entirely at count 0. - const items: ReactNode[] = pinnedThreads.map((thread) => - renderThreadRow(thread, "pinned"), - ); - if (pinnedThreads.length > 0) { - items.push( -
    • , - ); - } - for (const thread of activeThreads) { - items.push(renderThreadRow(thread, "active")); - } - // Snoozed shelf: between the inbox and Settled — out of the - // way, never gone. The header always renders while anything - // is snoozed (the count is the whole footprint when - // collapsed); rows only when expanded. Vanishes entirely at - // count 0. - if (snoozedThreads.length > 0) { - items.push( -
    • - -
    • , - ); - for (const thread of visibleSnoozedThreads) { - items.push(renderThreadRow(thread, "snoozed")); - } - } - if (settledThreads.length > 0) { - items.push( -
    • - -
    • , - ); - } - for (const thread of renderedSettledThreads) { - items.push(renderThreadRow(thread, "settled")); - } - return items; - })()} - {settledShelfExpanded && hiddenSettledCount > 0 ? ( -
    • - -
    • - ) : null} -
    -
    - ) : null} - {!isSearchingThreads && - pinnedThreads.length + - activeThreads.length + - snoozedThreads.length + - settledThreads.length === - 0 ? ( -
    - {projects.length === 0 ? ( - <> - No projects yet - - - ) : scopedProjectGroup ? ( - `No threads in ${scopedProjectGroup.displayName} yet` - ) : ( - "No threads yet" - )} -
    - ) : null} -
    -
    - { - if (!open) setProjectActionsTarget(null); - }} - > - - - Project settings - - Manage project names, grouping rules, and environments. - -
    - {projectActionsTarget?.memberProjects.map((member) => ( -
    - - - {member.workspaceRoot} - - - - - - {member.environmentLabel ?? "Current environment"} - - -
    - ))} -
    -
    - -
    - {projectActionsTarget?.memberProjects.map((member) => ( -
    -
    - - -
    - {projectActionsTarget.memberProjects.length > 1 ? ( -
    - -
    - ) : null} -
    - ))} -
    - {projectActionsTarget && projectActionsTarget.memberProjects.length > 1 ? ( -
    -
    -

    - Remove this project everywhere -

    -

    - Deletes all grouped entries and their conversation history. -

    -
    - -
    - ) : null} -
    - - {projectActionsTarget?.memberProjects.length === 1 ? ( - - ) : null} - - -
    -
    - - - ); -} diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index c5b86feab3..db13419962 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -1,84 +1,340 @@ -import { type EnvironmentId } from "@t3tools/contracts"; -import { memo } from "react"; - -import { cn } from "~/lib/utils"; -import { ProjectFavicon } from "../ProjectFavicon"; +import { + type EnvironmentId, + type EditorId, + type ProjectScript, + type ResolvedKeybindingsConfig, + type ThreadId, +} from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { ChangeRequestStateLike } from "@t3tools/client-runtime/state/thread-settled"; +import { ChevronDownIcon } from "lucide-react"; +import { + memo, + useCallback, + useMemo, + useRef, + useState, + type KeyboardEvent as ReactKeyboardEvent, + type MouseEvent as ReactMouseEvent, +} from "react"; +import GitActionsControl from "../GitActionsControl"; +import { type DraftId } from "~/composerDraftStore"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { toastManager } from "../ui/toast"; +import ProjectScriptsControl, { + type NewProjectScriptInput, + type ProjectScriptActionResult, +} from "../ProjectScriptsControl"; +import { OpenInPicker } from "./OpenInPicker"; +import { usePrimaryEnvironmentId } from "../../state/environments"; +import { useT3ProjectFileScripts } from "~/hooks/useT3ProjectFileScripts"; +import { useThreadActionMenu } from "~/hooks/useThreadActionMenu"; +import { threadEnvironment } from "../../state/threads"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { ProjectFavicon } from "../ProjectFavicon"; +import { + WorkspaceBreadcrumb, + WorkspaceBreadcrumbItem, + WorkspaceBreadcrumbSeparator, +} from "../WorkspaceBreadcrumb"; +import { cn } from "~/lib/utils"; interface ChatHeaderProps { activeThreadEnvironmentId: EnvironmentId; + activeThreadId: ThreadId; + draftId?: DraftId; activeThreadTitle: string; + /** Drafts have no server thread yet, so the title carries no action menu. */ + isServerThread: boolean; + /** PR state feeding the settled classification, resolved by ChatView. */ + changeRequestState: ChangeRequestStateLike | null; activeProjectName: string | undefined; activeProjectCwd: string | null; + activeProjectFaviconPath: string | null; + openInCwd: string | null; + activeProjectScripts: ReadonlyArray | undefined; + preferredScriptId: string | null; + keybindings: ResolvedKeybindingsConfig; + availableEditors: ReadonlyArray; rightPanelOpen: boolean; + gitCwd: string | null; + readonly onOpenPullRequest?: ((number: number) => void) | undefined; onNewThreadInProject: () => void; + onRunProjectScript: (script: ProjectScript) => void; + onAddProjectScript: (input: NewProjectScriptInput) => Promise; + onUpdateProjectScript: ( + scriptId: string, + input: NewProjectScriptInput, + ) => Promise; + onDeleteProjectScript: (scriptId: string) => Promise; +} + +/** + * Rename commit rule shared with the sidebar's inline rename: trim, reject + * empty (the caller toasts), and skip the mutation when nothing changed. + */ +export function resolveRenameCommit(input: { + readonly title: string; + readonly originalTitle: string; +}): { action: "commit"; title: string } | { action: "reject-empty" } | { action: "noop" } { + const trimmed = input.title.trim(); + if (trimmed.length === 0) return { action: "reject-empty" }; + if (trimmed === input.originalTitle) return { action: "noop" }; + return { action: "commit", title: trimmed }; +} + +export function shouldShowOpenInPicker(input: { + readonly activeProjectName: string | undefined; + readonly activeThreadEnvironmentId: EnvironmentId; + readonly primaryEnvironmentId: EnvironmentId | null; +}): boolean { + return ( + Boolean(input.activeProjectName) && + input.primaryEnvironmentId !== null && + input.activeThreadEnvironmentId === input.primaryEnvironmentId + ); } export const ChatHeader = memo(function ChatHeader({ activeThreadEnvironmentId, + activeThreadId, + draftId, activeThreadTitle, + isServerThread, + changeRequestState, activeProjectName, activeProjectCwd, + activeProjectFaviconPath, + openInCwd, + activeProjectScripts, + preferredScriptId, + keybindings, + availableEditors, rightPanelOpen, + gitCwd, + onOpenPullRequest, onNewThreadInProject, + onRunProjectScript, + onAddProjectScript, + onUpdateProjectScript, + onDeleteProjectScript, }: ChatHeaderProps) { + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const fileScripts = useT3ProjectFileScripts( + activeThreadEnvironmentId, + activeProjectScripts ? activeProjectCwd : null, + ); + const showOpenInPicker = shouldShowOpenInPicker({ + activeProjectName, + activeThreadEnvironmentId, + primaryEnvironmentId, + }); + const activeThreadRef = useMemo( + () => scopeThreadRef(activeThreadEnvironmentId, activeThreadId), + [activeThreadEnvironmentId, activeThreadId], + ); + const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { + reportFailure: false, + }); + // Inline rename, keyed by thread: navigating away drops an in-progress + // rename instead of committing stale text. Cleared on thread change (not + // just hidden) so returning to the thread doesn't revive the old draft. + const [renaming, setRenaming] = useState<{ threadId: ThreadId; title: string } | null>(null); + if (renaming !== null && renaming.threadId !== activeThreadId) { + setRenaming(null); + } + const renamingTitle = renaming?.threadId === activeThreadId ? renaming.title : null; + const renameCommittedRef = useRef(false); + const startRename = useCallback(() => { + renameCommittedRef.current = false; + setRenaming({ threadId: activeThreadId, title: activeThreadTitle }); + }, [activeThreadId, activeThreadTitle]); + const commitRename = useCallback( + (title: string) => { + setRenaming(null); + const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle }); + if (resolution.action === "reject-empty") { + toastManager.add({ type: "warning", title: "Thread title cannot be empty" }); + return; + } + if (resolution.action === "noop") return; + void updateThreadMetadata({ + environmentId: activeThreadEnvironmentId, + input: { threadId: activeThreadId, title: resolution.title }, + }).then((result) => { + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title: "Failed to rename thread", + description: error instanceof Error ? error.message : "An error occurred.", + }); + } + }); + }, + [activeThreadEnvironmentId, activeThreadId, activeThreadTitle, updateThreadMetadata], + ); + const { openMenu } = useThreadActionMenu({ + threadRef: isServerThread ? activeThreadRef : null, + projectCwd: activeProjectCwd, + changeRequestState, + onStartRename: startRename, + }); + const titleButtonRef = useRef(null); + const openMenuFromTitle = useCallback(() => { + const rect = titleButtonRef.current?.getBoundingClientRect(); + if (!rect) return; + openMenu({ x: rect.left, y: rect.bottom + 4 }); + }, [openMenu]); + const handleHeaderContextMenu = useCallback( + (event: ReactMouseEvent) => { + if (!isServerThread || renamingTitle !== null) return; + // The right-side controls (git, scripts, open-in) keep their own + // behavior; only the breadcrumb area opens the thread menu. + if ((event.target as HTMLElement).closest("[data-chat-header-actions]")) return; + event.preventDefault(); + openMenu({ x: event.clientX, y: event.clientY }); + }, + [isServerThread, openMenu, renamingTitle], + ); + const handleRenameKeyDown = useCallback( + (event: ReactKeyboardEvent) => { + if (event.key === "Enter") { + renameCommittedRef.current = true; + commitRename(event.currentTarget.value); + } else if (event.key === "Escape") { + renameCommittedRef.current = true; + setRenaming(null); + } + }, + [commitRename], + ); return (
    -
    + {/* The project always leads the header: knowing which project a thread lives in is priority zero, and the thread title alone doesn't answer it. */} {activeProjectName ? ( - + <> + + + + } + > + + {activeProjectName} + + New thread in {activeProjectName} + + + + + ) : null} + + {renamingTitle !== null ? ( + { + if (renameCommittedRef.current) return; + commitRename(event.currentTarget.value); + }} + onFocus={(event) => event.currentTarget.select()} + onKeyDown={handleRenameKeyDown} + /> + ) : isServerThread ? ( } > - {activeThreadTitle} + - {activeProjectName} - New thread in {activeProjectName} + {activeThreadTitle} - - / - - - ) : null} - - - {activeThreadTitle} - - + + {activeThreadTitle} + + } /> -======= - } + {activeThreadTitle} + + )} + + +
    + {activeProjectScripts && ( + - {activeThreadTitle} - ->>>>>>> ad06049b75 (fix: port main fixes stranded by the v2 rewrite (round 2)) + )} + {showOpenInPicker && ( + + )} + {activeProjectName && ( + + )}
    ); diff --git a/apps/web/src/components/chat/PanelLayoutControls.tsx b/apps/web/src/components/chat/PanelLayoutControls.tsx index 3dd7e76ef4..ad71ff971b 100644 --- a/apps/web/src/components/chat/PanelLayoutControls.tsx +++ b/apps/web/src/components/chat/PanelLayoutControls.tsx @@ -12,15 +12,10 @@ import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { Toggle } from "../ui/toggle"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -<<<<<<< HEAD -interface PanelLayoutControlsProps { - showTerminalControl?: boolean; -======= export interface PanelLayoutControlsProps { showThreadPanelControl?: boolean; showTerminalControl?: boolean; showRightPanelControl?: boolean; ->>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar) terminalAvailable: boolean; terminalOpen: boolean; terminalShortcutLabel: string | null; @@ -41,13 +36,9 @@ export interface PanelLayoutControlsProps { } export const PanelLayoutControls = memo(function PanelLayoutControls({ -<<<<<<< HEAD - showTerminalControl = true, -======= showThreadPanelControl = true, showTerminalControl = true, showRightPanelControl = true, ->>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar) terminalAvailable, terminalOpen, terminalShortcutLabel, @@ -100,8 +91,6 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({ className="flex h-full shrink-0 items-center gap-1 [-webkit-app-region:no-drag]" data-panel-layout-controls > -<<<<<<< HEAD -======= {showThreadPanelControl ? ( threadPanelPresentation === "popover" ? ( >>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar) {showTerminalControl ? ( - + } /> @@ -154,46 +142,6 @@ export const PanelLayoutControls = memo(function PanelLayoutControls({ ) : null} -<<<<<<< HEAD - - 0 - ? `Toggle right panel, ${liveAgentCount} ${liveAgentCount === 1 ? "agent" : "agents"} working` - : "Toggle right panel" - } - variant="ghost" - size="sm" - disabled={!rightPanelAvailable} - > - - {liveAgentCount > 0 ? ( - - {liveAgentCount} - - ) : null} - - } - /> - - {rightPanelAvailable - ? `Toggle right panel${rightPanelShortcutLabel ? ` (${rightPanelShortcutLabel})` : ""}${ - liveAgentCount > 0 - ? ` · ${liveAgentCount} ${liveAgentCount === 1 ? "agent" : "agents"} working` - : "" - }` - : "Right panel is unavailable"} - - -======= {showRightPanelControl ? ( ) : null} ->>>>>>> abd5cc5ff8 (Map thread panel into title bar and sidebar)
    ); }); @@ -244,9 +191,9 @@ export const RightPanelMaximizeControl = memo(function RightPanelMaximizeControl size="sm" > {maximized ? ( - + ) : ( - + )} } diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index f225880904..9b63e21f38 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -550,7 +550,6 @@ export function useSettingsRestore(onRestored?: () => void) { settings.glassOpacity, settings.enableLegacyTokenStreaming, settings.persistComposerContextStrip, - settings.enableAssistantStreaming, settings.enableProviderUpdateChecks, settings.sidebarAutoSettleAfterDays, settings.sidebarAutoSettleOnMerge, diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index 54eb72fefb..b446b05875 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -51,16 +51,9 @@ const SETTINGS_SECTION_ICONS: Readonly< "/settings/appearance": PaletteIcon, "/settings/keybindings": KeyboardIcon, "/settings/providers": BotIcon, -<<<<<<< HEAD - "/settings/source-control": GitBranchIcon, - "/settings/connections": Link2Icon, - "/settings/scheduled-tasks": CalendarClockIcon, -======= "/settings/scheduled-tasks": CalendarClockIcon, "/settings/source-control": GitBranchIcon, "/settings/connections": Link2Icon, - "/settings/beta": FlaskConicalIcon, ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) "/settings/archived": ArchiveIcon, }; diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index f0a0d67ca5..6bdd09181a 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -22,16 +22,8 @@ import { getProjectOrderKey, selectProjectGroupingSettings, } from "../logicalProject"; -<<<<<<< HEAD -<<<<<<< HEAD import { resolveDefaultThreadEnvMode } from "@t3tools/shared/threadEnvMode"; -import { readThreadShell, useProjects, useThread } from "../state/entities"; -======= import { readThreadShell, useProjects, useServerConfigs, useThreadShell } from "../state/entities"; ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= -import { readThreadShell, useProjects, useThreadShell } from "../state/entities"; ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions"; import { readT3ProjectFileDefaultThreadEnvMode } from "../lib/t3ProjectFileDefaults"; import { primaryServerSettingsAtom } from "../state/server"; diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts index 66e028f7fa..064b927031 100644 --- a/apps/web/src/localApi.test.ts +++ b/apps/web/src/localApi.test.ts @@ -14,111 +14,9 @@ const showContextMenuFallbackMock = ) => Promise >(); -<<<<<<< HEAD const requestConfirmDialogMock = vi.fn<(message: string, options?: ConfirmDialogOptions) => Promise | undefined>(); -function registerListener(listeners: Set<(event: T) => void>, listener: (event: T) => void) { - listeners.add(listener); - return () => { - listeners.delete(listener); - }; -} -const terminalEventListeners = new Set<(event: TerminalEvent) => void>(); -const shellStreamListeners = new Set<(event: OrchestrationShellStreamItem) => void>(); -const gitStatusListeners = new Set<(event: GitStatusResult) => void>(); - -const rpcClientMock = { - dispose: vi.fn(), - terminal: { - open: vi.fn(), - write: vi.fn(), - resize: vi.fn(), - clear: vi.fn(), - restart: vi.fn(), - close: vi.fn(), - onEvent: vi.fn((listener: (event: TerminalEvent) => void) => - registerListener(terminalEventListeners, listener), - ), - }, - projects: { - searchEntries: vi.fn(), - writeFile: vi.fn(), - }, - filesystem: { - browse: vi.fn(), - }, - shell: { - openInEditor: vi.fn(), - }, - git: { - pull: vi.fn(), - refreshStatus: vi.fn(), - onStatus: vi.fn((input: { cwd: string }, listener: (event: GitStatusResult) => void) => - registerListener(gitStatusListeners, listener), - ), - runStackedAction: vi.fn(), - listBranches: vi.fn(), - createWorktree: vi.fn(), - removeWorktree: vi.fn(), - createBranch: vi.fn(), - checkout: vi.fn(), - init: vi.fn(), - resolvePullRequest: vi.fn(), - preparePullRequestThread: vi.fn(), - }, - server: { - getConfig: vi.fn(), - refreshProviders: vi.fn(), - upsertKeybinding: vi.fn(), - getSettings: vi.fn(), - updateSettings: vi.fn(), - subscribeConfig: vi.fn(), - subscribeLifecycle: vi.fn(), - subscribeAuthAccess: vi.fn(), - }, - orchestration: { - dispatchCommand: vi.fn(), - getTurnDiff: vi.fn(), - getFullThreadDiff: vi.fn(), - subscribeShell: vi.fn((listener: (event: OrchestrationShellStreamItem) => void) => - registerListener(shellStreamListeners, listener), - ), - subscribeThread: vi.fn(() => () => undefined), - }, - orchestrationV2: { - dispatchCommand: vi.fn(), - getThreadProjection: vi.fn(), - subscribeThread: vi.fn(() => () => undefined), - }, -}; - -vi.mock("./environments/runtime", () => ({ - getPrimaryEnvironmentConnection: () => ({ - kind: "primary" as const, - knownEnvironment: { - id: "environment-local", - label: "Primary", - source: "manual" as const, - target: { - httpBaseUrl: "http://localhost:3000", - wsBaseUrl: "ws://localhost:3000", - }, - environmentId: EnvironmentId.make("environment-local"), - }, - client: rpcClientMock, - environmentId: EnvironmentId.make("environment-local"), - ensureBootstrapped: async () => undefined, - reconnect: async () => undefined, - dispose: async () => undefined, - }), - resetEnvironmentServiceForTests: vi.fn(), - resetSavedEnvironmentRegistryStoreForTests: vi.fn(), - resetSavedEnvironmentRuntimeStoreForTests: vi.fn(), -})); - -======= ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) vi.mock("./contextMenuFallback", () => ({ showContextMenuFallback: showContextMenuFallbackMock, })); diff --git a/apps/web/src/rightPanelStore.test.ts b/apps/web/src/rightPanelStore.test.ts index 84534d158a..fcc3bd5c9c 100644 --- a/apps/web/src/rightPanelStore.test.ts +++ b/apps/web/src/rightPanelStore.test.ts @@ -11,7 +11,6 @@ import { selectThreadPanelOpen, selectThreadPanelVisibility, selectThreadRightPanelState, - updatePullRequestTabStatus, useRightPanelStore, } from "./rightPanelStore"; @@ -183,557 +182,454 @@ describe("rightPanelStore", () => { }); it("drops persisted plan surfaces and does not reopen an empty panel", () => { - it("persists inline preference without restoring an open popover", () => { - expect( - migratePersistedRightPanelState({ + it("persists inline preference without restoring an open popover", () => { + expect( + migratePersistedRightPanelState({ + threadPanelVisibilityByThreadKey: { + "env-1:thread-A": { inlineOpen: false, popoverOpen: true }, + "env-1:thread-B": { inlineOpen: true, popoverOpen: true }, + }, + }), + ).toEqual({ + byThreadKey: {}, threadPanelVisibilityByThreadKey: { - "env-1:thread-A": { inlineOpen: false, popoverOpen: true }, - "env-1:thread-B": { inlineOpen: true, popoverOpen: true }, + "env-1:thread-A": { inlineOpen: false, popoverOpen: false }, }, - }), - ).toEqual({ - byThreadKey: {}, - threadPanelVisibilityByThreadKey: { - "env-1:thread-A": { inlineOpen: false, popoverOpen: false }, - }, - }); - }); - - it("tracks inline and popover visibility independently", () => { - const store = useRightPanelStore.getState(); - - expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "inline")).toBe( - true, - ); - expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "popover")).toBe( - false, - ); - - store.setThreadPanelOpen(refA, "inline", false); - store.toggleThreadPanel(refA, "popover"); - - expect( - selectThreadPanelVisibility( - useRightPanelStore.getState().threadPanelVisibilityByThreadKey, - refA, - ), - ).toEqual({ inlineOpen: false, popoverOpen: true }); - expect( - selectThreadPanelVisibility( - useRightPanelStore.getState().threadPanelVisibilityByThreadKey, - refB, - ), - ).toEqual({ inlineOpen: true, popoverOpen: false }); - }); - - it("closes the popover atomically when the real right panel opens", () => { - useRightPanelStore.getState().setThreadPanelOpen(refA, "popover", true); - useRightPanelStore.getState().open(refA, "diff"); - - expect( - selectThreadPanelVisibility( - useRightPanelStore.getState().threadPanelVisibilityByThreadKey, - refA, - ), - ).toEqual({ inlineOpen: true, popoverOpen: false }); - }); - - it("keeps an open popover visible by promoting it to inline when the real panel closes", () => { - const store = useRightPanelStore.getState(); - store.open(refA, "diff"); - store.setThreadPanelOpen(refA, "inline", false); - store.setThreadPanelOpen(refA, "popover", true); - store.close(refA); - - expect( - selectThreadPanelVisibility( - useRightPanelStore.getState().threadPanelVisibilityByThreadKey, - refA, - ), - ).toEqual({ inlineOpen: true, popoverOpen: true }); - }); - - it("open sets the active panel for a thread", () => { - useRightPanelStore.getState().open(refA, "preview"); - expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview"); - expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refB)).toBeNull(); - }); - - it("opening a different kind keeps both surfaces and activates the new one", () => { - useRightPanelStore.getState().open(refA, "agents"); - useRightPanelStore.getState().open(refA, "preview"); - expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("preview"); - expect( - selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces, - ).toHaveLength(2); - }); - - it("reopening an inactive singleton activates its existing surface", () => { - useRightPanelStore.getState().open(refA, "diff"); - useRightPanelStore.getState().open(refA, "agents"); - useRightPanelStore.getState().open(refA, "diff"); - - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: true, - activeSurfaceId: "diff", - surfaces: [ - { id: "diff", kind: "diff" }, - { id: "agents", kind: "agents" }, - ], - }); - }); - - it("keeps files as a singleton surface", () => { - useRightPanelStore.getState().open(refA, "files"); - useRightPanelStore.getState().open(refA, "files"); - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: true, - activeSurfaceId: "files", - surfaces: [{ id: "files", kind: "files" }], - }); - }); - - it("replaces the standalone explorer with peer file surfaces", () => { - useRightPanelStore.getState().open(refA, "files"); - useRightPanelStore.getState().openFile(refA, "src/index.ts"); - useRightPanelStore.getState().openFile(refA, "src/index.ts"); - useRightPanelStore.getState().openFile(refA, "README.md"); - - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: true, - activeSurfaceId: "file:README.md", - surfaces: [ - { - id: "file:src/index.ts", - kind: "file", - relativePath: "src/index.ts", - revealLine: null, - revealRequestId: 2, - }, - { - id: "file:README.md", - kind: "file", - relativePath: "README.md", - revealLine: null, - revealRequestId: 1, - }, - ], - }); - }); - - it("updates line reveal requests when reopening a file surface", () => { - useRightPanelStore.getState().openFile(refA, "src/index.ts", 42); - useRightPanelStore.getState().openFile(refA, "src/index.ts", 87); - - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: true, - activeSurfaceId: "file:src/index.ts", - surfaces: [ - { - id: "file:src/index.ts", - kind: "file", - relativePath: "src/index.ts", - revealLine: 87, - revealRequestId: 2, - }, - ], + }); }); - useRightPanelStore.getState().openFile(refA, "src/index.ts"); + it("tracks inline and popover visibility independently", () => { + const store = useRightPanelStore.getState(); - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: true, - activeSurfaceId: "file:src/index.ts", - surfaces: [ - { - id: "file:src/index.ts", - kind: "file", - relativePath: "src/index.ts", - revealLine: null, - revealRequestId: 3, - }, - ], - }); - }); - - it("removes persisted file surfaces when their workspace no longer exists", () => { - useRightPanelStore.getState().openFile(refA, "src/index.ts"); - useRightPanelStore.getState().open(refA, "agents"); - useRightPanelStore.getState().openFile(refA, "README.md"); - - useRightPanelStore.getState().reconcileFileSurfaces(refA, false); - - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: true, - activeSurfaceId: "agents", - surfaces: [{ id: "agents", kind: "agents" }], - }); - - useRightPanelStore.getState().openFile(refB, "conductor.json"); - useRightPanelStore.getState().reconcileFileSurfaces(refB, false); - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refB)).toEqual({ - isOpen: false, - activeSurfaceId: null, - surfaces: [], - }); - }); - - it("close hides the panel without clearing its selected surface", () => { - useRightPanelStore.getState().open(refA, "agents"); - useRightPanelStore.getState().close(refA); - expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull(); - expect( - selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA), - ).toEqual({ id: "agents", kind: "agents" }); - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: false, - activeSurfaceId: "agents", - surfaces: [{ id: "agents", kind: "agents" }], - }); - }); - - it("toggles empty panel visibility without creating a surface", () => { - useRightPanelStore.getState().toggleVisibility(refA); - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: true, - activeSurfaceId: null, - surfaces: [], - }); - - useRightPanelStore.getState().toggleVisibility(refA); - expect(useRightPanelStore.getState().byThreadKey).toEqual({}); - }); - - it("toggle hides the panel without discarding the active surface", () => { - useRightPanelStore.getState().toggle(refA, "diff"); - expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("diff"); - useRightPanelStore.getState().toggle(refA, "diff"); - expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull(); - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: false, - activeSurfaceId: "diff", - surfaces: [{ id: "diff", kind: "diff" }], - }); - }); - - it("toggle to a different kind switches active", () => { - useRightPanelStore.getState().toggle(refA, "preview"); - useRightPanelStore.getState().toggle(refA, "agents"); - expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("agents"); - }); - - it("removeThread clears persisted state", () => { - useRightPanelStore.getState().open(refA, "agents"); - useRightPanelStore.getState().removeThread(refA); - expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull(); - }); - - it("close on never-opened thread is a no-op", () => { - useRightPanelStore.getState().close(refA); - expect(useRightPanelStore.getState().byThreadKey).toEqual({}); - }); - - it("tracks one surface per browser session", () => { - useRightPanelStore.getState().openBrowser(refA, "tab-a"); - useRightPanelStore.getState().openBrowser(refA, "tab-b"); - - const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA); - expect(state.surfaces.map((surface) => surface.id)).toEqual(["browser:tab-a", "browser:tab-b"]); - expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - id: "browser:tab-b", - kind: "preview", - resourceId: "tab-b", - }); - }); - - it("tracks one surface per pull request", () => { - const first = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4909 }; - const second = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4910 }; - useRightPanelStore.getState().openPullRequest(refA, first); - useRightPanelStore.getState().openPullRequest(refA, second); - useRightPanelStore.getState().openPullRequest(refA, first); - - const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA); - expect(state.surfaces.map((surface) => surface.id)).toEqual([ - pullRequestSurfaceId(first), - pullRequestSurfaceId(second), - ]); - expect(state.activeSurfaceId).toBe(pullRequestSurfaceId(first)); - }); - - it("keeps one pull request read from two servers as two tabs", () => { - const local = { - environmentId: "local", - projectId: "project-a", - repository: "pingdotgg/t3code", - number: 4909, - }; - const remote = { ...local, environmentId: "remote" }; - - useRightPanelStore.getState().openPullRequest(refA, local); - useRightPanelStore.getState().openPullRequest(refA, remote); - - const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA); - expect(state.surfaces.map((surface) => surface.id)).toEqual([ - pullRequestSurfaceId(local), - pullRequestSurfaceId(remote), - ]); - }); - - it("keeps the page's panel tabs reachable when the set of connected servers changes", () => { - // The pull-requests page keys its one shared panel by a fixed sentinel environment, not by - // whichever capable server happens to sort first (see PULL_REQUESTS_PANEL_ENVIRONMENT_ID in - // _chat.pull-requests.tsx) — a server disconnecting must not move every open tab to a store - // key nobody wrote them under. - const panelId = ThreadId.make("pull-requests-panel"); - const stableRef = scopeThreadRef("pull-requests-panel" as EnvironmentId, panelId); - const fromServerA = { - environmentId: "server-a", - projectId: "project-a", - repository: "pingdotgg/t3code", - number: 1, - }; - const fromServerB = { - environmentId: "server-b", - projectId: "project-b", - repository: "pingdotgg/t3code", - number: 2, - }; - - // Both servers connected: tabs from each open under the one stable ref. - useRightPanelStore.getState().openPullRequest(stableRef, fromServerA); - useRightPanelStore.getState().openPullRequest(stableRef, fromServerB); - - // Server A disconnects. The stable ref does not depend on which servers remain connected, so - // the same lookup still finds both tabs. - const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, stableRef); - expect(state.surfaces.map((surface) => surface.id)).toEqual([ - pullRequestSurfaceId(fromServerA), - pullRequestSurfaceId(fromServerB), - ]); - - // The bug this guards against: a ref keyed by the first capable environment instead of a - // fixed sentinel changes identity when that environment drops out, and a lookup under the new - // key finds nothing even though the tabs are still sitting under the old one. - const refWhileBothConnected = scopeThreadRef("server-a" as EnvironmentId, panelId); - const refAfterServerADisconnects = scopeThreadRef("server-b" as EnvironmentId, panelId); - expect(refWhileBothConnected).not.toEqual(refAfterServerADisconnects); - expect( - selectThreadRightPanelState( - useRightPanelStore.getState().byThreadKey, - refAfterServerADisconnects, - ).surfaces, - ).toEqual([]); - }); - - describe("updatePullRequestTabStatus", () => { - const status = (isDraft: boolean) => ({ - projectId: "project-a", - repository: "pingdotgg/t3code", - number: 4909, - state: "open" as const, - isDraft, - }); - - // Regression for the tab wearing no state: this failed when the status was written under a - // key rebuilt from the pull request while the tab strip reads it under the surface's own id. - it("keys a status under the same id a surface opened from an environment carries", () => { - const target = { - environmentId: "remote", - projectId: "project-a", - repository: "pingdotgg/t3code", - number: 4909, - }; - useRightPanelStore.getState().openPullRequest(refA, target); - const surface = selectSelectedRightPanelSurface( - useRightPanelStore.getState().byThreadKey, - refA, + expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "inline")).toBe( + true, ); - expect(surface).not.toBeNull(); - - const statuses = updatePullRequestTabStatus({}, surface!.id, status(false)); - expect(statuses[surface!.id]).toEqual(status(false)); - }); - - it("keys a status under the same id a thread surface with no environment carries", () => { - const target = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4909 }; - useRightPanelStore.getState().openPullRequest(refA, target); - const surface = selectSelectedRightPanelSurface( - useRightPanelStore.getState().byThreadKey, - refA, + expect(selectThreadPanelOpen(store.threadPanelVisibilityByThreadKey, refA, "popover")).toBe( + false, ); - expect(surface).not.toBeNull(); - const statuses = updatePullRequestTabStatus({}, surface!.id, status(false)); - expect(statuses[surface!.id]).toEqual(status(false)); + store.setThreadPanelOpen(refA, "inline", false); + store.toggleThreadPanel(refA, "popover"); + + expect( + selectThreadPanelVisibility( + useRightPanelStore.getState().threadPanelVisibilityByThreadKey, + refA, + ), + ).toEqual({ inlineOpen: false, popoverOpen: true }); + expect( + selectThreadPanelVisibility( + useRightPanelStore.getState().threadPanelVisibilityByThreadKey, + refB, + ), + ).toEqual({ inlineOpen: true, popoverOpen: false }); }); - it("returns the identical map when the tab's state and draft flag are unchanged", () => { - const first = updatePullRequestTabStatus({}, "pull-request:1", status(false)); - const second = updatePullRequestTabStatus(first, "pull-request:1", status(false)); - expect(second).toBe(first); + it("closes the popover atomically when the real right panel opens", () => { + useRightPanelStore.getState().setThreadPanelOpen(refA, "popover", true); + useRightPanelStore.getState().open(refA, "diff"); + + expect( + selectThreadPanelVisibility( + useRightPanelStore.getState().threadPanelVisibilityByThreadKey, + refA, + ), + ).toEqual({ inlineOpen: true, popoverOpen: false }); }); - it("replaces the entry when the draft flag changes", () => { - const first = updatePullRequestTabStatus({}, "pull-request:1", status(false)); - const second = updatePullRequestTabStatus(first, "pull-request:1", status(true)); - expect(second).not.toBe(first); - expect(second["pull-request:1"]).toEqual(status(true)); + it("keeps an open popover visible by promoting it to inline when the real panel closes", () => { + const store = useRightPanelStore.getState(); + store.open(refA, "diff"); + store.setThreadPanelOpen(refA, "inline", false); + store.setThreadPanelOpen(refA, "popover", true); + store.close(refA); + + expect( + selectThreadPanelVisibility( + useRightPanelStore.getState().threadPanelVisibilityByThreadKey, + refA, + ), + ).toEqual({ inlineOpen: true, popoverOpen: true }); }); - }); - it("tracks one surface per terminal session", () => { - useRightPanelStore.getState().openTerminal(refA, "term-1"); - useRightPanelStore.getState().openTerminal(refA, "term-2"); + it("open sets the active panel for a thread", () => { + useRightPanelStore.getState().open(refA, "preview"); + expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe( + "preview", + ); + expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refB)).toBeNull(); + }); - const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA); - expect(state.surfaces).toEqual([ - { + it("opening a different kind keeps both surfaces and activates the new one", () => { + useRightPanelStore.getState().open(refA, "agents"); + useRightPanelStore.getState().open(refA, "preview"); + expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe( + "preview", + ); + expect( + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces, + ).toHaveLength(2); + }); + + it("reopening an inactive singleton activates its existing surface", () => { + useRightPanelStore.getState().open(refA, "diff"); + useRightPanelStore.getState().open(refA, "agents"); + useRightPanelStore.getState().open(refA, "diff"); + + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "diff", + surfaces: [ + { id: "diff", kind: "diff" }, + { id: "agents", kind: "agents" }, + ], + }); + }); + + it("keeps files as a singleton surface", () => { + useRightPanelStore.getState().open(refA, "files"); + useRightPanelStore.getState().open(refA, "files"); + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "files", + surfaces: [{ id: "files", kind: "files" }], + }); + }); + + it("replaces the standalone explorer with peer file surfaces", () => { + useRightPanelStore.getState().open(refA, "files"); + useRightPanelStore.getState().openFile(refA, "src/index.ts"); + useRightPanelStore.getState().openFile(refA, "src/index.ts"); + useRightPanelStore.getState().openFile(refA, "README.md"); + + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "file:README.md", + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: null, + revealRequestId: 2, + }, + { + id: "file:README.md", + kind: "file", + relativePath: "README.md", + revealLine: null, + revealRequestId: 1, + }, + ], + }); + }); + + it("updates line reveal requests when reopening a file surface", () => { + useRightPanelStore.getState().openFile(refA, "src/index.ts", 42); + useRightPanelStore.getState().openFile(refA, "src/index.ts", 87); + + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "file:src/index.ts", + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: 87, + revealRequestId: 2, + }, + ], + }); + + useRightPanelStore.getState().openFile(refA, "src/index.ts"); + + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "file:src/index.ts", + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: null, + revealRequestId: 3, + }, + ], + }); + }); + + it("removes persisted file surfaces when their workspace no longer exists", () => { + useRightPanelStore.getState().openFile(refA, "src/index.ts"); + useRightPanelStore.getState().open(refA, "agents"); + useRightPanelStore.getState().openFile(refA, "README.md"); + + useRightPanelStore.getState().reconcileFileSurfaces(refA, false); + + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "agents", + surfaces: [{ id: "agents", kind: "agents" }], + }); + + useRightPanelStore.getState().openFile(refB, "conductor.json"); + useRightPanelStore.getState().reconcileFileSurfaces(refB, false); + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refB)).toEqual({ + isOpen: false, + activeSurfaceId: null, + surfaces: [], + }); + }); + + it("close hides the panel without clearing its selected surface", () => { + useRightPanelStore.getState().open(refA, "agents"); + useRightPanelStore.getState().close(refA); + expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull(); + expect( + selectSelectedRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA), + ).toEqual({ id: "agents", kind: "agents" }); + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: false, + activeSurfaceId: "agents", + surfaces: [{ id: "agents", kind: "agents" }], + }); + }); + + it("toggles empty panel visibility without creating a surface", () => { + useRightPanelStore.getState().toggleVisibility(refA); + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: null, + surfaces: [], + }); + + useRightPanelStore.getState().toggleVisibility(refA); + expect(useRightPanelStore.getState().byThreadKey).toEqual({}); + }); + + it("toggle hides the panel without discarding the active surface", () => { + useRightPanelStore.getState().toggle(refA, "diff"); + expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe("diff"); + useRightPanelStore.getState().toggle(refA, "diff"); + expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull(); + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: false, + activeSurfaceId: "diff", + surfaces: [{ id: "diff", kind: "diff" }], + }); + }); + + it("toggle to a different kind switches active", () => { + useRightPanelStore.getState().toggle(refA, "preview"); + useRightPanelStore.getState().toggle(refA, "agents"); + expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBe( + "agents", + ); + }); + + it("removeThread clears persisted state", () => { + useRightPanelStore.getState().open(refA, "agents"); + useRightPanelStore.getState().removeThread(refA); + expect(selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, refA)).toBeNull(); + }); + + it("close on never-opened thread is a no-op", () => { + useRightPanelStore.getState().close(refA); + expect(useRightPanelStore.getState().byThreadKey).toEqual({}); + }); + + it("tracks one surface per browser session", () => { + useRightPanelStore.getState().openBrowser(refA, "tab-a"); + useRightPanelStore.getState().openBrowser(refA, "tab-b"); + + const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA); + expect(state.surfaces.map((surface) => surface.id)).toEqual([ + "browser:tab-a", + "browser:tab-b", + ]); + expect( + selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA), + ).toEqual({ + id: "browser:tab-b", + kind: "preview", + resourceId: "tab-b", + }); + }); + + it("tracks one surface per pull request", () => { + const first = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4909 }; + const second = { projectId: "project-a", repository: "pingdotgg/t3code", number: 4910 }; + useRightPanelStore.getState().openPullRequest(refA, first); + useRightPanelStore.getState().openPullRequest(refA, second); + useRightPanelStore.getState().openPullRequest(refA, first); + + const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA); + expect(state.surfaces.map((surface) => surface.id)).toEqual([ + pullRequestSurfaceId(first), + pullRequestSurfaceId(second), + ]); + expect(state.activeSurfaceId).toBe(pullRequestSurfaceId(first)); + }); + + it("tracks one surface per terminal session", () => { + useRightPanelStore.getState().openTerminal(refA, "term-1"); + useRightPanelStore.getState().openTerminal(refA, "term-2"); + + const state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA); + expect(state.surfaces).toEqual([ + { + id: "terminal:term-1", + kind: "terminal", + resourceId: "term-1", + terminalIds: ["term-1"], + activeTerminalId: "term-1", + }, + { + id: "terminal:term-2", + kind: "terminal", + resourceId: "term-2", + terminalIds: ["term-2"], + activeTerminalId: "term-2", + }, + ]); + expect(state.activeSurfaceId).toBe("terminal:term-2"); + }); + + it("tracks split panes and the active pane within a terminal surface", () => { + useRightPanelStore.getState().openTerminal(refA, "term-1"); + useRightPanelStore.getState().splitTerminal(refA, "terminal:term-1", "term-2"); + + expect( + selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA), + ).toEqual({ id: "terminal:term-1", kind: "terminal", resourceId: "term-1", - terminalIds: ["term-1"], - activeTerminalId: "term-1", - }, - { - id: "terminal:term-2", + terminalIds: ["term-1", "term-2"], + activeTerminalId: "term-2", + }); + + useRightPanelStore.getState().activateTerminal(refA, "terminal:term-1", "term-1"); + useRightPanelStore.getState().closeTerminal(refA, "terminal:term-1", "term-1"); + expect( + selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA), + ).toEqual({ + id: "terminal:term-1", kind: "terminal", - resourceId: "term-2", + resourceId: "term-1", terminalIds: ["term-2"], activeTerminalId: "term-2", - }, - ]); - expect(state.activeSurfaceId).toBe("terminal:term-2"); - }); - - it("tracks split panes and the active pane within a terminal surface", () => { - useRightPanelStore.getState().openTerminal(refA, "term-1"); - useRightPanelStore.getState().splitTerminal(refA, "terminal:term-1", "term-2"); - - expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - id: "terminal:term-1", - kind: "terminal", - resourceId: "term-1", - terminalIds: ["term-1", "term-2"], - activeTerminalId: "term-2", + }); }); - useRightPanelStore.getState().activateTerminal(refA, "terminal:term-1", "term-1"); - useRightPanelStore.getState().closeTerminal(refA, "terminal:term-1", "term-1"); - expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - id: "terminal:term-1", - kind: "terminal", - resourceId: "term-1", - terminalIds: ["term-2"], - activeTerminalId: "term-2", + it("tracks vertical layout for a terminal surface", () => { + useRightPanelStore.getState().openTerminal(refA, "term-1"); + useRightPanelStore.getState().splitTerminal(refA, "terminal:term-1", "term-2", "vertical"); + + expect( + selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA), + ).toEqual({ + id: "terminal:term-1", + kind: "terminal", + resourceId: "term-1", + terminalIds: ["term-1", "term-2"], + activeTerminalId: "term-2", + splitDirection: "vertical", + }); }); - }); - it("tracks vertical layout for a terminal surface", () => { - useRightPanelStore.getState().openTerminal(refA, "term-1"); - useRightPanelStore.getState().splitTerminal(refA, "terminal:term-1", "term-2", "vertical"); + it("closing the final terminal pane removes its surface and closes the panel", () => { + useRightPanelStore.getState().openTerminal(refA, "term-1"); + useRightPanelStore.getState().closeTerminal(refA, "terminal:term-1", "term-1"); - expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - id: "terminal:term-1", - kind: "terminal", - resourceId: "term-1", - terminalIds: ["term-1", "term-2"], - activeTerminalId: "term-2", - splitDirection: "vertical", + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: false, + activeSurfaceId: null, + surfaces: [], + }); }); - }); - it("closing the final terminal pane removes its surface and closes the panel", () => { - useRightPanelStore.getState().openTerminal(refA, "term-1"); - useRightPanelStore.getState().closeTerminal(refA, "terminal:term-1", "term-1"); + it("closing the active surface activates a neighboring surface", () => { + useRightPanelStore.getState().openBrowser(refA, "tab-a"); + useRightPanelStore.getState().openTerminal(refA, "term-1"); + useRightPanelStore.getState().closeSurface(refA, "terminal:term-1"); - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: false, - activeSurfaceId: null, - surfaces: [], + expect( + selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)?.id, + ).toBe("browser:tab-a"); }); - }); - it("closing the active surface activates a neighboring surface", () => { - useRightPanelStore.getState().openBrowser(refA, "tab-a"); - useRightPanelStore.getState().openTerminal(refA, "term-1"); - useRightPanelStore.getState().closeSurface(refA, "terminal:term-1"); + it("closing the final surface closes the panel", () => { + useRightPanelStore.getState().openTerminal(refA, "term-1"); + useRightPanelStore.getState().closeSurface(refA, "terminal:term-1"); - expect(selectActiveRightPanelSurface(useRightPanelStore.getState().byThreadKey, refA)?.id).toBe( - "browser:tab-a", - ); - }); - - it("closing the final surface closes the panel", () => { - useRightPanelStore.getState().openTerminal(refA, "term-1"); - useRightPanelStore.getState().closeSurface(refA, "terminal:term-1"); - - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: false, - activeSurfaceId: null, - surfaces: [], + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: false, + activeSurfaceId: null, + surfaces: [], + }); }); - }); - it("closing other surfaces keeps the selected surface active", () => { - useRightPanelStore.getState().openBrowser(refA, "tab-a"); - useRightPanelStore.getState().openFile(refA, "src/index.ts"); - useRightPanelStore.getState().openTerminal(refA, "term-1"); + it("closing other surfaces keeps the selected surface active", () => { + useRightPanelStore.getState().openBrowser(refA, "tab-a"); + useRightPanelStore.getState().openFile(refA, "src/index.ts"); + useRightPanelStore.getState().openTerminal(refA, "term-1"); - useRightPanelStore.getState().closeOtherSurfaces(refA, "file:src/index.ts"); + useRightPanelStore.getState().closeOtherSurfaces(refA, "file:src/index.ts"); - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: true, - activeSurfaceId: "file:src/index.ts", - surfaces: [ - { - id: "file:src/index.ts", - kind: "file", - relativePath: "src/index.ts", - revealLine: null, - revealRequestId: 1, - }, - ], + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "file:src/index.ts", + surfaces: [ + { + id: "file:src/index.ts", + kind: "file", + relativePath: "src/index.ts", + revealLine: null, + revealRequestId: 1, + }, + ], + }); }); - }); - it("closing surfaces to the right activates the selected surface when active was removed", () => { - useRightPanelStore.getState().openBrowser(refA, "tab-a"); - useRightPanelStore.getState().openFile(refA, "src/index.ts"); - useRightPanelStore.getState().openTerminal(refA, "term-1"); + it("closing surfaces to the right activates the selected surface when active was removed", () => { + useRightPanelStore.getState().openBrowser(refA, "tab-a"); + useRightPanelStore.getState().openFile(refA, "src/index.ts"); + useRightPanelStore.getState().openTerminal(refA, "term-1"); - useRightPanelStore.getState().closeSurfacesToRight(refA, "browser:tab-a"); + useRightPanelStore.getState().closeSurfacesToRight(refA, "browser:tab-a"); - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: true, - activeSurfaceId: "browser:tab-a", - surfaces: [{ id: "browser:tab-a", kind: "preview", resourceId: "tab-a" }], + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: true, + activeSurfaceId: "browser:tab-a", + surfaces: [{ id: "browser:tab-a", kind: "preview", resourceId: "tab-a" }], + }); }); - }); - it("closing all surfaces closes the panel", () => { - useRightPanelStore.getState().openBrowser(refA, "tab-a"); - useRightPanelStore.getState().openFile(refA, "src/index.ts"); + it("closing all surfaces closes the panel", () => { + useRightPanelStore.getState().openBrowser(refA, "tab-a"); + useRightPanelStore.getState().openFile(refA, "src/index.ts"); - useRightPanelStore.getState().closeAllSurfaces(refA); + useRightPanelStore.getState().closeAllSurfaces(refA); - expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ - isOpen: false, - activeSurfaceId: null, - surfaces: [], + expect(selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA)).toEqual({ + isOpen: false, + activeSurfaceId: null, + surfaces: [], + }); }); - }); - it("reconciles browser surfaces without deleting other surface kinds", () => { - useRightPanelStore.getState().openTerminal(refA, "term-1"); - useRightPanelStore.getState().openBrowser(refA, "tab-a"); - useRightPanelStore.getState().openBrowser(refA, "tab-b"); - useRightPanelStore.getState().reconcileBrowserSurfaces(refA, ["tab-b", "tab-c"]); + it("reconciles browser surfaces without deleting other surface kinds", () => { + useRightPanelStore.getState().openTerminal(refA, "term-1"); + useRightPanelStore.getState().openBrowser(refA, "tab-a"); + useRightPanelStore.getState().openBrowser(refA, "tab-b"); + useRightPanelStore.getState().reconcileBrowserSurfaces(refA, ["tab-b", "tab-c"]); - expect( - selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces.map( - (surface) => surface.id, - ), - ).toEqual(["terminal:term-1", "browser:tab-b", "browser:tab-c"]); + expect( + selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces.map( + (surface) => surface.id, + ), + ).toEqual(["terminal:term-1", "browser:tab-b", "browser:tab-c"]); + }); }); }); diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index c59c88bde5..6326088dc1 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -15,27 +15,18 @@ import { Route as PairRouteImport } from './routes/pair' import { Route as ConnectRouteImport } from './routes/connect' import { Route as ChatRouteImport } from './routes/_chat' import { Route as ChatIndexRouteImport } from './routes/_chat.index' -import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control' import { Route as SettingsScheduledTasksRouteImport } from './routes/settings.scheduled-tasks' +import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control' import { Route as SettingsProvidersRouteImport } from './routes/settings.providers' import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings' import { Route as SettingsGeneralRouteImport } from './routes/settings.general' import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics' import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections' import { Route as SettingsArchivedRouteImport } from './routes/settings.archived' -<<<<<<< HEAD -<<<<<<< HEAD import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance' import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey' import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback' import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-requests' -import { Route as DebugOrchestrationV2RouteImport } from './routes/debug.orchestration-v2' -======= ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= -import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance' -import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback' ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId' import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId' @@ -68,16 +59,16 @@ const ChatIndexRoute = ChatIndexRouteImport.update({ path: '/', getParentRoute: () => ChatRoute, } as any) -const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({ - id: '/source-control', - path: '/source-control', - getParentRoute: () => SettingsRoute, -} as any) const SettingsScheduledTasksRoute = SettingsScheduledTasksRouteImport.update({ id: '/scheduled-tasks', path: '/scheduled-tasks', getParentRoute: () => SettingsRoute, } as any) +const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({ + id: '/source-control', + path: '/source-control', + getParentRoute: () => SettingsRoute, +} as any) const SettingsProvidersRoute = SettingsProvidersRouteImport.update({ id: '/providers', path: '/providers', @@ -108,16 +99,11 @@ const SettingsArchivedRoute = SettingsArchivedRouteImport.update({ path: '/archived', getParentRoute: () => SettingsRoute, } as any) -<<<<<<< HEAD -<<<<<<< HEAD -======= ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) const SettingsAppearanceRoute = SettingsAppearanceRouteImport.update({ id: '/appearance', path: '/appearance', getParentRoute: () => SettingsRoute, } as any) -<<<<<<< HEAD const ProjectsProjectKeyRoute = ProjectsProjectKeyRouteImport.update({ id: '/projects/$projectKey', path: '/projects/$projectKey', @@ -126,9 +112,6 @@ const ProjectsProjectKeyRoute = ProjectsProjectKeyRouteImport.update({ const ConnectCallbackRoute = ConnectCallbackRouteImport.update({ id: '/connect_/callback', path: '/connect/callback', -const DebugOrchestrationV2Route = DebugOrchestrationV2RouteImport.update({ - id: '/debug/orchestration-v2', - path: '/debug/orchestration-v2', getParentRoute: () => rootRouteImport, } as any) const ChatPullRequestsRoute = ChatPullRequestsRouteImport.update({ @@ -136,15 +119,6 @@ const ChatPullRequestsRoute = ChatPullRequestsRouteImport.update({ path: '/pull-requests', getParentRoute: () => ChatRoute, } as any) -======= ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= -const ConnectCallbackRoute = ConnectCallbackRouteImport.update({ - id: '/connect_/callback', - path: '/connect/callback', - getParentRoute: () => rootRouteImport, -} as any) ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) const ChatDraftDraftIdRoute = ChatDraftDraftIdRouteImport.update({ id: '/draft/$draftId', path: '/draft/$draftId', @@ -162,20 +136,11 @@ export interface FileRoutesByFullPath { '/connect': typeof ConnectRoute '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren -<<<<<<< HEAD -<<<<<<< HEAD '/usage': typeof UsageRoute '/pull-requests': typeof ChatPullRequestsRoute '/connect/callback': typeof ConnectCallbackRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/settings/appearance': typeof SettingsAppearanceRoute - '/debug/orchestration-v2': typeof DebugOrchestrationV2Route -======= ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= - '/connect/callback': typeof ConnectCallbackRoute - '/settings/appearance': typeof SettingsAppearanceRoute ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) '/settings/archived': typeof SettingsArchivedRoute '/settings/connections': typeof SettingsConnectionsRoute '/settings/diagnostics': typeof SettingsDiagnosticsRoute @@ -191,20 +156,11 @@ export interface FileRoutesByTo { '/connect': typeof ConnectRoute '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren -<<<<<<< HEAD -<<<<<<< HEAD '/usage': typeof UsageRoute '/pull-requests': typeof ChatPullRequestsRoute '/connect/callback': typeof ConnectCallbackRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/settings/appearance': typeof SettingsAppearanceRoute - '/debug/orchestration-v2': typeof DebugOrchestrationV2Route -======= ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= - '/connect/callback': typeof ConnectCallbackRoute - '/settings/appearance': typeof SettingsAppearanceRoute ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) '/settings/archived': typeof SettingsArchivedRoute '/settings/connections': typeof SettingsConnectionsRoute '/settings/diagnostics': typeof SettingsDiagnosticsRoute @@ -223,20 +179,11 @@ export interface FileRoutesById { '/connect': typeof ConnectRoute '/pair': typeof PairRoute '/settings': typeof SettingsRouteWithChildren -<<<<<<< HEAD -<<<<<<< HEAD '/usage': typeof UsageRoute '/_chat/pull-requests': typeof ChatPullRequestsRoute '/connect_/callback': typeof ConnectCallbackRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/settings/appearance': typeof SettingsAppearanceRoute - '/debug/orchestration-v2': typeof DebugOrchestrationV2Route -======= ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= - '/connect_/callback': typeof ConnectCallbackRoute - '/settings/appearance': typeof SettingsAppearanceRoute ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) '/settings/archived': typeof SettingsArchivedRoute '/settings/connections': typeof SettingsConnectionsRoute '/settings/diagnostics': typeof SettingsDiagnosticsRoute @@ -256,20 +203,11 @@ export interface FileRouteTypes { | '/connect' | '/pair' | '/settings' -<<<<<<< HEAD -<<<<<<< HEAD | '/usage' | '/pull-requests' | '/connect/callback' | '/projects/$projectKey' | '/settings/appearance' - | '/debug/orchestration-v2' -======= ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= - | '/connect/callback' - | '/settings/appearance' ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) | '/settings/archived' | '/settings/connections' | '/settings/diagnostics' @@ -285,20 +223,11 @@ export interface FileRouteTypes { | '/connect' | '/pair' | '/settings' -<<<<<<< HEAD -<<<<<<< HEAD | '/usage' | '/pull-requests' | '/connect/callback' | '/projects/$projectKey' | '/settings/appearance' - | '/debug/orchestration-v2' -======= ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= - | '/connect/callback' - | '/settings/appearance' ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) | '/settings/archived' | '/settings/connections' | '/settings/diagnostics' @@ -316,20 +245,11 @@ export interface FileRouteTypes { | '/connect' | '/pair' | '/settings' -<<<<<<< HEAD -<<<<<<< HEAD | '/usage' | '/_chat/pull-requests' | '/connect_/callback' | '/projects/$projectKey' | '/settings/appearance' - | '/debug/orchestration-v2' -======= ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= - | '/connect_/callback' - | '/settings/appearance' ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) | '/settings/archived' | '/settings/connections' | '/settings/diagnostics' @@ -348,17 +268,9 @@ export interface RootRouteChildren { ConnectRoute: typeof ConnectRoute PairRoute: typeof PairRoute SettingsRoute: typeof SettingsRouteWithChildren -<<<<<<< HEAD -<<<<<<< HEAD UsageRoute: typeof UsageRoute ConnectCallbackRoute: typeof ConnectCallbackRoute ProjectsProjectKeyRoute: typeof ProjectsProjectKeyRoute - DebugOrchestrationV2Route: typeof DebugOrchestrationV2Route -======= ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= - ConnectCallbackRoute: typeof ConnectCallbackRoute ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) } declare module '@tanstack/react-router' { @@ -405,13 +317,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ChatIndexRouteImport parentRoute: typeof ChatRoute } - '/settings/source-control': { - id: '/settings/source-control' - path: '/source-control' - fullPath: '/settings/source-control' - preLoaderRoute: typeof SettingsSourceControlRouteImport - parentRoute: typeof SettingsRoute - } '/settings/scheduled-tasks': { id: '/settings/scheduled-tasks' path: '/scheduled-tasks' @@ -419,6 +324,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SettingsScheduledTasksRouteImport parentRoute: typeof SettingsRoute } + '/settings/source-control': { + id: '/settings/source-control' + path: '/source-control' + fullPath: '/settings/source-control' + preLoaderRoute: typeof SettingsSourceControlRouteImport + parentRoute: typeof SettingsRoute + } '/settings/providers': { id: '/settings/providers' path: '/providers' @@ -461,10 +373,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SettingsArchivedRouteImport parentRoute: typeof SettingsRoute } -<<<<<<< HEAD -<<<<<<< HEAD -======= ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) '/settings/appearance': { id: '/settings/appearance' path: '/appearance' @@ -472,7 +380,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SettingsAppearanceRouteImport parentRoute: typeof SettingsRoute } -<<<<<<< HEAD '/projects/$projectKey': { id: '/projects/$projectKey' path: '/projects/$projectKey' @@ -480,19 +387,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ProjectsProjectKeyRouteImport parentRoute: typeof rootRouteImport } -======= ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) '/connect_/callback': { id: '/connect_/callback' path: '/connect/callback' fullPath: '/connect/callback' preLoaderRoute: typeof ConnectCallbackRouteImport -<<<<<<< HEAD - '/debug/orchestration-v2': { - id: '/debug/orchestration-v2' - path: '/debug/orchestration-v2' - fullPath: '/debug/orchestration-v2' - preLoaderRoute: typeof DebugOrchestrationV2RouteImport parentRoute: typeof rootRouteImport } '/_chat/pull-requests': { @@ -502,12 +401,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ChatPullRequestsRouteImport parentRoute: typeof ChatRoute } -======= ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= - parentRoute: typeof rootRouteImport - } ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) '/_chat/draft/$draftId': { id: '/_chat/draft/$draftId' path: '/draft/$draftId' @@ -574,17 +467,9 @@ const rootRouteChildren: RootRouteChildren = { ConnectRoute: ConnectRoute, PairRoute: PairRoute, SettingsRoute: SettingsRouteWithChildren, -<<<<<<< HEAD -<<<<<<< HEAD UsageRoute: UsageRoute, ConnectCallbackRoute: ConnectCallbackRoute, ProjectsProjectKeyRoute: ProjectsProjectKeyRoute, - DebugOrchestrationV2Route: DebugOrchestrationV2Route, -======= ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) -======= - ConnectCallbackRoute: ConnectCallbackRoute, ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/apps/web/src/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsx index aee41fb696..da04bd5166 100644 --- a/apps/web/src/routes/_chat.pull-requests.tsx +++ b/apps/web/src/routes/_chat.pull-requests.tsx @@ -1291,9 +1291,15 @@ function PullRequestsRouteView() { const panelToggleControls = ( undefined} rightPanelAvailable={rightPanelState.surfaces.length > 0} rightPanelOpen={rightPanelState.isOpen} rightPanelShortcutLabel={null} diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 5b103316f2..e5a83827f4 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -185,7 +185,6 @@ export function readEnvironmentSupportsTitleRegeneration(environmentId: Environm ); } -<<<<<<< HEAD /** Whether the environment's server understands thread.pin.reorder (and orderKey on thread.pin). Same version-skew contract as settlement. */ export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId): boolean { @@ -195,12 +194,8 @@ export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId): ); } -export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null { - return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref)); -======= export function readThreadProjection(ref: ScopedThreadRef): EnvironmentThread | null { return appAtomRegistry.get(environmentThreadDetails.threadAtom(ref)); ->>>>>>> d849d1caf9 (Retire V1 client orchestration parity) } /** Whether the environment's server understands thread.settle/unsettle. diff --git a/apps/web/src/state/queries.ts b/apps/web/src/state/queries.ts index 576d780249..91ee86b337 100644 --- a/apps/web/src/state/queries.ts +++ b/apps/web/src/state/queries.ts @@ -52,7 +52,7 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({ labelPrefix: "web:thread-search", }); -function useDebouncedValue
    (value: A, delayMs: number): A { +export function useDebouncedValue(value: A, delayMs: number): A { const [debounced, setDebounced] = useState(value); useEffect(() => { diff --git a/docs/README.md b/docs/README.md index 9b8641e99f..adaebd5bee 100644 --- a/docs/README.md +++ b/docs/README.md @@ -5,12 +5,9 @@ - [Install and first run](./user/install.md) - [Permission modes](./user/permission-modes.md) - [Keyboard shortcuts](./user/keybindings.md) -<<<<<<< HEAD - [Organizing threads](./user/thread-sidebar.md) - [Review usage](./user/usage.md) - [Customize a project icon](./user/project-settings.md) -======= ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) - [Remote access](./user/remote-access.md) - [Appearance](./user/appearance.md) - [Keeping app and server in sync](./user/updating.md) @@ -46,7 +43,6 @@ policy in [CONTRIBUTING.md](../CONTRIBUTING.md); agent rules in [AGENTS.md](../A - [Observability](./operations/observability.md) - [Relay observability](./operations/relay-observability.md) - [Mobile app store screenshots](./operations/mobile-app-store-screenshots.md) -<<<<<<< HEAD - [Getting started](./getting-started/quick-start.md) - [Architecture](./architecture/overview.md) - [T3 Connect](./cloud/t3-connect-clerk.md) @@ -57,5 +53,3 @@ policy in [CONTRIBUTING.md](../CONTRIBUTING.md); agent rules in [AGENTS.md](../A [Cursor](./providers/cursor.md) - [Reference](./reference/encyclopedia.md) - [User guides](./user/keybindings.md) -======= ->>>>>>> 290392fac9 (fix: reconcile rebase with latest main) diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 536cd00f69..c3753998ff 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -77,9 +77,17 @@ export interface UnsettleThreadInput extends ThreadCommandInput { readonly reason: "user"; } -export type PinThreadInput = ThreadCommandInput; +export interface PinThreadInput extends ThreadCommandInput { + /** Initial slot in the user-arranged pinned order; omit to pin keyless. */ + readonly orderKey?: string; +} export type UnpinThreadInput = ThreadCommandInput; +export interface ReorderPinnedThreadInput extends ThreadCommandInput { + /** Fractional-index key that sorts between the drop position's neighbors. */ + readonly orderKey: string; +} + export interface SnoozeThreadInput extends ThreadCommandInput { readonly snoozedUntil: string; } @@ -384,7 +392,25 @@ export const settleThread = Effect.fn("EnvironmentCommands.settleThread")(functi export const pinThread = Effect.fn("EnvironmentCommands.pinThread")(function* ( input: PinThreadInput, ) { - return yield* simpleThreadCommand("thread.pin", input); + const commandId = yield* allocateCommandId(input); + return yield* dispatch({ + type: "thread.pin", + commandId, + threadId: input.threadId, + ...(input.orderKey === undefined ? {} : { orderKey: input.orderKey }), + }); +}); + +export const reorderPinnedThread = Effect.fn("EnvironmentCommands.reorderPinnedThread")(function* ( + input: ReorderPinnedThreadInput, +) { + const commandId = yield* allocateCommandId(input); + return yield* dispatch({ + type: "thread.pin.reorder", + commandId, + threadId: input.threadId, + orderKey: input.orderKey, + }); }); export const unpinThread = Effect.fn("EnvironmentCommands.unpinThread")(function* ( diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 9ac77cda10..27758d2484 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -99,6 +99,8 @@ export interface EnvironmentThreadShell { readonly snoozedUntil: string | null; readonly snoozedAt: string | null; readonly pinnedAt: string | null; + /** Slot in the user-arranged pinned order; null for keyless (legacy) pins. */ + readonly pinOrderKey: string | null; /** * Server-tracked visited watermark. `undefined` means the environment's * server predates visited tracking and clients should fall back to any @@ -210,6 +212,7 @@ export function presentThreadShell( snoozedUntil: nullableIso(thread.snoozedUntil ?? null), snoozedAt: nullableIso(thread.snoozedAt ?? null), pinnedAt: nullableIso(thread.pinnedAt ?? null), + pinOrderKey: thread.pinOrderKey ?? null, ...(thread.lastVisitedAt === undefined ? {} : { lastVisitedAt: nullableIso(thread.lastVisitedAt) }), diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts index 8ca83a590f..98144197a4 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -114,6 +114,7 @@ export function applyOrchestrationV2ProjectionEvent( case "thread.unsnoozed": case "thread.pinned": case "thread.unpinned": + case "thread.pin-reordered": case "thread.metadata-updated": case "thread.runtime-mode-updated": case "thread.interaction-mode-updated": diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 3d7e7c8b40..3a594aaf9c 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -708,6 +708,7 @@ export function createServerEnvironmentAtoms( label: "environment-data:server:usage-summary", tag: WS_METHODS.serverGetUsageSummary, staleTimeMs: 60_000, + }), resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, { label: "environment-data:server:resource-telemetry", tag: WS_METHODS.subscribeResourceTelemetry, diff --git a/packages/contracts/src/applicationEvent.ts b/packages/contracts/src/applicationEvent.ts index d5b118f793..e90a0738e6 100644 --- a/packages/contracts/src/applicationEvent.ts +++ b/packages/contracts/src/applicationEvent.ts @@ -10,7 +10,7 @@ import { ProviderItemId, TrimmedNonEmptyString, } from "./baseSchemas.ts"; -import { RepositoryIdentity } from "./environment.ts"; +import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts"; import { ModelSelection } from "./modelSelection.ts"; import type { OrchestrationV2StoredEvent } from "./orchestrationV2.ts"; import { ProjectScript } from "./project.ts"; @@ -31,6 +31,11 @@ export const ApplicationProjectCreatedPayload = Schema.Struct({ workspaceRoot: TrimmedNonEmptyString, repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)), defaultModelSelection: Schema.NullOr(ModelSelection), + // Per-project override for where new threads start; optional so persisted + // events from older servers still decode. + defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)), + // Optional so persisted events from older servers still decode. + faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), scripts: Schema.Array(ProjectScript), createdAt: IsoDateTime, updatedAt: IsoDateTime, @@ -43,6 +48,9 @@ export const ApplicationProjectMetaUpdatedPayload = Schema.Struct({ workspaceRoot: Schema.optional(TrimmedNonEmptyString), repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)), defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)), + // Absent = leave unchanged; null = clear the override. + defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)), + faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), scripts: Schema.optional(Schema.Array(ProjectScript)), updatedAt: IsoDateTime, }); diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 74ee89e23a..e88d5edbb4 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -27,7 +27,8 @@ import { RuntimeMode, } from "./providerPolicy.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; -import { Project, ProjectScript } from "./project.ts"; +import { Project, ProjectScript, ProjectScriptIcon } from "./project.ts"; +import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts"; import { OrchestrationProjectShell } from "./orchestrationProject.ts"; import { ApplicationEventMetadata, @@ -59,36 +60,6 @@ export { export const CorrelationId = CommandId; export type CorrelationId = typeof CorrelationId.Type; -export const ProjectScriptIcon = Schema.Literals([ - "play", - "test", - "lint", - "configure", - "build", - "debug", -]); -export type ProjectScriptIcon = typeof ProjectScriptIcon.Type; - -export const ProjectScript = Schema.Struct({ - id: TrimmedNonEmptyString, - name: TrimmedNonEmptyString, - command: TrimmedNonEmptyString, - icon: ProjectScriptIcon, - runOnWorktreeCreate: Schema.Boolean, - /** - * URL to open in the in-app browser preview when this script runs (or - * when the user explicitly requests a preview). Optional; only honored on - * the desktop build. - */ - previewUrl: Schema.optional(TrimmedNonEmptyString), - /** - * When true, automatically open the preview panel pointed at `previewUrl` - * the moment this script starts. Ignored without `previewUrl` or on web. - */ - autoOpenPreview: Schema.optional(Schema.Boolean), -}); -export type ProjectScript = typeof ProjectScript.Type; - export const ProjectFaviconPath = TrimmedNonEmptyString.check( Schema.isMaxLength(1024), Schema.isPattern(/\.(?:avif|gif|ico|jpe?g|png|svg|webp)$/i), diff --git a/packages/contracts/src/orchestrationProject.ts b/packages/contracts/src/orchestrationProject.ts index f17ad64e0a..682042bf47 100644 --- a/packages/contracts/src/orchestrationProject.ts +++ b/packages/contracts/src/orchestrationProject.ts @@ -1,7 +1,7 @@ import * as Schema from "effect/Schema"; import { IsoDateTime, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts"; -import { RepositoryIdentity } from "./environment.ts"; +import { RepositoryIdentity, ThreadEnvMode } from "./environment.ts"; import { ModelSelection } from "./modelSelection.ts"; import { ProjectScript } from "./project.ts"; @@ -12,6 +12,11 @@ export const OrchestrationProjectShell = Schema.Struct({ workspaceRoot: TrimmedNonEmptyString, repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)), defaultModelSelection: Schema.NullOr(ModelSelection), + // Per-project override for where new threads start. Null/absent means + // "no override": clients fall back to t3.json, then the global setting. + defaultThreadEnvMode: Schema.optional(Schema.NullOr(ThreadEnvMode)), + // Optional on the wire so cached snapshots from older servers still decode. + faviconPath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), scripts: Schema.Array(ProjectScript), createdAt: IsoDateTime, updatedAt: IsoDateTime, diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index c4c0d018e0..90b7f90949 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -325,6 +325,9 @@ export const OrchestrationV2AppThread = Schema.Struct({ snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), + // Fractional-index slot in the user-arranged pinned order. Optional so + // payloads from pre-reorder servers still decode. + pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe( Schema.withDecodingDefault(Effect.succeed(null)), ), @@ -1098,6 +1101,7 @@ export const OrchestrationV2DomainEvent = Schema.Union([ "thread.unsnoozed", "thread.pinned", "thread.unpinned", + "thread.pin-reordered", "thread.visited", "thread.marked-unread", "thread.metadata-updated", @@ -1301,6 +1305,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), /** Omitted by servers that predate thread pinning. */ pinnedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), + /** Slot in the user-arranged pinned order; omitted by pre-reorder servers. */ + pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), /** * Omitted by servers that predate server-side visited tracking; clients fall * back to their local visited state when the field is absent. @@ -1818,6 +1824,7 @@ export const OrchestrationV2DomainEventJson = Schema.Union([ "thread.unsnoozed", "thread.pinned", "thread.unpinned", + "thread.pin-reordered", "thread.visited", "thread.marked-unread", "thread.metadata-updated", @@ -1994,12 +2001,26 @@ export const OrchestrationV2Command = Schema.Union([ type: Schema.Literal("thread.pin"), commandId: CommandId, threadId: ThreadId, + // Initial slot in the user-arranged pinned order (see thread.pin.reorder). + // Optional: clients on pre-reorder servers omit it, and the pinned block + // falls back to creation order for keyless threads. + orderKey: Schema.optional(TrimmedNonEmptyString), }), Schema.Struct({ type: Schema.Literal("thread.unpin"), commandId: CommandId, threadId: ThreadId, }), + Schema.Struct({ + type: Schema.Literal("thread.pin.reorder"), + commandId: CommandId, + threadId: ThreadId, + // Fractional-index key: pinned threads sort lexicographically by these + // keys, so a drag writes one key to one thread — neighbors are never + // touched. Clients compute a key that sorts between the dropped + // position's neighbors. + orderKey: TrimmedNonEmptyString, + }), Schema.Struct({ type: Schema.Literal("thread.visit"), commandId: CommandId, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 54d57666cb..dad02192a6 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -96,6 +96,7 @@ import { RelayClientInstallProgressEventSchema, RelayClientStatusSchema, } from "./relayClient.ts"; +import { ORCHESTRATION_V2_WS_METHODS, OrchestrationGetWorkflowScriptError, OrchestrationV2DispatchCommandError, @@ -104,11 +105,6 @@ import { OrchestrationV2RpcSchemas, OrchestrationV2ThreadLaunchError, } from "./orchestrationV2.ts"; -import { - RelayClientInstallFailedError, - RelayClientInstallProgressEventSchema, - RelayClientStatusSchema, -} from "./relayClient.ts"; import { ProjectListEntriesError, ProjectListEntriesInput,