diff --git a/apps/server/src/assets/AttachmentUpload.ts b/apps/server/src/assets/AttachmentUpload.ts index f3cc445abf55d..d1a1b055bfe11 100644 --- a/apps/server/src/assets/AttachmentUpload.ts +++ b/apps/server/src/assets/AttachmentUpload.ts @@ -230,8 +230,9 @@ export const storeAttachmentUpload = Effect.fn("AttachmentUpload.store")(functio }), }).pipe( Effect.as(true), - Effect.catch((error) => - error.reason._tag === "AlreadyExists" ? Effect.succeed(false) : Effect.fail(error), + Effect.catchIf( + (error) => error.reason._tag === "AlreadyExists", + () => Effect.succeed(false), ), ); }), diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 21d111956a5ea..c14b782e1bddb 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -307,8 +307,8 @@ export const make = Effect.gen(function* () { ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input))); return GitWorkflowService.of({ - isRepository: (cwd) => - registry.detect({ cwd }).pipe( + isRepository: Effect.fn("GitWorkflowService.isRepository")(function (cwd) { + return registry.detect({ cwd }).pipe( Effect.map((handle) => handle?.kind === "git"), Effect.mapError( (cause) => @@ -319,9 +319,10 @@ export const make = Effect.gen(function* () { cause, }), ), - ), - hasCommit: (input) => - ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe( + ); + }), + hasCommit: Effect.fn("GitWorkflowService.hasCommit")(function (input) { + return ensureGitCommand("GitWorkflowService.hasCommit", input.cwd).pipe( Effect.andThen( git.execute({ operation: "GitWorkflowService.hasCommit", @@ -331,10 +332,11 @@ export const make = Effect.gen(function* () { }), ), Effect.map((result) => result.exitCode === 0), - ), - hasRefNamed: (input) => + ); + }), + hasRefNamed: Effect.fn("GitWorkflowService.hasRefNamed")(function (input) { // Pattern characters would widen the ref match. - /[*?[\\]/.test(input.refName) + return /[*?[\\]/.test(input.refName) ? Effect.succeed(false) : ensureGitCommand("GitWorkflowService.hasRefNamed", input.cwd).pipe( Effect.andThen( @@ -350,45 +352,52 @@ export const make = Effect.gen(function* () { }), ), Effect.map((result) => result.stdout.trim().length > 0), - ), - status: (input) => - detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe( + ); + }), + status: Effect.fn("GitWorkflowService.status")(function (input) { + return detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe( Effect.flatMap((isGitRepository) => isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()), ), - ), - localStatus: (input) => - detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe( + ); + }), + localStatus: Effect.fn("GitWorkflowService.localStatus")(function (input) { + return detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe( Effect.flatMap((isGitRepository) => isGitRepository ? gitManager.localStatus(input) : Effect.succeed(nonRepositoryLocalStatus()), ), - ), - remoteStatus: (input, options) => - detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe( + ); + }), + remoteStatus: Effect.fn("GitWorkflowService.remoteStatus")(function (input, options) { + return detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe( Effect.flatMap((isGitRepository) => isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null), ), - ), + ); + }), invalidateLocalStatus: gitManager.invalidateLocalStatus, invalidateRemoteStatus: gitManager.invalidateRemoteStatus, invalidateStatus: gitManager.invalidateStatus, // Coder: route these driver seams through the same Git-only command guard. - moveWorktree: (input) => - ensureGitCommand("GitWorkflowService.moveWorktree", input.cwd).pipe( + moveWorktree: Effect.fn("GitWorkflowService.moveWorktree")(function (input) { + return ensureGitCommand("GitWorkflowService.moveWorktree", input.cwd).pipe( Effect.andThen(git.moveWorktree(input)), - ), - localRefStatus: (input) => - ensureGitCommand("GitWorkflowService.localRefStatus", input.cwd).pipe( + ); + }), + localRefStatus: Effect.fn("GitWorkflowService.localRefStatus")(function (input) { + return ensureGitCommand("GitWorkflowService.localRefStatus", input.cwd).pipe( Effect.andThen(git.refStatusLocal(input.cwd)), - ), - pullCurrentBranch: (cwd) => - ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe( + ); + }), + pullCurrentBranch: Effect.fn("GitWorkflowService.pullCurrentBranch")(function (cwd) { + return ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe( Effect.andThen(git.pullCurrentBranch(cwd)), - ), - runStackedAction: (input, options) => - ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe( + ); + }), + runStackedAction: Effect.fn("GitWorkflowService.runStackedAction")(function (input, options) { + return ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe( Effect.flatMap((handle) => input.featureBranch ? withCheckoutLease( @@ -397,90 +406,115 @@ export const make = Effect.gen(function* () { ) : gitManager.runStackedAction(input, options), ), - ), + ); + }), resolvePullRequest: routeGitManager( "GitWorkflowService.resolvePullRequest", gitManager.resolvePullRequest, ), - preparePullRequestThread: (input) => - ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe( - Effect.flatMap((handle) => - input.mode === "local" - ? withCheckoutLease( - handle.repository.rootPath, - gitManager.preparePullRequestThread(input), - ) - : gitManager.preparePullRequestThread(input), - ), - ), - listRefs: (input) => - detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe( + preparePullRequestThread: Effect.fn("GitWorkflowService.preparePullRequestThread")( + function (input) { + return ensureGit("GitWorkflowService.preparePullRequestThread", input.cwd).pipe( + Effect.flatMap((handle) => + input.mode === "local" + ? withCheckoutLease( + handle.repository.rootPath, + gitManager.preparePullRequestThread(input), + ) + : gitManager.preparePullRequestThread(input), + ), + ); + }, + ), + listRefs: Effect.fn("GitWorkflowService.listRefs")(function (input) { + return detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe( Effect.flatMap((isGitRepository) => isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()), ), - ), - createWorktree: (input, options) => - ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe( + ); + }), + createWorktree: Effect.fn("GitWorkflowService.createWorktree")(function (input, options) { + return ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe( Effect.andThen(gitManager.createWorktree(input, options)), - ), - listLocalBranchNames: (cwd) => - ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe( + ); + }), + listLocalBranchNames: Effect.fn("GitWorkflowService.listLocalBranchNames")(function (cwd) { + return ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe( Effect.andThen(git.listLocalBranchNames(cwd)), - ), - fetchRemote: (input) => - ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe( + ); + }), + fetchRemote: Effect.fn("GitWorkflowService.fetchRemote")(function (input) { + return ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe( Effect.andThen(git.fetchRemote(input)), - ), - remoteExists: (input) => - ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe( + ); + }), + remoteExists: Effect.fn("GitWorkflowService.remoteExists")(function (input) { + return ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe( Effect.andThen(git.remoteExists(input)), - ), - remoteBranchExists: (input) => - ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe( + ); + }), + remoteBranchExists: Effect.fn("GitWorkflowService.remoteBranchExists")(function (input) { + return ensureGitCommand("GitWorkflowService.remoteBranchExists", input.cwd).pipe( Effect.andThen(git.remoteBranchExists(input)), - ), - resolveRemoteTrackingCommit: (input) => - ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe( - Effect.andThen(git.resolveRemoteTrackingCommit(input)), - ), - resolveWorktreeBaseRemote: (input) => - ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe( - Effect.andThen(git.resolveWorktreeBaseRemote(input)), - ), - fetchWorktreeBaseCommit: (input) => - ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe( - Effect.andThen(git.fetchWorktreeBaseCommit(input)), - ), - removeWorktree: (input) => - ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe( + ); + }), + resolveRemoteTrackingCommit: Effect.fn("GitWorkflowService.resolveRemoteTrackingCommit")( + function (input) { + return ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe( + Effect.andThen(git.resolveRemoteTrackingCommit(input)), + ); + }, + ), + resolveWorktreeBaseRemote: Effect.fn("GitWorkflowService.resolveWorktreeBaseRemote")( + function (input) { + return ensureGitCommand("GitWorkflowService.resolveWorktreeBaseRemote", input.cwd).pipe( + Effect.andThen(git.resolveWorktreeBaseRemote(input)), + ); + }, + ), + fetchWorktreeBaseCommit: Effect.fn("GitWorkflowService.fetchWorktreeBaseCommit")( + function (input) { + return ensureGitCommand("GitWorkflowService.fetchWorktreeBaseCommit", input.cwd).pipe( + Effect.andThen(git.fetchWorktreeBaseCommit(input)), + ); + }, + ), + removeWorktree: Effect.fn("GitWorkflowService.removeWorktree")(function (input) { + return ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe( Effect.andThen(git.removeWorktree(input)), - ), - pruneWorktrees: (input) => - ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe( + ); + }), + pruneWorktrees: Effect.fn("GitWorkflowService.pruneWorktrees")(function (input) { + return ensureGitCommand("GitWorkflowService.pruneWorktrees", input.cwd).pipe( Effect.andThen(git.pruneWorktrees(input)), - ), - deleteLocalBranch: (input) => - ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe( + ); + }), + deleteLocalBranch: Effect.fn("GitWorkflowService.deleteLocalBranch")(function (input) { + return ensureGitCommand("GitWorkflowService.deleteLocalBranch", input.cwd).pipe( Effect.andThen(git.deleteLocalBranch(input)), - ), - createRef: (input) => - ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe( + ); + }), + createRef: Effect.fn("GitWorkflowService.createRef")(function (input) { + return ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe( Effect.flatMap((handle) => input.switchRef ? withCheckoutLease(handle.repository.rootPath, git.createRef(input)) : git.createRef(input), ), - ), - switchRef: (input) => - ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe( + ); + }), + switchRef: Effect.fn("GitWorkflowService.switchRef")(function (input) { + return ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe( Effect.flatMap((handle) => withCheckoutLease(handle.repository.rootPath, Effect.scoped(git.switchRef(input))), ), - ), - renameBranch: (input) => - ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe( + ); + }), + renameBranch: Effect.fn("GitWorkflowService.renameBranch")(function (input) { + return ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe( Effect.andThen(git.renameBranch(input)), - ), + ); + }), }); }); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index f0c97e321ce10..83068f65f67a5 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -808,7 +808,7 @@ function threadTitle(input: { return detail.length > 80 ? `${detail.slice(0, 77)}...` : detail; } -function taskPrompt(input: OrchestratorMcpDelegateTaskInput): string { +export function taskPrompt(input: OrchestratorMcpDelegateTaskInput): string { return input.role === undefined || input.role === "general" ? input.task : `Act as the ${input.role} sub-agent for this task.\n\n${input.task}`; diff --git a/apps/server/src/mcpApps/McpAppModelContext.ts b/apps/server/src/mcpApps/McpAppModelContext.ts index 6e563e10b56ff..8dc16e67564a0 100644 --- a/apps/server/src/mcpApps/McpAppModelContext.ts +++ b/apps/server/src/mcpApps/McpAppModelContext.ts @@ -91,5 +91,12 @@ export const layer = Layer.effect( export const layerEmpty = Layer.succeed( McpAppModelContext, - McpAppModelContext.of({ set: () => Effect.void, forThread: () => Effect.succeed([]) }), + McpAppModelContext.of({ + set: Effect.fn("McpAppModelContext.set")(function () { + return Effect.void; + }), + forThread: Effect.fn("McpAppModelContext.forThread")(function () { + return Effect.succeed([]); + }), + }), ); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 2983aedcde02b..ff4a9c63f39d0 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -982,12 +982,9 @@ describe("ClaudeAdapterV2 approval cancellation", () => { decision: ProviderApprovalDecision; feedback?: string; }>(); - const controller = new AbortController(); - controller.abort(); - const result = yield* ClaudeAdapterV2.awaitClaudeApprovalDecision( decision, - controller.signal, + AbortSignal.abort(), ); assert.deepEqual(result, { decision: "cancel" }); @@ -1247,14 +1244,14 @@ describe("ClaudeAdapterV2 resume compaction", () => { Stream.runHead, Effect.forkScoped, ); - const controller = new AbortController(); + const signal = yield* Effect.abortSignal; const dialog = yield* Effect.promise(() => callback!( { dialogKind: "resume_return", payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 }, }, - { signal: controller.signal, requestId: "dialog-resume-1" }, + { signal, requestId: "dialog-resume-1" }, ), ).pipe(Effect.forkScoped); const event = yield* Fiber.join(requestEvent); @@ -1270,8 +1267,6 @@ describe("ClaudeAdapterV2 resume compaction", () => { }); assert.deepEqual(yield* Fiber.join(dialog), { behavior: "completed", result: "compact" }); - const cancelledController = new AbortController(); - cancelledController.abort(); assert.deepEqual( yield* Effect.promise(() => callback!( @@ -1279,7 +1274,7 @@ describe("ClaudeAdapterV2 resume compaction", () => { dialogKind: "resume_return", payload: { sessionAgeMinutes: 90, estimatedTokens: 120000 }, }, - { signal: cancelledController.signal, requestId: "dialog-resume-2" }, + { signal: AbortSignal.abort(), requestId: "dialog-resume-2" }, ), ), { behavior: "cancelled" }, @@ -14475,6 +14470,55 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ), ); + + it.effect("keeps the CLI's goal confirmation out of the conversation", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const condition = "all tests pass"; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: { + ...harness.providerThread, + goal: { objective: condition, status: "active", checks: 1 }, + }, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("goal-clear-attempt"), + text: "/goal clear", + attachments: [], + }), + ); + yield* Queue.offer( + harness.sdkMessages, + syntheticFrame("goal-clear", `Goal cleared: ${condition}`), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "goal-clear-result", + result: `Goal cleared: ${condition}\n`, + numTurns: 0, + }), + ); + yield* Queue.take(harness.terminalReceipts); + assert.isTrue( + harness.events.some( + (event) => + event.type === "provider_thread.updated" && event.providerThread.goal === null, + ), + ); + assert.isFalse( + harness.events.some( + (event) => event.type === "message.updated" && event.message.role === "assistant", + ), + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); }); }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 00a3995d8dfac..b893b26b5d948 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -540,6 +540,15 @@ export class ClaudeAgentSdkQueryRunnerError extends Schema.TaggedError()( + "ClaudeMcpRegistrationTimeoutError", + {}, +) { + override get message(): string { + return "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs."; + } +} + export class ClaudeBackgroundWorkBlocksQueryReplacementError extends Schema.TaggedError()( "ClaudeBackgroundWorkBlocksQueryReplacementError", {}, @@ -609,6 +618,7 @@ export interface ClaudeAgentSdkSubagentLookupInput { } const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAgentSdkQueryRunnerError); +const isClaudeMcpRegistrationTimeoutError = Schema.is(ClaudeMcpRegistrationTimeoutError); const isProviderAdapterRuntimeRequestResponseError = Schema.is( ProviderAdapter.ProviderAdapterRuntimeRequestResponseError, ); @@ -848,249 +858,310 @@ export const layerQueryRunner: Layer.Layer< allocateSessionId: crypto .randomUUIDv4() .pipe(Effect.mapError((cause) => queryRunnerError(cause, "allocateSessionId"))), - open: Effect.fn("ClaudeAgentSdkQueryRunner.open")(function* ( - input: ClaudeAgentSdkQueryOpenInput, - ) { - const protocolLogger = makeClaudeAgentSdkProtocolLogger({ - nativeEventLogger, - threadId: input.threadId, - providerSessionId: input.providerSessionId, - }); - const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) => - protocolLogger === undefined ? Effect.void : protocolLogger(event); - const promptQueue = yield* Queue.unbounded(); - const prompt = Stream.fromQueue(promptQueue).pipe( - Stream.catchCause((cause) => - Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause), - ), - Stream.toAsyncIterable, - ); - // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments. - const { mcpServers, ...queryOptions } = input.options; - // The SDK can prepend a scope wrapper to native binaries; script entries run through node. - const binaryPath = queryOptions.pathToClaudeCodeExecutable; - const launch = - binaryPath === undefined || - CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext)) - ? undefined - : yield* agentScope.wrap({ - command: binaryPath, - args: [], - name: "claude", - threadId: input.threadId, - env: queryOptions.env, + open: Effect.fn("ClaudeAgentSdkQueryRunner.open")( + function* (input: ClaudeAgentSdkQueryOpenInput) { + const protocolLogger = makeClaudeAgentSdkProtocolLogger({ + nativeEventLogger, + threadId: input.threadId, + providerSessionId: input.providerSessionId, + }); + const logProtocolEvent = (event: ClaudeAgentSdkProtocolLogEvent) => + protocolLogger === undefined ? Effect.void : protocolLogger(event); + // A failed open shuts down its queue before retrying, so the old CLI cannot take the prompt. + const promptQueue = yield* Queue.unbounded(); + const prompt = Stream.fromQueue(promptQueue).pipe( + Stream.catchCause((cause) => + Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause), + ), + Stream.toAsyncIterable, + ); + // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments. + const { mcpServers, ...queryOptions } = input.options; + // The SDK can prepend a scope wrapper to native binaries; script entries run through node. + const binaryPath = queryOptions.pathToClaudeCodeExecutable; + const launch = + binaryPath === undefined || + CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext)) + ? undefined + : yield* agentScope.wrap({ + command: binaryPath, + args: [], + name: "claude", + threadId: input.threadId, + env: queryOptions.env, + }); + const options = + launch === undefined || launch.args.length === 0 + ? queryOptions + : { + ...queryOptions, + pathToClaudeCodeExecutable: launch.command, + executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])], + }; + const unit = launch?.unit; + const stopScope = + unit === undefined ? undefined : () => void runFork(agentScope.stop(unit)); + const spawnProcess = + options.spawnClaudeCodeProcess ?? + ((spawnOptions: ClaudeSpawnOptions) => { + if (platform !== "win32") return spawnClaudeProcessGroup(spawnOptions, stopScope); + const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, { + cwd: spawnOptions.cwd, + env: spawnOptions.env, + signal: spawnOptions.signal, + windowsHide: true, + stdio: ["pipe", "pipe", "pipe"], }); - const options = - launch === undefined || launch.args.length === 0 - ? queryOptions - : { - ...queryOptions, - pathToClaudeCodeExecutable: launch.command, - executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])], - }; - const unit = launch?.unit; - const stopScope = - unit === undefined ? undefined : () => void runFork(agentScope.stop(unit)); - // Windows has no process groups, so there the SDK spawns the CLI itself. - const spawnClaudeCodeProcess = - options.spawnClaudeCodeProcess ?? - (platform === "win32" - ? undefined - : (spawnOptions: ClaudeSpawnOptions) => - spawnClaudeProcessGroup(spawnOptions, stopScope)); - const queryRuntime = yield* Effect.uninterruptibleMask((restore) => - Effect.try({ - try: () => - query({ - prompt, - options: - spawnClaudeCodeProcess === undefined - ? options - : { ...options, spawnClaudeCodeProcess }, - }), - catch: (cause) => queryRunnerError(cause, "query"), - }).pipe( - Effect.tap((queryRuntime) => - restore( - Effect.gen(function* () { - if (mcpServers !== undefined) { - // Errors and mcp_status can echo headers; log only server names. - const failed = yield* Effect.tryPromise(() => - queryRuntime.setMcpServers(mcpServers), - ).pipe( - Effect.map((result) => Object.keys(result.errors)), - Effect.orElseSucceed(() => Object.keys(mcpServers)), - Effect.timeoutOrElse({ - duration: CLAUDE_MCP_REGISTRATION_TIMEOUT, - orElse: () => - Effect.fail( - queryRunnerError( - "Claude Code did not answer the MCP server registration.", - "setMcpServers", + child.stderr + .setEncoding("utf8") + .on("data", (chunk: string) => options.stderr?.(chunk)); + return child; + }); + let spawnedProcess: ClaudeSpawnedProcess | undefined; + let processExited = false; + let processExit: Promise | undefined; + const spawnClaudeCodeProcess = (spawnOptions: ClaudeSpawnOptions) => { + const child = spawnProcess(spawnOptions); + spawnedProcess = child; + processExited = child.exitCode !== null || child.signalCode != null; + processExit = new Promise((resolve) => { + if (processExited) resolve(); + else + child.once("exit", () => { + processExited = true; + resolve(); + }); + }); + return child; + }; + const queryRuntime = yield* Effect.uninterruptibleMask((restore) => + Effect.try({ + try: () => + query({ + prompt, + options: { ...options, spawnClaudeCodeProcess }, + }), + catch: (cause) => queryRunnerError(cause, "query"), + }).pipe( + Effect.tap((queryRuntime) => + restore( + Effect.gen(function* () { + if (mcpServers !== undefined) { + // Errors and mcp_status can echo headers; log only server names. + const failed = yield* Effect.tryPromise(() => + queryRuntime.setMcpServers(mcpServers), + ).pipe( + Effect.map((result) => Object.keys(result.errors)), + Effect.orElseSucceed(() => Object.keys(mcpServers)), + Effect.timeoutOrElse({ + duration: CLAUDE_MCP_REGISTRATION_TIMEOUT, + orElse: () => + Effect.logWarning("orchestration-v2.claude-mcp-registration-timeout", { + threadId: input.threadId, + providerSessionId: input.providerSessionId, + }).pipe( + Effect.andThen( + Effect.fail( + queryRunnerError( + new ClaudeMcpRegistrationTimeoutError(), + "setMcpServers", + ), + ), + ), ), - ), - }), - ); - if (failed.length > 0) { - yield* Effect.logWarning("orchestration-v2.claude-mcp-servers-unavailable", { - threadId: input.threadId, - servers: failed, - }); + }), + ); + if (failed.length > 0) { + yield* Effect.logWarning( + "orchestration-v2.claude-mcp-servers-unavailable", + { + threadId: input.threadId, + servers: failed, + }, + ); + } } - } - yield* logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.open", - options: loggedClaudeQueryOptions(input.options), - }, - }); - }), - ).pipe( - Effect.onError(() => - Queue.shutdown(promptQueue).pipe( - Effect.andThen(closeClaudeQuery(queryRuntime)), - Effect.ignore, + yield* logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.open", + options: loggedClaudeQueryOptions(input.options), + }, + }); + }), + ).pipe( + Effect.onError(() => + Queue.shutdown(promptQueue).pipe( + // SDK disposal can return before process exit; await the owned child's exit before retrying. + Effect.andThen( + Effect.tryPromise({ + try: async () => { + if (spawnedProcess !== undefined && !processExited) { + spawnedProcess.kill("SIGKILL"); + } + await processExit; + }, + catch: (cause) => queryRunnerError(cause, "close"), + }).pipe(Effect.timeout("10 seconds")), + ), + Effect.ensuring( + Effect.tryPromise({ + try: () => queryRuntime[Symbol.asyncDispose](), + catch: (cause) => queryRunnerError(cause, "close"), + }).pipe(Effect.orDie), + ), + Effect.orDie, + ), ), ), ), ), - ), - ); + ); - return { - messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) => - queryRunnerError(cause, "fromAsyncIterable"), - ).pipe( - Stream.tap((message) => - logProtocolEvent({ - direction: "incoming", - stage: "decoded", - payload: message, - }), - ), - ), - offer: (message, onQueued) => - Effect.uninterruptibleMask((restore) => - restore(Queue.offer(promptQueue, message)).pipe( - Effect.tap(() => Effect.sync(() => onQueued?.())), - ), + return { + messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) => + queryRunnerError(cause, "fromAsyncIterable"), ).pipe( - Effect.asVoid, - Effect.tap(() => + Stream.tap((message) => logProtocolEvent({ - direction: "outgoing", + direction: "incoming", stage: "decoded", - payload: { - type: "prompt.offer", - message, - }, + payload: message, }), ), ), - setModel: (model) => - Effect.tryPromise({ - try: () => queryRuntime.setModel(model), - catch: (cause) => queryRunnerError(cause, "setModel"), - }).pipe( - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.set_model", - model, - }, - }), + offer: (message, onQueued) => + Effect.uninterruptibleMask((restore) => + restore(Queue.offer(promptQueue, message)).pipe( + Effect.tap(() => Effect.sync(() => onQueued?.())), + ), + ).pipe( + Effect.asVoid, + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "prompt.offer", + message, + }, + }), + ), ), - ), - applyFlagSettings: (settings) => - Effect.tryPromise({ - try: () => queryRuntime.applyFlagSettings(settings), - catch: (cause) => queryRunnerError(cause, "applyFlagSettings"), + setModel: (model) => + Effect.tryPromise({ + try: () => queryRuntime.setModel(model), + catch: (cause) => queryRunnerError(cause, "setModel"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.set_model", + model, + }, + }), + ), + ), + applyFlagSettings: (settings) => + Effect.tryPromise({ + try: () => queryRuntime.applyFlagSettings(settings), + catch: (cause) => queryRunnerError(cause, "applyFlagSettings"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.apply_flag_settings", + settings, + }, + }), + ), + ), + setPermissionMode: (mode) => + Effect.tryPromise({ + try: () => queryRuntime.setPermissionMode(mode), + catch: (cause) => queryRunnerError(cause, "setPermissionMode"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { + type: "query.set_permission_mode", + mode, + }, + }), + ), + ), + stopTask: (taskId) => + Effect.tryPromise({ + try: () => queryRuntime.stopTask(taskId), + catch: (cause) => queryRunnerError(cause, "stopTask"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { type: "query.stop_task", taskId }, + }), + ), + ), + backgroundTasks: (toolUseId) => + Effect.tryPromise({ + try: () => queryRuntime.backgroundTasks(toolUseId), + catch: (cause) => queryRunnerError(cause, "backgroundTasks"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { type: "query.background_tasks", toolUseId }, + }), + ), + ), + interrupt: Effect.tryPromise({ + try: () => queryRuntime.interrupt(), + catch: (cause) => queryRunnerError(cause, "interrupt"), }).pipe( Effect.tap(() => logProtocolEvent({ direction: "outgoing", stage: "decoded", payload: { - type: "query.apply_flag_settings", - settings, + type: "query.interrupt", }, }), ), ), - setPermissionMode: (mode) => - Effect.tryPromise({ - try: () => queryRuntime.setPermissionMode(mode), - catch: (cause) => queryRunnerError(cause, "setPermissionMode"), - }).pipe( + close: Queue.shutdown(promptQueue).pipe( + Effect.andThen(closeClaudeQuery(queryRuntime)), Effect.tap(() => logProtocolEvent({ direction: "outgoing", stage: "decoded", payload: { - type: "query.set_permission_mode", - mode, + type: "query.close", }, }), ), ), - stopTask: (taskId) => - Effect.tryPromise({ - try: () => queryRuntime.stopTask(taskId), - catch: (cause) => queryRunnerError(cause, "stopTask"), - }).pipe( - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { type: "query.stop_task", taskId }, - }), - ), - ), - backgroundTasks: (toolUseId) => - Effect.tryPromise({ - try: () => queryRuntime.backgroundTasks(toolUseId), - catch: (cause) => queryRunnerError(cause, "backgroundTasks"), - }).pipe( - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { type: "query.background_tasks", toolUseId }, - }), - ), - ), - interrupt: Effect.tryPromise({ - try: () => queryRuntime.interrupt(), - catch: (cause) => queryRunnerError(cause, "interrupt"), - }).pipe( - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.interrupt", - }, - }), - ), - ), - close: Queue.shutdown(promptQueue).pipe( - Effect.andThen(closeClaudeQuery(queryRuntime)), - Effect.tap(() => - logProtocolEvent({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.close", - }, - }), - ), + } satisfies ClaudeAgentSdkQuerySession; + }, + // Fresh IDs may already have a metadata-only transcript; only resumed opens can reuse their ID. + (effect, input) => + effect.pipe( + Effect.retry({ + times: 1, + while: (error) => + input.options.resume !== undefined && + isClaudeMcpRegistrationTimeoutError(error.cause), + }), ), - } satisfies ClaudeAgentSdkQuerySession; - }), + ), forkSession: Effect.fn("ClaudeAgentSdkQueryRunner.forkSession")(function* ( input: ClaudeAgentSdkSessionForkInput, ) { @@ -1590,6 +1661,19 @@ function nextClaudeGoal( }; } +/** The CLI confirms a goal change as a synthetic reply; the goal row shows that change instead. */ +function isClaudeGoalAcknowledgement(message: SDKMessage): boolean { + if ( + message.type !== "assistant" || + message.parent_tool_use_id !== null || + message.message.model !== "" + ) { + return false; + } + const text = textFromClaudeContent(message.message.content).trim(); + return text.startsWith(CLAUDE_GOAL_SET_PREFIX) || text.startsWith("Goal cleared: "); +} + const providerGoalsEqual = Schema.toEquivalence(Schema.NullOr(OrchestrationV2ProviderGoal)); function normalizeClaudeResultText(text: string): string { @@ -4245,8 +4329,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return ProviderAdapter.ProviderAdapterV2.of({ instanceId: adapterOptions.instanceId, driver: CLAUDE_PROVIDER, - getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2), - planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()), + getCapabilities: Effect.fn("ClaudeAdapterV2.getCapabilities")(function () { + return Effect.succeed(ClaudeProviderCapabilitiesV2); + }), + planSelectionTransition: Effect.fn("ClaudeAdapterV2.planSelectionTransition")(function () { + return Effect.succeed(turnScopedSelectionTransition()); + }), openSession: Effect.fn("ClaudeAdapterV2.openSession")( function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) { const sessionScope = yield* Effect.scope; @@ -8743,6 +8831,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); return; } + if (isClaudeGoalAcknowledgement(message)) { + // The CLI repeats a local command's output as the turn's result text. + if (assistantText !== null) { + context.assistant.noticeTexts.add(normalizeClaudeResultText(assistantText.text)); + } + return; + } // Claude Code echoes /compact's stdout ("Not enough messages to compact.") as a // synthetic assistant message. The compaction item reports that outcome; it is not a // reply. @@ -8815,7 +8910,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( context.assistant.fallbackText.length === 0 && resultText !== null && resultText.text.length > 0 && - !context.assistant.noticeTexts.has(resultText.text) + !context.assistant.noticeTexts.has(resultText.text) && + !context.assistant.noticeTexts.has(normalizeClaudeResultText(resultText.text)) ) { context.assistant.fallbackText = resultText.text; context.assistant.fallbackNativeItemId = resultText.nativeItemId; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 87d2d3b956d19..5d79868c09113 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -1,24 +1,33 @@ // @effect-diagnostics nodeBuiltinImport:off -- the fake CLI and its leftover child are real processes. import * as NodeChildProcess from "node:child_process"; +import * as NodeEvents from "node:events"; import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; +import * as NodeStream from "node:stream"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ProviderSessionId, ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { AgentScope } from "@t3tools/shared/AgentScope"; import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers"; +import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; // Coder: the runner queries Claude through the CLI transport's SDK-typed shim, so the test // stubs the shim's query rather than the Agent SDK's. +import type * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk"; +import * as ClaudeAgentSdk from "../../provider/Drivers/ClaudeAgentSdk.ts"; import { ClaudeAgentSdkQueryRunner, + type ClaudeAgentSdkQueryOpenInput, layerQueryRunner, spawnClaudeProcessGroup, } from "./ClaudeAdapterV2.ts"; @@ -37,6 +46,271 @@ const realQueryRunner = layerQueryRunner.pipe( Layer.provide(NodeServices.layer), ); +// Coder: upstream declares this beside its fork tests, which are not carried (see above). +const FORK_SESSION_ID = "11111111-1111-4111-8111-111111111111"; + +const resumedMcpQueryInput = { + threadId: ThreadId.make("thread-restart-registration"), + providerSessionId: ProviderSessionId.make("session-restart-registration"), + options: { + resume: FORK_SESSION_ID, + model: "claude-sonnet-4-6", + tools: [], + permissionMode: "default", + mcpServers: { + "t3-code": { + type: "http", + url: "http://localhost:3773/mcp", + headers: { Authorization: "Bearer test-mcp-credential" }, + }, + }, + }, +} satisfies ClaudeAgentSdkQueryOpenInput; + +it.effect("reopens a stalled MCP registration before delivering the resumed prompt", () => + Effect.scoped( + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const disposalStarted = Promise.withResolvers(); + const finishDisposal = Promise.withResolvers(); + const prompts: AsyncIterable[] = []; + const firstClose = vi.fn(); + const secondClose = vi.fn(); + const firstRegistration = vi.fn(() => { + registrationStarted.resolve(); + return new Promise(() => {}); + }); + const secondRegistration = vi.fn(async () => ({ + added: ["t3-code"], + removed: [], + errors: {}, + })); + const querySpy = vi.spyOn(ClaudeAgentSdk, "query").mockImplementation(({ prompt }) => { + assert.notTypeOf(prompt, "string"); + if (typeof prompt === "string") throw new Error("Expected streaming input"); + prompts.push(prompt); + return { + setMcpServers: prompts.length === 1 ? firstRegistration : secondRegistration, + close: prompts.length === 1 ? firstClose : secondClose, + [Symbol.asyncDispose]: async () => { + firstClose(); + disposalStarted.resolve(); + await finishDisposal.promise; + }, + } as unknown as ClaudeSdk.Query; + }); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* TestClock.adjust("90 seconds"); + yield* Effect.promise(() => disposalStarted.promise); + assert.equal(querySpy.mock.calls.length, 1); + finishDisposal.resolve(); + const session = yield* Fiber.join(opening); + yield* Effect.addFinalizer(() => session.close.pipe(Effect.orDie)); + + assert.equal(firstClose.mock.calls.length, 1); + assert.equal(secondClose.mock.calls.length, 0); + assert.equal(querySpy.mock.calls.length, 2); + for (const [call] of querySpy.mock.calls) { + assert.equal(call.options?.resume, FORK_SESSION_ID); + assert.isUndefined(call.options?.mcpServers); + } + assert.deepEqual(secondRegistration.mock.calls, [[resumedMcpQueryInput.options.mcpServers]]); + const message = { + type: "user", + message: { role: "user", content: "Continue where you left off." }, + parent_tool_use_id: null, + session_id: FORK_SESSION_ID, + } satisfies ClaudeSdk.SDKUserMessage; + yield* session.offer(message); + assert.isTrue((yield* Effect.promise(() => prompts[0]![Symbol.asyncIterator]().next())).done); + const delivered = yield* Effect.promise(() => prompts[1]![Symbol.asyncIterator]().next()); + assert.deepEqual(delivered.value, message); + assert.isFalse(delivered.done); + }).pipe(Effect.provide(realQueryRunner)), + ), +); + +it.effect.each([true, false])("only retries after confirmed process exit: %s", (exits) => + Effect.scoped( + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const cleanupProgress = Promise.withResolvers<"kill" | "retry">(); + const events = new NodeEvents.EventEmitter(); + const stdin = new NodeStream.PassThrough(); + const stdout = new NodeStream.PassThrough(); + const child = { + stdin, + stdout, + killed: false, + exitCode: null, + kill: vi.fn(() => { + cleanupProgress.resolve("kill"); + return true; + }), + on: events.on.bind(events), + once: events.once.bind(events), + off: events.off.bind(events), + } satisfies ClaudeSdk.SpawnedProcess; + const signal = yield* Effect.abortSignal; + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeAgentSdk, "query").mockImplementation(({ options }) => { + const first = querySpy.mock.calls.length === 1; + if (first) { + options?.spawnClaudeCodeProcess?.({ command: "claude", args: [], env: {}, signal }); + } else { + cleanupProgress.resolve("retry"); + } + return { + setMcpServers: () => { + registrationStarted.resolve(); + return first + ? new Promise(() => {}) + : Promise.resolve({ added: ["t3-code"], removed: [], errors: {} }); + }, + close: vi.fn(), + [Symbol.asyncDispose]: disposed, + } as unknown as ClaudeSdk.Query; + }); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + querySpy.mockRestore(); + stdin.destroy(); + stdout.destroy(); + }), + ); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner + .open({ + ...resumedMcpQueryInput, + options: { ...resumedMcpQueryInput.options, spawnClaudeCodeProcess: () => child }, + }) + .pipe(Effect.exit, Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* TestClock.adjust("90 seconds"); + + assert.equal(yield* Effect.promise(() => cleanupProgress.promise), "kill"); + assert.equal(querySpy.mock.calls.length, 1); + assert.deepEqual(child.kill.mock.calls, [["SIGKILL"]]); + if (exits) events.emit("exit", null, "SIGKILL"); + else yield* TestClock.adjust("10 seconds"); + const result = yield* Fiber.join(opening); + assert.equal(Exit.isSuccess(result), exits); + if (Exit.isSuccess(result)) yield* result.value.close; + assert.equal(querySpy.mock.calls.length, exits ? 2 : 1); + assert.equal(disposed.mock.calls.length, 1); + }).pipe(Effect.provide(realQueryRunner)), + ), +); + +it.effect("stops retrying MCP registration after two timeouts and reports the cause", () => + Effect.scoped( + Effect.gen(function* () { + const firstRegistration = Promise.withResolvers(); + const secondRegistration = Promise.withResolvers(); + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeAgentSdk, "query").mockImplementation(() => { + const started = querySpy.mock.calls.length === 1 ? firstRegistration : secondRegistration; + return { + setMcpServers: () => { + started.resolve(); + return new Promise(() => {}); + }, + [Symbol.asyncDispose]: disposed, + } as unknown as ClaudeSdk.Query; + }); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner + .open(resumedMcpQueryInput) + .pipe(Effect.result, Effect.forkChild); + yield* Effect.promise(() => firstRegistration.promise); + yield* TestClock.adjust("90 seconds"); + yield* Effect.promise(() => secondRegistration.promise); + yield* TestClock.adjust("90 seconds"); + const result = yield* Fiber.join(opening); + + assert.equal(result._tag, "Failure"); + if (result._tag !== "Failure") return; + assert.equal(querySpy.mock.calls.length, 2); + assert.equal(disposed.mock.calls.length, 2); + assert.equal( + makeProviderFailure({ + cause: { _tag: "ProviderAdapterTurnStartError", cause: result.failure }, + }).message, + "Claude timed out while registering its MCP tools. Retry the turn; if it keeps failing, check Claude and the server logs.", + ); + }).pipe(Effect.provide(realQueryRunner)), + ), +); + +it.effect("cancels a stalled registration without retrying or retaining its prompt queue", () => + Effect.scoped( + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeAgentSdk, "query").mockImplementation( + () => + ({ + setMcpServers: () => { + registrationStarted.resolve(); + return new Promise(() => {}); + }, + [Symbol.asyncDispose]: disposed, + }) as unknown as ClaudeSdk.Query, + ); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const opening = yield* runner.open(resumedMcpQueryInput).pipe(Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* Fiber.interrupt(opening); + + assert.equal(querySpy.mock.calls.length, 1); + assert.equal(disposed.mock.calls.length, 1); + const prompt = querySpy.mock.calls[0]![0].prompt; + if (typeof prompt === "string") throw new Error("Expected streaming input"); + assert.isTrue((yield* Effect.promise(() => prompt[Symbol.asyncIterator]().next())).done); + }).pipe(Effect.provide(realQueryRunner)), + ), +); + +it.effect("does not reuse a fresh session ID after MCP registration times out", () => + Effect.scoped( + Effect.gen(function* () { + const registrationStarted = Promise.withResolvers(); + const disposed = vi.fn(async () => {}); + const querySpy = vi.spyOn(ClaudeAgentSdk, "query").mockImplementation( + () => + ({ + setMcpServers: () => { + registrationStarted.resolve(); + return new Promise(() => {}); + }, + [Symbol.asyncDispose]: disposed, + }) as unknown as ClaudeSdk.Query, + ); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const { resume, ...options } = resumedMcpQueryInput.options; + const opening = yield* runner + .open({ + ...resumedMcpQueryInput, + options: { ...options, sessionId: resume }, + }) + .pipe(Effect.result, Effect.forkChild); + yield* Effect.promise(() => registrationStarted.promise); + yield* TestClock.adjust("90 seconds"); + const result = yield* Fiber.join(opening); + + assert.equal(result._tag, "Failure"); + assert.equal(querySpy.mock.calls.length, 1); + assert.equal(disposed.mock.calls.length, 1); + }).pipe(Effect.provide(realQueryRunner)), + ), +); + function fakeClaudeCli(script: string): string { const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-claude-cli-")); const cli = NodePath.join(dir, "claude"); @@ -121,6 +395,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro args: [], cwd: dir, env: process.env, + // @effect-diagnostics-next-line abortControllerInEffect:off - This crash fixture closes pipes itself; aborting on test teardown raises an unrelated process error. signal: new AbortController().signal, }) as NodeChildProcess.ChildProcess; yield* Effect.addFinalizer(() => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index c84fa8fb40173..a77f4c5cee4cd 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -5989,6 +5989,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { nativeThreadId, nativeTurnId: "goal-turn-1", prompt: objective, + sentPrompt: `Start working toward this goal: ${objective}`, }).slice(5), 5, ), @@ -6053,6 +6054,8 @@ describe("CodexAdapterV2 post-settle continuation", () => { [providerTurnId("goal-turn-2"), RunAttemptId.make("goal-attempt"), 2], ], ); + // The goal is set paused until its first turn starts; only the result shows. + assert.notInclude(providerGoals(harness.events), "paused"); assert.equal(providerGoals(harness.events).at(-1), "complete"); }).pipe( Effect.scoped, @@ -6235,6 +6238,233 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("pauses a goal Codex does not continue before its run settles", () => + Effect.gen(function* () { + const prompt = "Keep going"; + const transcript = makeCodexReplayTranscript({ + scenario: "goal-continuation-expired", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn", prompt }), + notification("goal active", "thread/goal/updated", { + threadId: nativeThreadId, + turnId: "goal-turn", + goal: codexGoal("active", 10), + }), + notification("turn done", "turn/completed", { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: "goal-turn", status: "completed" }), + }), + notification("goal accounted", "thread/goal/updated", { + threadId: nativeThreadId, + turnId: null, + goal: codexGoal("active", 11), + }), + ...request( + 4, + "thread/goal/set", + { threadId: nativeThreadId, status: "paused" }, + { goal: codexGoal("paused", 11) }, + ), + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("goal-expired-attempt"), + text: prompt, + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_thread.updated" && + event.providerThread.goal?.tokensUsed === 11, + ), + ); + assert.lengthOf(harness.terminalEvents(), 0); + yield* TestClock.adjust("5 seconds"); + yield* harness.firstTerminal; + + assert.deepEqual(providerGoals(harness.events), ["active", "active", "paused"]); + assert.deepEqual( + harness.terminalEvents().map((event) => event.status), + ["completed"], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + + it.effect("stops a turn Codex starts while the expiry pause is in flight", () => + Effect.gen(function* () { + const prompt = "Keep going"; + const transcript = makeCodexReplayTranscript({ + scenario: "goal-continuation-during-expiry", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn", prompt }), + notification("goal active", "thread/goal/updated", { + threadId: nativeThreadId, + turnId: "goal-turn", + goal: codexGoal("active", 10), + }), + notification("turn done", "turn/completed", { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: "goal-turn", status: "completed" }), + }), + notification("goal accounted", "thread/goal/updated", { + threadId: nativeThreadId, + turnId: null, + goal: codexGoal("active", 11), + }), + { + type: "expect_outbound", + label: "pause", + frame: { + id: 4, + method: "thread/goal/set", + params: { threadId: nativeThreadId, status: "paused" }, + }, + }, + notification("goal paused", "thread/goal/updated", { + threadId: nativeThreadId, + turnId: null, + goal: codexGoal("paused", 11), + }), + notification("late continuation", "turn/started", { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: "goal-turn-2", status: "inProgress" }), + }), + ...request( + 5, + "thread/goal/set", + { threadId: nativeThreadId, status: "paused" }, + { goal: codexGoal("paused", 11) }, + ), + ...request( + 6, + "turn/interrupt", + { threadId: nativeThreadId, turnId: "goal-turn-2" }, + {}, + ), + { + type: "emit_inbound", + label: "paused", + frame: { id: 4, result: { goal: codexGoal("paused", 11) } }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("goal-race-attempt"), + text: prompt, + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_thread.updated" && + event.providerThread.goal?.tokensUsed === 11, + ), + ); + yield* TestClock.adjust("5 seconds"); + yield* harness.firstTerminal; + + assert.deepEqual( + harness.terminalEvents().map((event) => [event.providerTurnId, event.status]), + [ + [ + (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + nativeTurnId: "goal-turn", + }), + "completed", + ], + ], + ); + assert.equal(providerGoals(harness.events).at(-1), "paused"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + + it.effect("settles the run when Codex never answers the expiry pause", () => + Effect.gen(function* () { + const prompt = "Keep going"; + const transcript = makeCodexReplayTranscript({ + scenario: "goal-expiry-pause-unanswered", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "goal-turn", prompt }), + notification("goal active", "thread/goal/updated", { + threadId: nativeThreadId, + turnId: "goal-turn", + goal: codexGoal("active", 10), + }), + notification("turn done", "turn/completed", { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: "goal-turn", status: "completed" }), + }), + notification("goal accounted", "thread/goal/updated", { + threadId: nativeThreadId, + turnId: null, + goal: codexGoal("active", 11), + }), + { + type: "expect_outbound", + label: "pause", + frame: { + id: 4, + method: "thread/goal/set", + params: { threadId: nativeThreadId, status: "paused" }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("goal-unanswered-attempt"), + text: prompt, + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_thread.updated" && + event.providerThread.goal?.tokensUsed === 11, + ), + ); + yield* TestClock.adjust("5 seconds"); + yield* TestClock.adjust("10 seconds"); + yield* harness.firstTerminal; + + assert.deepEqual( + harness.terminalEvents().map((event) => event.status), + ["completed"], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + it.effect("pauses an active goal before Stop interrupts its turn", () => Effect.gen(function* () { const prompt = "Keep going"; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 1be120606ff58..d91e108beb361 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -30,7 +30,9 @@ import { CodexSettings, defaultInstanceIdForDriver, isOrchestrationV2WorkActive, + type OrchestrationV2GoalCommand, OrchestrationV2ProviderGoal, + parseGoalCommand, ProviderDriverKind, type ProviderSetupError, } from "@t3tools/contracts"; @@ -884,32 +886,6 @@ const isTerminalProviderTurn = (turn: OrchestrationV2ProviderTurn): boolean => turn.status === "failed" || turn.status === "cancelled"); -export type CodexGoalCommand = - | { readonly type: "show" } - | { readonly type: "clear" } - | { readonly type: "pause" } - | { readonly type: "resume" } - | { readonly type: "set"; readonly objective: string }; - -function parseCodexGoalCommand(text: string): CodexGoalCommand | null { - const match = /^\/goal(?:\s+([\s\S]*))?$/u.exec(text.trim()); - if (match === null) return null; - const argument = (match[1] ?? "").trim(); - switch (argument.toLowerCase()) { - case "": - case "edit": - return { type: "show" }; - case "clear": - return { type: "clear" }; - case "pause": - return { type: "pause" }; - case "resume": - return { type: "resume" }; - default: - return { type: "set", objective: argument }; - } -} - type CodexThreadGoal = CodexSchema.V2ThreadGoalUpdatedNotification["goal"]; const CODEX_GOAL_STATUSES = { @@ -1605,8 +1581,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( return ProviderAdapter.ProviderAdapterV2.of({ instanceId: adapterOptions.instanceId, driver: CODEX_PROVIDER, - getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), - planSelectionTransition: () => Effect.succeed(turnScopedSelectionTransition()), + getCapabilities: Effect.fn("CodexAdapterV2.getCapabilities")(function () { + return Effect.succeed(CodexProviderCapabilitiesV2); + }), + planSelectionTransition: Effect.fn("CodexAdapterV2.planSelectionTransition")(function () { + return Effect.succeed(turnScopedSelectionTransition()); + }), openSession: Effect.fn("CodexAdapterV2.openSession")( function* (input) { const scope = yield* Scope.Scope; @@ -1816,9 +1796,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) => Queue.offer(events, event).pipe(Effect.asVoid); + // Setting a goal passes through cleared and paused states; publish only the result. + const goalUpdatesHeld = new Set(); const emitGoalUpdate = Effect.fnUntraced(function* (nativeThreadId: string) { const providerThread = rootProviderThreads.get(nativeThreadId); - if (providerThread === undefined || !goalsByNativeThread.has(nativeThreadId)) return; + if ( + providerThread === undefined || + !goalsByNativeThread.has(nativeThreadId) || + goalUpdatesHeld.has(nativeThreadId) + ) { + return; + } const goal = goalsByNativeThread.get(nativeThreadId) ?? null; if (providerGoalsEqual(providerThread.goal ?? null, goal)) return; const updated = { ...providerThread, goal, updatedAt: yield* DateTime.now }; @@ -1839,6 +1827,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* emitGoalUpdate(nativeThreadId); }); + const releaseGoalUpdates = (nativeThreadId: string) => + Effect.suspend(() => { + goalUpdatesHeld.delete(nativeThreadId); + return emitGoalUpdate(nativeThreadId); + }); + // Only new model output proves recovery; local item/completed can arrive during upstream retries. const completeProviderRetry = Effect.fn("CodexAdapterV2.completeProviderRetry")(function* ( context: ActiveCodexTurnContext, @@ -2883,15 +2877,15 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( : null, ), Effect.orElseSucceed(() => null), - Effect.flatMap((response) => - response === null - ? client.raw - .request("thread/resume", { - threadId: input.nativeThreadId, - excludeTurns: true, - }) - .pipe(Effect.flatMap(decodeCodexChildModel)) - : Effect.succeed(response), + Effect.filterOrElse( + (response) => !(response === null), + (_response) => + client.raw + .request("thread/resume", { + threadId: input.nativeThreadId, + excludeTurns: true, + }) + .pipe(Effect.flatMap(decodeCodexChildModel)), ), Effect.timeout("5 seconds"), Effect.flatMap((response) => @@ -5654,10 +5648,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( next: yield* Deferred.make(), }); yield* Effect.sleep(CODEX_GOAL_CONTINUATION_GRACE).pipe( + Effect.andThen(pauseUncontinuedGoal(nativeThreadId, event)), Effect.andThen( turnTerminalizationPermit.withPermits(1)(releaseGoalHold(nativeThreadId, event)), ), - Effect.forkIn(scope), + // The grace window starts when the turn completes, not when the fiber is scheduled. + Effect.forkIn(scope, { startImmediately: true }), ); return; } @@ -5665,6 +5661,51 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }, ); + // A goal must not read as active once its run ends. Claiming the hold first + // makes a turn Codex starts during the pause an orphan, which is stopped. + const pauseUncontinuedGoal = Effect.fnUntraced(function* ( + nativeThreadId: string, + expected: CodexRootTerminalEvent, + ) { + const hold = goalHolds.get(nativeThreadId); + if ( + hold?.event !== expected || + goalStops.has(nativeThreadId) || + goalsByNativeThread.get(nativeThreadId)?.status !== "active" + ) { + return; + } + goalHolds.delete(nativeThreadId); + // Keeps a turn Codex starts before settlement an orphan once the goal reads paused. + goalStops.set(nativeThreadId, (goalStops.get(nativeThreadId) ?? 0) + 1); + yield* Effect.logWarning("orchestration-v2.codex-goal-continuation-expired", { + nativeThreadId, + }); + yield* client + .request("thread/goal/set", { threadId: nativeThreadId, status: "paused" }) + .pipe( + // The hold is already claimed, so an unanswered pause must not keep the run open. + Effect.timeout("10 seconds"), + Effect.flatMap(({ goal }) => { + goalsByNativeThread.set(nativeThreadId, providerGoalFromCodex(goal)); + return emitGoalUpdate(nativeThreadId); + }), + Effect.catch((cause) => + Effect.logWarning("orchestration-v2.codex-goal-pause-failed", { cause }), + ), + Effect.ensuring( + turnTerminalizationPermit.withPermits(1)(settleGoalHold(hold, "completed")), + ), + Effect.ensuring( + Effect.sync(() => { + const stops = (goalStops.get(nativeThreadId) ?? 1) - 1; + if (stops > 0) goalStops.set(nativeThreadId, stops); + else goalStops.delete(nativeThreadId); + }), + ), + ); + }); + /** Hold the terminalization permit and remove the goalHolds entry before calling. */ const settleGoalHold = Effect.fnUntraced(function* ( hold: CodexGoalHold, @@ -6043,9 +6084,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }), ); + /** Settles a /goal turn that never reaches Codex. State changes reply through the goal row. */ const completeGoalCommandTurn = Effect.fnUntraced(function* ( turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, - reply: string, + reply: string | null, ) { const now = yield* DateTime.now; const nativeId = `goal-command:${turnInput.attemptId}`; @@ -6090,26 +6132,28 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( providerTurn, }); yield* rememberRootProviderThread(turnInput.providerThread); - const artifacts = yield* buildAgentMessageArtifacts( - context, - { id: nativeId, text: reply }, - true, - ); - yield* emitProviderEvent({ - type: "node.updated", - driver: CODEX_PROVIDER, - node: artifacts.node, - }); - yield* emitProviderEvent({ - type: "message.updated", - driver: CODEX_PROVIDER, - message: artifacts.message, - }); - yield* emitProviderEvent({ - type: "turn_item.updated", - driver: CODEX_PROVIDER, - turnItem: artifacts.turnItem, - }); + if (reply !== null) { + const artifacts = yield* buildAgentMessageArtifacts( + context, + { id: nativeId, text: reply }, + true, + ); + yield* emitProviderEvent({ + type: "node.updated", + driver: CODEX_PROVIDER, + node: artifacts.node, + }); + yield* emitProviderEvent({ + type: "message.updated", + driver: CODEX_PROVIDER, + message: artifacts.message, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CODEX_PROVIDER, + turnItem: artifacts.turnItem, + }); + } yield* emitProviderEvent({ type: "provider_turn.updated", driver: CODEX_PROVIDER, @@ -6272,7 +6316,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const runGoalCommand = Effect.fn("CodexAdapterV2.runGoalCommand")( function* ( turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, - command: CodexGoalCommand, + command: OrchestrationV2GoalCommand, ) { const threadId = yield* getNativeThreadId(turnInput.providerThread); rootProviderThreads.set(threadId, turnInput.providerThread); @@ -6294,10 +6338,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (command.type === "clear") { const { cleared } = yield* client.request("thread/goal/clear", { threadId }); goalsByNativeThread.set(threadId, null); - return yield* completeGoalCommandTurn( - turnInput, - cleared ? "Goal cleared." : "No goal to clear.", - ); + return yield* completeGoalCommandTurn(turnInput, cleared ? null : "No goal is set."); } if (current === null && command.type !== "set") { return yield* completeGoalCommandTurn(turnInput, "No goal is set."); @@ -6308,12 +6349,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( status: "paused", }); goalsByNativeThread.set(threadId, providerGoalFromCodex(goal)); - return yield* completeGoalCommandTurn( - turnInput, - "Goal paused. Send /goal resume to continue.", - ); + return yield* completeGoalCommandTurn(turnInput, null); } if (command.type === "set") { + goalUpdatesHeld.add(threadId); if (current !== null) yield* client.request("thread/goal/clear", { threadId }); // Keep paused until our turn starts so Codex cannot start one first. const { goal } = yield* client.request("thread/goal/set", { @@ -6327,12 +6366,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const activation = { stopped: false }; goalActivations.set(threadId, activation); yield* Effect.gen(function* () { + // A bare objective reads like a statement, so the model echoes it back. yield* startNativeTurn( turnInput, command.type === "set" ? yield* toCodexInput({ ...turnInput, - message: { ...turnInput.message, text: command.objective }, + message: { + ...turnInput.message, + text: `Start working toward this goal: ${command.objective}`, + }, }) : [], ); @@ -6366,6 +6409,14 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }, (effect, turnInput) => effect.pipe( + Effect.ensuring( + Effect.suspend(() => { + const threadId = turnInput.providerThread.nativeThreadRef?.nativeId; + return threadId == null || !goalUpdatesHeld.has(threadId) + ? Effect.void + : releaseGoalUpdates(threadId); + }), + ), Effect.mapError( (cause) => new ProviderAdapter.ProviderAdapterTurnStartError({ @@ -6654,9 +6705,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), startTurn: (turnInput) => { const goalCommand = - turnInput.message.attachments.length === 0 && turnInput.restartContinuationOfRunId === undefined - ? parseCodexGoalCommand(turnInput.message.text) + ? parseGoalCommand(turnInput.message) : null; if (goalCommand !== null) return runGoalCommand(turnInput, goalCommand); return Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index 3727df9e3753b..8924943fda29f 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -232,14 +232,15 @@ export const layer: Layer.Layer< }); return CheckpointCaptureServiceV2.of({ - execute: (input) => - execute(input).pipe( + execute: Effect.fn("CheckpointCaptureServiceV2.execute")(function (input) { + return execute(input).pipe( Effect.mapError((cause) => isCheckpointCaptureExecutionError(cause) ? cause : new CheckpointCaptureExecutionError({ ...input, cause }), ), - ), + ); + }), }); }), ); diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts index 5888feed349a7..268549d7bf7fe 100644 --- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts +++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts @@ -34,15 +34,12 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi if (!shared && worktreePath !== null) { // Storage cleanup may have removed the worktree; rollback recreates it. const resolve = (target: string) => - fileSystem - .realPath(target) - .pipe( - Effect.catch((error) => - error.reason._tag === "NotFound" - ? Effect.succeed(path.resolve(target)) - : Effect.fail(error), - ), - ); + fileSystem.realPath(target).pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + (_error) => Effect.succeed(path.resolve(target)), + ), + ); const cwd = yield* resolve(scope.cwd); const worktreeCwd = yield* resolve(worktreePath); shared = cwd !== worktreeCwd; @@ -74,13 +71,12 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi for (const candidate of paths) { if (checkedPaths.has(candidate)) continue; checkedPaths.add(candidate); - const otherCwd = yield* fileSystem - .realPath(candidate) - .pipe( - Effect.catch((error) => - error.reason._tag === "NotFound" ? Effect.succeed(null) : Effect.fail(error), - ), - ); + const otherCwd = yield* fileSystem.realPath(candidate).pipe( + Effect.catchIf( + (error) => error.reason._tag === "NotFound", + (_error) => Effect.succeed(null), + ), + ); if (otherCwd !== null && (contains(cwd, otherCwd) || contains(otherCwd, cwd))) { shared = true; break; diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index 934805ac30fea..bde3af2c2aea9 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -139,6 +139,7 @@ it.effect.each(deliveries)( const sdkMessages = yield* Queue.unbounded(); const offers: SDKUserMessage[] = []; const nativeQueue: SDKUserMessage[] = []; + // @effect-diagnostics-next-line abortControllerInEffect:off - The fake SDK interrupts its batch independently of the test fiber. const batchAbort = new AbortController(); const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ instanceId: modelSelection.instanceId, diff --git a/apps/server/src/orchestration-v2/CommandOutputHub.test.ts b/apps/server/src/orchestration-v2/CommandOutputHub.test.ts index 06475371f4ce4..3740f4f9a2400 100644 --- a/apps/server/src/orchestration-v2/CommandOutputHub.test.ts +++ b/apps/server/src/orchestration-v2/CommandOutputHub.test.ts @@ -163,8 +163,9 @@ const subscribeFrames = (threadId: ThreadId) => const takeFrame = (frames: Queue.Queue) => Queue.take(frames).pipe( - Effect.flatMap((frame) => - frame === "ended" ? Effect.die("command output stream ended early") : Effect.succeed(frame), + Effect.filterOrElse( + (frame) => !(frame === "ended"), + (_frame) => Effect.die("command output stream ended early"), ), ); diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index 6c07a410a1b36..8a8ef82554f63 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -4,6 +4,8 @@ import { ModelSelection, type OrchestrationV2Command, OrchestrationV2ProviderCapabilities, + type OrchestrationV2GoalCommand, + type OrchestrationV2ProviderGoalStatus, type OrchestrationV2Run, OrchestrationV2ThreadProjection, ProviderInstanceId, @@ -128,6 +130,26 @@ export function isNativeMaintenanceCommand(message: { ); } +/** + * A goal command sent into active work stops that work when it starts or + * replaces goal work, or ends a goal that is driving the run. + */ +export function goalCommandStopsActiveRun( + command: OrchestrationV2GoalCommand, + goalStatus: OrchestrationV2ProviderGoalStatus | null, +): boolean { + switch (command.type) { + case "set": + case "resume": + return true; + case "clear": + case "pause": + return goalStatus === "active"; + case "show": + return false; + } +} + export function resolveMessageDispatchIntent( projection: OrchestrationV2ThreadProjection, requestedMode: MessageDispatchMode, diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 92a96944ee536..1cb52118fa894 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -88,7 +88,7 @@ export const layerExecutor: Layer.Layer< const threads = yield* ThreadManagementService.ThreadManagementService; const settings = yield* ServerSettings.ServerSettingsService; return OrchestrationEffectExecutorV2.of({ - execute: (effect, options) => { + execute: Effect.fn("OrchestrationEffectExecutorV2.execute")(function (effect, options) { const willRetry = options?.willRetry ?? false; switch (effect.request.type) { case "provider-runtime.continue": { @@ -170,14 +170,14 @@ export const layerExecutor: Layer.Layer< cause, }), ), - Effect.catch((cause) => - request.subagent === undefined && - isNonRetryableProviderTurnControlFailure( - request.type, - Cause.pretty(Cause.fail(cause)), - ) - ? Effect.void - : Effect.fail(cause), + Effect.catchIf( + (cause) => + request.subagent === undefined && + isNonRetryableProviderTurnControlFailure( + request.type, + Cause.pretty(Cause.fail(cause)), + ), + () => Effect.void, ), Effect.andThen((outcome) => request.subagent !== undefined && outcome === undefined @@ -550,7 +550,7 @@ export const layerExecutor: Layer.Layer< ), ); } - }, + }), }); }), ); diff --git a/apps/server/src/orchestration-v2/EventStore.ts b/apps/server/src/orchestration-v2/EventStore.ts index 6a0afd60448fd..e2125508dee8f 100644 --- a/apps/server/src/orchestration-v2/EventStore.ts +++ b/apps/server/src/orchestration-v2/EventStore.ts @@ -107,8 +107,8 @@ const layerBase: Layer.Layer - applicationEvents.appendAgentEvents(input).pipe( + append: Effect.fn("EventStoreV2.append")(function (input) { + return applicationEvents.appendAgentEvents(input).pipe( Effect.mapError( (cause) => new EventStoreAppendEventsError({ @@ -116,20 +116,22 @@ const layerBase: Layer.Layer - applicationEvents + ); + }), + appendProjectEvent: Effect.fn("EventStoreV2.appendProjectEvent")(function (event) { + return applicationEvents .appendProjectEvent(event) .pipe( Effect.mapError((cause) => new EventStoreAppendEventsError({ eventCount: 1, cause })), - ), + ); + }), read, readByCommandId: ({ commandId }) => applicationEvents .readAgentEvents({ commandId }) .pipe(Stream.mapError((cause) => new EventStoreReadEventsError({ cause }))), - latestSequence: (input) => - applicationEvents.latestAgentSequence(input?.threadId).pipe( + latestSequence: Effect.fn("EventStoreV2.latestSequence")(function (input) { + return applicationEvents.latestAgentSequence(input?.threadId).pipe( Effect.mapError( (cause) => new EventStoreReadEventsError({ @@ -137,7 +139,8 @@ const layerBase: Layer.Layer new EventStoreReadEventsError({ cause })), ), diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 2ce2b5ae5e462..b21f76b32444a 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -737,6 +737,7 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { }); let afterSequence = created[0]!.sequence; + // oxlint-disable-next-line t3code/no-polling-loop-in-tests -- Fixed-count writes exercise the catch-up/live handoff; each iteration awaits its event rather than polling. for (let index = 1; index <= 32; index += 1) { const nextEvent = { id: EventId.make(`event:foundation-stream-race:${index}`), @@ -2426,6 +2427,8 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { const releaseA1 = yield* Deferred.make(); const releaseA2 = yield* Deferred.make(); const releaseB1 = yield* Deferred.make(); + const settled = yield* Deferred.make(); + const completed = yield* Ref.make(0); const gates = new Map([ [effectA1, { started: startedA1, release: releaseA1 }], [effectA2, { started: startedA2, release: releaseA2 }], @@ -2447,7 +2450,24 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { workerId: "concurrency-worker", }).pipe( Layer.provide( - Layer.merge(Layer.succeed(EffectOutbox.EffectOutboxV2, outbox), layerExecutor), + Layer.merge( + Layer.succeed(EffectOutbox.EffectOutboxV2, { + ...outbox, + succeed: (input) => + outbox + .succeed(input) + .pipe( + Effect.tap(() => + Ref.updateAndGet(completed, (count) => count + 1).pipe( + Effect.flatMap((count) => + count === 3 ? Deferred.succeed(settled, undefined) : Effect.void, + ), + ), + ), + ), + }), + layerExecutor, + ), ), ); @@ -2493,13 +2513,12 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { yield* Deferred.succeed(releaseB1, undefined); yield* Deferred.await(startedA2); yield* Deferred.succeed(releaseA2, undefined); - let settled = false; - while (!settled) { - settled = (yield* outbox.listByCommandId(commandId)).every( + yield* Deferred.await(settled); + assert.isTrue( + (yield* outbox.listByCommandId(commandId)).every( (effect) => effect.status === "succeeded", - ); - if (!settled) yield* Effect.yieldNow; - } + ), + ); }).pipe(Effect.provide(layerWorker), Effect.scoped); }), ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 908293b247bc3..dbf51b67b00af 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -55,6 +55,7 @@ import { type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, latestProviderTurnForAttempt, + parseGoalCommand, orchestrationV2RunWorkStartedAt, ProviderInstanceId, ProviderInteractionMode, @@ -93,6 +94,7 @@ import { import { CheckpointServiceV2 } from "./CheckpointService.ts"; import { CommandPolicyV2, + goalCommandStopsActiveRun, isNativeMaintenanceCommand, resolveMessageDispatchIntent, } from "./CommandPolicy.ts"; @@ -451,13 +453,6 @@ function wakeWorkStartedAt( return previous === undefined ? {} : { workStartedAt: orchestrationV2RunWorkStartedAt(previous) }; } -function isGoalCommand(message: { - readonly text: string; - readonly attachments: ReadonlyArray; -}): boolean { - return message.attachments.length === 0 && /^\/goal(?:\s|$)/u.test(message.text.trim()); -} - const threadPullRequestLinksEqual = Schema.toEquivalence(Schema.NullOr(ThreadLinkedPullRequest)); function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { @@ -621,10 +616,12 @@ function isBlockingRun(run: OrchestrationV2Run): boolean { } /** Waiting runs only drain post-terminal output; their agent turn is over and still needs a wake. */ +function isLiveRun(run: OrchestrationV2Run): boolean { + return run.status === "preparing" || run.status === "starting" || run.status === "running"; +} + function hasLiveRun(projection: Pick): boolean { - return projection.runs.some( - (run) => run.status === "preparing" || run.status === "starting" || run.status === "running", - ); + return projection.runs.some(isLiveRun); } function withPullRequestWatch( @@ -986,6 +983,35 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const threadForkService = yield* ThreadForkServiceV2; const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor; + /** The driver when this provider runs `/goal` natively, else undefined. */ + const goalDriverFor = Effect.fn("Orchestrator.goalDriverFor")(function* ( + command: OrchestrationV2ServerCommand, + providerInstanceId: ProviderInstanceId, + ) { + const { driver } = yield* providerAdapters + .get(providerInstanceId) + .pipe(mapDispatchError(command)); + return driver === "codex" || driver === "claudeAgent" ? driver : undefined; + }); + + /** Claude Code reads `/goal pause` and `/goal resume` as new goals named "pause" and "resume". */ + const ensureGoalCommandSupported = Effect.fn("Orchestrator.ensureGoalCommandSupported")( + function* ( + command: OrchestrationV2ServerCommand, + message: { readonly text: string; readonly attachments: ReadonlyArray }, + providerInstanceId: ProviderInstanceId, + ) { + const goalCommand = parseGoalCommand(message); + if (goalCommand?.type !== "pause" && goalCommand?.type !== "resume") return; + if ((yield* goalDriverFor(command, providerInstanceId)) !== "claudeAgent") return; + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "Claude goals cannot be paused or resumed. Send /goal clear to remove the goal.", + }); + }, + ); + const mapDispatchError = (command: OrchestrationV2ServerCommand) => (effect: Effect.Effect): Effect.Effect => @@ -4277,7 +4303,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : "Signing out must run as a separate turn. Queue it or wait for the active turn to finish.", }); } - if (isGoalCommand(input)) { + if (parseGoalCommand(input) !== null) { return yield* new OrchestratorDispatchError({ commandId: input.command.commandId, commandType: input.command.type, @@ -5201,6 +5227,45 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "queue_after_active" }; } + // Codex and Claude own /goal; elsewhere it is ordinary text that cannot steer. + const parsedGoalCommand = parseGoalCommand(command); + const goalCommand = + parsedGoalCommand === null || + (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined + ? null + : parsedGoalCommand; + let goalStopRunId: RunId | undefined; + if (goalCommand !== null) { + yield* ensureGoalCommandSupported(command, command, modelSelection.instanceId); + // A goal command never joins a running turn. One that starts or ends goal + // work stops the run and goes first in the queue; the rest wait. A send + // that asked to be queued (no delivery intent) only queues, and a run + // that is only finishing or running background work is never stopped. + const resolvedMode = dispatchMode; + const target = + resolvedMode.type === "steer_active" || resolvedMode.type === "restart_active" + ? projection.runs.find((run) => run.id === resolvedMode.targetRunId) + : resolvedMode.type === "queue_after_active" && command.deliveryIntent !== undefined + ? projection.runs.findLast(isLiveRun) + : undefined; + if (target !== undefined) { + const goal = projection.providerThreads.find( + (candidate) => candidate.id === target.providerThreadId, + )?.goal; + const targetMessage = projection.messages.find( + (message) => message.id === target.userMessageId, + ); + if ( + isLiveRun(target) && + goalCommandStopsActiveRun(goalCommand, goal?.status ?? null) && + (targetMessage === undefined || !isNativeMaintenanceCommand(targetMessage)) && + !(yield* stopReachedRun(command, command.threadId, target.id)) + ) { + goalStopRunId = target.id; + } + dispatchMode = { type: "queue_after_active" }; + } + } if ( command.notification !== undefined && (command.createdBy !== "agent" || @@ -5546,12 +5611,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? { queueHeld: true } : {}), queuePosition: - Math.max( - 0, - ...projection.runs - .filter((candidate) => candidate.status === "queued") - .map((candidate) => candidate.queuePosition ?? candidate.ordinal), - ) + 1, + goalStopRunId !== undefined + ? 1 + : Math.max( + 0, + ...projection.runs + .filter((candidate) => candidate.status === "queued") + .map((candidate) => candidate.queuePosition ?? candidate.ordinal), + ) + 1, requestedAt: now, startedAt: null, completedAt: null, @@ -5704,6 +5771,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, }); } + if (goalStopRunId !== undefined) { + return yield* stopRunForGoalCommand({ + command, + events, + effects, + projection: yield* getProjectionWithPendingEvents(command.threadId, events), + queuedRunId: runId, + targetRunId: goalStopRunId, + now, + }); + } return; } const pendingForkTransfer = pendingForkTransferForThread(projection); @@ -8269,6 +8347,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const now = yield* DateTime.now; const emitEvent = emit(events, command); + const parsedGoalCommand = parseGoalCommand(queuedMessage); + const goalCommand = + parsedGoalCommand === null || + (yield* goalDriverFor(command, queuedRun.providerInstanceId)) === undefined + ? null + : parsedGoalCommand; + if (goalCommand !== null) { + yield* ensureGoalCommandSupported(command, queuedMessage, queuedRun.providerInstanceId); + const target = projection.runs.find((run) => run.id === command.targetRunId); + const goal = projection.providerThreads.find( + (candidate) => candidate.id === target?.providerThreadId, + )?.goal; + const targetMessage = projection.messages.find( + (message) => message.id === target?.userMessageId, + ); + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: queuedRun.id, + nodeId: queuedRootNode.id, + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: { ...queuedRun, queuePosition: 1 }, + }); + const stops = + target !== undefined && + isLiveRun(target) && + goalCommandStopsActiveRun(goalCommand, goal?.status ?? null) && + (targetMessage === undefined || !isNativeMaintenanceCommand(targetMessage)) && + !(yield* stopReachedRun(command, command.threadId, target.id)); + return yield* stopRunForGoalCommand({ + command, + events, + effects, + projection, + queuedRunId: queuedRun.id, + targetRunId: stops ? target.id : undefined, + now, + }); + } yield* emitEvent({ type: "run.updated", threadId: command.threadId, @@ -8579,6 +8697,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: "A guest's message cannot be edited. Cancel it instead.", }); } + yield* ensureGoalCommandSupported( + command, + { text: command.text, attachments: command.attachments ?? queuedMessage.attachments }, + queuedRun.providerInstanceId, + ); const queuedTurnItem = projection.turnItems.find( (candidate) => candidate.type === "user_message" && candidate.messageId === queuedMessage.id, ); @@ -10370,6 +10493,73 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); + /** Puts a queued goal command first and, given a target, stops the run in its way. */ + const stopRunForGoalCommand = Effect.fn("Orchestrator.stopRunForGoalCommand")(function* (input: { + readonly command: Extract< + OrchestrationV2Command, + { readonly type: "message.dispatch" | "queued-message.promote-to-steer" } + >; + readonly events: Ref.Ref>; + readonly effects: Ref.Ref>; + readonly projection: Pick; + readonly queuedRunId: RunId; + readonly targetRunId: RunId | undefined; + readonly now: DateTime.Utc; + }) { + const { command, events, effects, projection, now, targetRunId } = input; + const others = queuedRunsInDeliveryOrder(projection).filter( + (run) => run.id !== input.queuedRunId && !isAutomaticCompletionRun(projection, run), + ); + for (const [index, run] of others.entries()) { + const queuePosition = index + 2; + if (run.queuePosition === queuePosition) continue; + yield* emit( + events, + command, + )({ + type: "run.updated", + threadId: command.threadId, + runId: run.id, + ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...run, queuePosition }, + }); + } + if (targetRunId === undefined) return undefined; + const interruptEvents = yield* Ref.make>([]); + const interruptEffects = yield* Ref.make>([]); + const interrupted = yield* Effect.exit( + dispatchRunInterrupt( + { + type: "run.interrupt", + commandId: command.commandId, + threadId: command.threadId, + runId: targetRunId, + reason: "Stopped to apply /goal", + }, + interruptEvents, + interruptEffects, + ), + ); + // A failed interrupt may have written part of its events, so they are kept apart. + // The goal command then waits for the turn to end. + if (Exit.isFailure(interrupted)) { + yield* Effect.logWarning("goal command could not stop the running turn", { + threadId: command.threadId, + runId: targetRunId, + cause: interrupted.cause, + }); + return undefined; + } + const written = yield* Ref.get(interruptEvents); + const enqueued = yield* Ref.get(interruptEffects); + yield* Ref.update(events, (existing) => [...existing, ...written]); + yield* Ref.update(effects, (existing) => [...existing, ...enqueued]); + // Like Stop: a run stopped before its provider started also abandons that start. + return interrupted.value; + }); + const dispatchThreadStop = Effect.fn("Orchestrator.dispatchThreadStop")(function* ( command: Extract, events: Ref.Ref>, @@ -11708,7 +11898,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio text: guestSend.text, context: { version: 1 as const, records: [], guest: guestSend.guest }, }; - yield* dispatchMessage(dispatched, events, effects); + cancelUnsettledEffects = yield* dispatchMessage(dispatched, events, effects); yield* recordSubagentFollowup(dispatched, events).pipe(mapDispatchError(command)); break; } @@ -11768,7 +11958,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cancelUnsettledEffects = yield* dispatchThreadStop(command, events, effects); break; case "queued-message.promote-to-steer": - yield* dispatchQueuedMessagePromoteToSteer(command, events, effects); + cancelUnsettledEffects = yield* dispatchQueuedMessagePromoteToSteer( + command, + events, + effects, + ); break; case "queued-run.start": case "queue.resume": { @@ -11980,21 +12174,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } const plan = yield* dispatchOnce(command).pipe( - Effect.flatMap((planned) => - planned.events.length > 0 || - command.type === "thread.background-work.settle" || - command.type === "thread.stop" || - command.type === "subagent.stop" || - // A second Stop sharing, or one after the share already ended, is not an error. - command.type === "thread.guest-share.close" - ? Effect.succeed(planned) - : Effect.fail( - new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: "Command produced no domain events.", - }), - ), + Effect.filterOrFail( + (planned) => + planned.events.length > 0 || + command.type === "thread.background-work.settle" || + command.type === "thread.stop" || + command.type === "subagent.stop" || + // Closing a share again, or after it ended, is not an error. + command.type === "thread.guest-share.close", + (_planned) => + new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "Command produced no domain events.", + }), ), Effect.catch((cause) => Effect.gen(function* () { @@ -12399,13 +12592,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio recoverDelegatedTasks, recoverDelegatedTask, delegatedTaskResultPending, - restartContinuationPending: (run) => - awaitsRestartContinuation(run).pipe(Effect.orElseSucceed(() => false)), - awaitRestartContinuation: (run) => - effectOutbox.awaitSettled(`effect:restart-continuation:${run.id}`).pipe(Effect.ignore), + restartContinuationPending: Effect.fn("OrchestratorV2.restartContinuationPending")( + function (run) { + return awaitsRestartContinuation(run).pipe(Effect.orElseSucceed(() => false)); + }, + ), + awaitRestartContinuation: Effect.fn("OrchestratorV2.awaitRestartContinuation")(function (run) { + return effectOutbox.awaitSettled(`effect:restart-continuation:${run.id}`).pipe(Effect.ignore); + }), dispatch: dispatchWithReceipt, - autoArmLimitRecovery: (input) => - threadDispatch.withLock( + autoArmLimitRecovery: Effect.fn("OrchestratorV2.autoArmLimitRecovery")(function (input) { + return threadDispatch.withLock( input.threadId, Effect.gen(function* () { const thread = yield* projectionStore @@ -12423,7 +12620,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return; yield* dispatchWithReceiptEffect({ type: "thread.metadata.update", ...input }); }), - ), + ); + }), searchThreadStream: (input) => projectionStore .searchThreadStream(input) @@ -12432,77 +12630,108 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }), ), ), - searchThread: (input) => - projectionStore + searchThread: Effect.fn("OrchestratorV2.searchThread")(function (input) { + return projectionStore .searchThread(input) .pipe( Effect.mapError( (cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }), ), - ), - getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) => - projectionStore - .getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly) - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), - getTimelinePage: (threadId, options) => - projectionStore + ); + }), + getThreadHistoryPage: Effect.fn("OrchestratorV2.getThreadHistoryPage")( + function (threadId, cursor, throughEntryId, conversationOnly) { + return projectionStore + .getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly) + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }, + ), + getTimelinePage: Effect.fn("OrchestratorV2.getTimelinePage")(function (threadId, options) { + return projectionStore .getTimelinePage(threadId, options) - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), - getMessageCount: (threadId) => - projectionStore + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }), + getMessageCount: Effect.fn("OrchestratorV2.getMessageCount")(function (threadId) { + return projectionStore .getMessageCount(threadId) - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), - getTurnItem: (input) => - projectionStore + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }), + getTurnItem: Effect.fn("OrchestratorV2.getTurnItem")(function (input) { + return projectionStore .getTurnItem(input) .pipe( Effect.mapError( (cause) => new OrchestratorProjectionError({ threadId: input.threadId, cause }), ), - ), - getThreadRecords: (threadId, fields, filter) => - projectionStore - .getThreadRecords(threadId, fields, filter) - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), - getThreadProjection: (threadId) => - projectionStore + ); + }), + getThreadRecords: Effect.fn("OrchestratorV2.getThreadRecords")( + function (threadId, fields, filter) { + return projectionStore + .getThreadRecords(threadId, fields, filter) + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }, + ), + getThreadProjection: Effect.fn("OrchestratorV2.getThreadProjection")(function (threadId) { + return projectionStore .getThreadProjection(threadId) - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), - getCheckpointContext: (threadId) => - projectionStore + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }), + getCheckpointContext: Effect.fn("OrchestratorV2.getCheckpointContext")(function (threadId) { + return projectionStore .getCheckpointContext(threadId) - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), - getThreadSnapshot: (threadId) => - projectionStore + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }), + getThreadSnapshot: Effect.fn("OrchestratorV2.getThreadSnapshot")(function (threadId) { + return projectionStore .getThreadSnapshot(threadId) - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), - getThreadSnapshotWindow: (threadId, options) => - projectionStore - .getThreadSnapshotWindow(threadId, options) - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), - getShellSnapshot: (options) => - projectionStore.getShellSnapshot(options).pipe(Effect.mapError(shellProjectionError)), - listActiveSubagentThreadIds: () => - projectionStore.listActiveSubagentThreadIds().pipe(Effect.mapError(shellProjectionError)), - listOlderSettledThreads: (query) => - projectionStore.listOlderSettledThreads(query).pipe(Effect.mapError(shellProjectionError)), - readShellSnapshot: (options) => - projectionStore + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }), + getThreadSnapshotWindow: Effect.fn("OrchestratorV2.getThreadSnapshotWindow")( + function (threadId, options) { + return projectionStore + .getThreadSnapshotWindow(threadId, options) + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }, + ), + getShellSnapshot: Effect.fn("OrchestratorV2.getShellSnapshot")(function (options) { + return projectionStore.getShellSnapshot(options).pipe(Effect.mapError(shellProjectionError)); + }), + listActiveSubagentThreadIds: Effect.fn("OrchestratorV2.listActiveSubagentThreadIds")( + function () { + return projectionStore + .listActiveSubagentThreadIds() + .pipe(Effect.mapError(shellProjectionError)); + }, + ), + listOlderSettledThreads: Effect.fn("OrchestratorV2.listOlderSettledThreads")(function (query) { + return projectionStore + .listOlderSettledThreads(query) + .pipe(Effect.mapError(shellProjectionError)); + }), + readShellSnapshot: Effect.fn("OrchestratorV2.readShellSnapshot")(function (options) { + return projectionStore .readShellSnapshot(options) .pipe( Effect.mapError(shellProjectionError), Effect.map(Effect.mapError(shellProjectionError)), - ), - getThreadShell: (threadId) => - projectionStore + ); + }), + getThreadShell: Effect.fn("OrchestratorV2.getThreadShell")(function (threadId) { + return projectionStore .getThreadShell(threadId) - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), - findGuestShareThreadId: (shareId) => - projectionStore.findGuestShareThreadId(shareId).pipe(Effect.mapError(shellProjectionError)), - getThreadEventSequence: (threadId) => - eventSink + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }), + findGuestShareThreadId: Effect.fn("OrchestratorV2.findGuestShareThreadId")(function (shareId) { + return projectionStore + .findGuestShareThreadId(shareId) + .pipe(Effect.mapError(shellProjectionError)); + }), + getThreadEventSequence: Effect.fn("OrchestratorV2.getThreadEventSequence")(function (threadId) { + return eventSink .latestSequence({ threadId }) - .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))), + .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + }), streamStoredEvents: eventSink.stream().pipe( Stream.mapError( (cause) => diff --git a/apps/server/src/orchestration-v2/ProjectStore.ts b/apps/server/src/orchestration-v2/ProjectStore.ts index 335522c7542af..4a81ee2b62500 100644 --- a/apps/server/src/orchestration-v2/ProjectStore.ts +++ b/apps/server/src/orchestration-v2/ProjectStore.ts @@ -266,11 +266,14 @@ export const make = Effect.gen(function* () { get, list, findActiveByWorkspaceRoot, - getShell: (projectId) => get(projectId).pipe(Effect.map(Option.map(toShell))), - listShells: (options) => - list(options?.projectIds === undefined ? undefined : { projectIds: options.projectIds }).pipe( - Effect.map((rows) => rows.map(toShell)), - ), + getShell: Effect.fn("ProjectStoreV2.getShell")(function (projectId) { + return get(projectId).pipe(Effect.map(Option.map(toShell))); + }), + listShells: Effect.fn("ProjectStoreV2.listShells")(function (options) { + return list( + options?.projectIds === undefined ? undefined : { projectIds: options.projectIds }, + ).pipe(Effect.map((rows) => rows.map(toShell))); + }), }); }); diff --git a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts index e53ce61bc1259..3a34df29f71f2 100644 --- a/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts +++ b/apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts @@ -75,8 +75,8 @@ export const layerFromProviderInstanceRegistry: Layer.Layer< Effect.gen(function* () { const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; return ProviderAdapterRegistryV2.of({ - get: (instanceId) => - instances.getInstance(instanceId).pipe( + get: Effect.fn("ProviderAdapterRegistryV2.get")(function (instanceId) { + return instances.getInstance(instanceId).pipe( Effect.flatMap((instance) => { if (instance === undefined) return new ProviderAdapterRegistryLookupError({ instanceId }); @@ -131,11 +131,13 @@ export const layerFromProviderInstanceRegistry: Layer.Layer< }, } satisfies ProviderAdapter.ProviderAdapterV2["Service"]); }), - ), - list: () => - instances.listInstances.pipe( + ); + }), + list: Effect.fn("ProviderAdapterRegistryV2.list")(function () { + return instances.listInstances.pipe( Effect.map((available) => available.map((instance) => instance.instanceId)), - ), + ); + }), getMetadata: Effect.fn("ProviderAdapterRegistry.getMetadata")(function* (instanceId) { const instance = yield* instances.getInstance(instanceId); if (instance === undefined) { diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 4dc5b83690721..368c1dd73890b 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -820,6 +820,7 @@ export const layer: Layer.Layer< ), ), ), + // @effect-diagnostics-next-line flatMapConditionalToFilterOrFail:off - The predicate narrows the captured event for the subagent update. Effect.flatMap((storedEvents) => storedEvents.length === 0 || input.event.type !== "subagent.updated" ? Effect.succeed(storedEvents) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 6604edbf82a8c..7a922d79c7317 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -3,6 +3,7 @@ import { expect, it, vi } from "vite-plus/test"; import { it as effectIt } from "@effect/vitest"; import { CheckpointScopeId, + GitCommandError, MessageId, NodeId, ProviderSessionId, @@ -33,6 +34,8 @@ import * as Schema from "effect/Schema"; import * as ServerConfig from "../config.ts"; import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import * as GitWorkflow from "../git/GitWorkflowService.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import { layerRealGit } from "./ProviderTurnStartService.testkit.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProviderAuthService from "../provider/ProviderAuthService.ts"; import * as ServerSettings from "../serverSettings.ts"; @@ -121,6 +124,7 @@ function startWithMissingWorktree( const startRootRun = vi.fn(() => Effect.void); const pruneWorktrees = vi.fn(() => Effect.void); const createWorktree = vi.fn(() => Effect.succeed({} as never)); + const listLocalBranchNames = vi.fn(() => Effect.succeed(["feature/restore"])); const layer = ProviderTurnStart.layer.pipe( Layer.provide( Layer.mergeAll( @@ -142,7 +146,11 @@ function startWithMissingWorktree( ), } as never), layerWorktreeLocation(), - Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees, createWorktree }), + Layer.mock(GitWorkflow.GitWorkflowService)({ + pruneWorktrees, + createWorktree, + listLocalBranchNames, + }), Layer.mock(ProjectService.ProjectService)({ getById: () => Effect.succeedSome({ workspaceRoot: "/tmp/provider-turn-start-project" } as never), @@ -257,6 +265,8 @@ function makeLocalCommandHarness(input: { readonly text: string; readonly worktreePath?: string; readonly worktreesDir?: string; + readonly workspaceRoot?: string; + readonly gitWorkflow?: GitWorkflow.GitWorkflowService["Service"]; readonly fileSystem?: FileSystem.FileSystem; readonly previousNativeSession?: boolean; readonly previousMessages?: ReadonlyArray; @@ -664,7 +674,9 @@ function makeLocalCommandHarness(input: { ({ thread }: Parameters[0]) => Effect.succeed({ cwd: thread.worktreePath ?? "/tmp/native-account-command" } as never), ); - const createWorktree = vi.fn(() => Effect.succeed({} as never)); + const createWorktree = vi.fn(() => + Effect.succeed({} as never), + ); const getThreadRecords = vi.fn(() => Effect.succeed(projection), ); @@ -690,13 +702,18 @@ function makeLocalCommandHarness(input: { input.fileSystem === undefined ? FileSystem.layerNoop({ exists: () => Effect.succeed(true) }) : Layer.succeed(FileSystem.FileSystem, input.fileSystem), - Layer.mock(GitWorkflow.GitWorkflowService)({ - pruneWorktrees: () => Effect.void, - createWorktree, - }), + input.gitWorkflow === undefined + ? Layer.mock(GitWorkflow.GitWorkflowService)({ + pruneWorktrees: () => Effect.void, + listLocalBranchNames: () => Effect.succeed(["feature/restore"]), + createWorktree, + }) + : Layer.succeed(GitWorkflow.GitWorkflowService, input.gitWorkflow), Layer.mock(ProjectService.ProjectService)({ getById: () => - Effect.succeedSome({ workspaceRoot: "/tmp/native-account-project" } as never), + Effect.succeedSome({ + workspaceRoot: input.workspaceRoot ?? "/tmp/native-account-project", + } as never), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ getThreadRecords, @@ -770,6 +787,167 @@ function makeLocalCommandHarness(input: { }; } +effectIt.effect( + "recovers the thread branch tip, falls back to the current project branch, and rejects detached HEAD", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const gitWorkflow = yield* GitWorkflow.GitWorkflowService; + const driver = yield* GitVcsDriver.GitVcsDriver; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-recreate-repo-" }); + const workspaceRoot = path.join(root, "project"); + const worktreesDir = path.join(root, "worktrees"); + const worktreePath = path.join(worktreesDir, "project", "restore"); + yield* fileSystem.makeDirectory(workspaceRoot); + const git = (cwd: string, args: ReadonlyArray) => + driver + .execute({ operation: "test.worktreeRecovery", cwd, args }) + .pipe(Effect.map((result) => result.stdout.trim())); + yield* git(workspaceRoot, ["init", "-b", "main"]); + yield* git(workspaceRoot, ["config", "user.name", "Test"]); + yield* git(workspaceRoot, ["config", "user.email", "test@example.com"]); + yield* git(workspaceRoot, ["commit", "--allow-empty", "-m", "base"]); + yield* git(workspaceRoot, ["worktree", "add", "-b", "feature/restore", worktreePath]); + yield* fileSystem.writeFileString(path.join(worktreePath, "thread.txt"), "thread work"); + yield* git(worktreePath, ["add", "."]); + yield* git(worktreePath, ["commit", "-m", "thread tip"]); + const threadTip = yield* git(worktreePath, ["rev-parse", "HEAD"]); + yield* git(workspaceRoot, ["switch", "-c", "project-current"]); + yield* fileSystem.writeFileString( + path.join(workspaceRoot, "project.txt"), + "new project code", + ); + yield* git(workspaceRoot, ["add", "."]); + yield* git(workspaceRoot, ["commit", "-m", "project tip"]); + const projectTip = yield* git(workspaceRoot, ["rev-parse", "HEAD"]); + expect(projectTip).not.toBe(threadTip); + // Tags must neither hide the thread branch nor select a different recovery tip. + yield* git(workspaceRoot, ["tag", "feature/restore", projectTip]); + yield* git(workspaceRoot, ["tag", "project-current", threadTip]); + + // Reuse the workflow across turns so recovery cannot select a cached project branch. + for (const scenario of ["retained", "deleted", "detached"] as const) { + yield* fileSystem.remove(worktreePath, { recursive: true }); + if (scenario !== "retained") { + yield* git(workspaceRoot, ["worktree", "prune"]); + yield* git(workspaceRoot, ["branch", "-D", "feature/restore"]); + } + if (scenario === "detached") { + yield* git(workspaceRoot, ["switch", "--detach"]); + expect(yield* git(workspaceRoot, ["branch", "--show-current"])).toBe(""); + } + const harness = makeLocalCommandHarness({ + text: "Continue", + workspaceRoot, + worktreePath, + worktreesDir, + fileSystem, + gitWorkflow, + failReadsAfterRunning: true, + }); + const open = harness.open.getMockImplementation()!; + harness.open.mockImplementation(() => + Effect.gen(function* () { + expect(yield* git(worktreePath, ["branch", "--show-current"])).toBe("feature/restore"); + expect(yield* git(worktreePath, ["rev-parse", "HEAD"])).toBe( + scenario === "retained" ? threadTip : projectTip, + ); + expect( + yield* fileSystem.readFileString( + path.join(worktreePath, scenario === "retained" ? "thread.txt" : "project.txt"), + ), + ).toBe(scenario === "retained" ? "thread work" : "new project code"); + return yield* open(); + }).pipe(Effect.orDie), + ); + + yield* harness.start; + + if (scenario === "detached") { + expect(harness.open).not.toHaveBeenCalled(); + expect(harness.startRootRun).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("failed"); + expect(harness.projection().turnItems).toMatchObject([ + { type: "error", failure: { message: expect.stringContaining("no current branch") } }, + ]); + expect(yield* fileSystem.exists(worktreePath)).toBe(false); + expect(yield* git(workspaceRoot, ["branch", "--list", "feature/restore"])).toBe(""); + } else { + expect(harness.open).toHaveBeenCalledOnce(); + expect(harness.startRootRun).toHaveBeenCalledWith( + expect.objectContaining({ + runtimePolicy: expect.objectContaining({ cwd: worktreePath }), + }), + ); + expect(harness.projection().runs.at(-1)?.status).toBe("running"); + } + } + }).pipe(Effect.scoped, Effect.provide(layerRealGit)), +); + +effectIt.effect( + "preserves recreation interrupts and retries, then fails the final attempt before provider start", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const worktreesDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-recreate-failure-", + }); + const worktreePath = path.join(worktreesDir, "project", "restore"); + const harness = makeLocalCommandHarness({ + text: "Continue", + worktreesDir, + worktreePath, + fileSystem, + failReadsAfterRunning: true, + }); + harness.createWorktree.mockImplementationOnce(() => Effect.interrupt); + harness.createWorktree.mockImplementation(() => + Effect.fail( + new GitCommandError({ + operation: "worktree-add", + command: "git worktree add", + cwd: "/tmp/native-account-project", + detail: "fatal: private git diagnostic", + }), + ), + ); + + const interrupted = yield* Effect.exit(harness.start); + expect(interrupted._tag).toBe("Failure"); + if (interrupted._tag === "Failure") + expect(Cause.hasInterruptsOnly(interrupted.cause)).toBe(true); + expect(harness.events).toEqual([]); + expect(harness.projection().runs.at(-1)?.status).toBe("starting"); + + const retry = yield* Effect.result(harness.startWithRetry); + expect(retry).toMatchObject({ _tag: "Failure", failure: { _tag: "ProviderTurnStartError" } }); + expect(harness.events).toEqual([]); + expect(harness.projection().runs.at(-1)?.status).toBe("starting"); + + yield* harness.start; + expect(harness.createWorktree).toHaveBeenCalledTimes(3); + expect(harness.writeIfRunCurrent).toHaveBeenCalledOnce(); + expect(harness.open).not.toHaveBeenCalled(); + expect(harness.startRootRun).not.toHaveBeenCalled(); + const projection = harness.projection(); + expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null }); + expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null }); + expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null }); + expect(projection.turnItems).toMatchObject([ + { + type: "error", + failure: { + message: `Could not recreate the worktree for branch 'feature/restore' at ${worktreePath}.`, + }, + }, + ]); + expect(JSON.stringify(harness.events)).not.toContain("private git diagnostic"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + effectIt.effect("recovers an abandoned failed turn before continuing its native conversation", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.testkit.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.testkit.ts index 6e517ef73a66b..5b614b1e2aa6c 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.testkit.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.testkit.ts @@ -1,3 +1,18 @@ +import { SourceControlProviderError, SourceControlProviderKind } from "@t3tools/contracts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as ServerConfig from "../config.ts"; +import * as GitManager from "../git/GitManager.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; +import * as VcsProjectConfig from "../vcs/VcsProjectConfig.ts"; +import * as VcsProcess from "../vcs/VcsProcess.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; +import * as TextGeneration from "../textGeneration/TextGeneration.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProjectStore from "./ProjectStore.ts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -13,3 +28,35 @@ export const layer = Layer.merge( getById: () => Effect.succeedNone, }), ); + +// Keep repository detection, branch selection and worktree creation on the real Git path. +export const layerRealGit = GitWorkflow.layer.pipe( + Layer.provide(GitManager.layer), + Layer.provide( + Layer.mergeAll( + Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ + resolveLink: () => undefined, + resolve: ({ cwd }) => + Effect.fail( + new SourceControlProviderError({ + provider: SourceControlProviderKind.make("unknown"), + operation: "resolve", + cwd, + detail: "No source control provider in tests", + }), + ), + }), + Layer.mock(TextGeneration.TextGeneration)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}), + Layer.mock(ProjectionStore.ProjectionStoreV2)({}), + Layer.mock(ProjectStore.ProjectStoreV2)({}), + ServerSettings.layerTest(), + ), + ), + Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer))), + Layer.provideMerge(GitVcsDriver.layer), + Layer.provideMerge(VcsProcess.layer), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-recreate-" })), + Layer.provideMerge(NodeServices.layer), +); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index e383835f83568..9d9ae2e646cd5 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -9,11 +9,12 @@ import { type OrchestrationV2Run, type OrchestrationV2RunAttempt, type OrchestrationV2TurnItem, + isCompactionCommandMessage, + parseGoalCommand, RunId, ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; -import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -66,6 +67,28 @@ export class ProviderTurnStartError extends Schema.TaggedError()( + "WorktreeRecreateError", + { + worktreePath: Schema.String, + branch: Schema.String, + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Could not recreate the worktree for branch '${this.branch}' at ${this.worktreePath}.`; + } +} + +class WorktreeRecreateNoBaseError extends Schema.TaggedError()( + "WorktreeRecreateNoBaseError", + { worktreePath: Schema.String, branch: Schema.String }, +) { + override get message(): string { + return `Could not recreate branch '${this.branch}' at ${this.worktreePath}: the project workspace has no current branch to start it from (detached HEAD?).`; + } +} + const isProviderTurnStartError = Schema.is(ProviderTurnStartError); /** @@ -129,6 +152,35 @@ export const layer: Layer.Layer< const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2; const isManagedWorktreePath = yield* makeIsManagedWorktreePath; + const recreateMissingWorktree = Effect.fn("ProviderTurnStartService.recreateMissingWorktree")( + function* (input: { + readonly cwd: string; + readonly worktreePath: string; + readonly branch: string; + }) { + const { cwd, worktreePath, branch } = input; + yield* gitWorkflow.pruneWorktrees({ cwd }); + const localBranchNames = yield* gitWorkflow.listLocalBranchNames(cwd); + if (localBranchNames.includes(branch)) { + yield* gitWorkflow.createWorktree({ cwd, refName: branch, path: worktreePath }); + return; + } + // Recovery can follow an external checkout, before the status cache expires. + yield* gitWorkflow.invalidateLocalStatus(cwd); + const { refName: baseRef } = yield* gitWorkflow.localStatus({ cwd }); + if (baseRef === null) { + return yield* new WorktreeRecreateNoBaseError({ worktreePath, branch }); + } + yield* gitWorkflow.createWorktree({ + cwd, + refName: `refs/heads/${baseRef}`, + newRefName: branch, + baseRefName: `refs/heads/${baseRef}`, + path: worktreePath, + }); + }, + ); + // Build draining callbacks outside startup scope so they cannot retain full thread history. const makeRunControls = (input: { readonly threadId: ThreadId; @@ -282,11 +334,12 @@ export const layer: Layer.Layer< source.status === "interrupted" || (source.status === "completed" && handoff.delivery === undefined && + // Compaction and /goal turns defer history to the next turn. projection.messages.some( (message) => message.id === source.userMessageId && - message.attachments.length === 0 && - message.text.trim().toLowerCase() === "/compact", + (isCompactionCommandMessage(message) || + parseGoalCommand(message) !== null), ))), ))), ); @@ -396,6 +449,39 @@ export const layer: Layer.Layer< }); }, ); + const settleStartFailure = Effect.fn("ProviderTurnStartService.settleStartFailure")( + function* (failed: { + readonly signal: string; + readonly title: string; + readonly error: Error; + readonly message?: string; + }) { + const nestedCause = "cause" in failed.error ? failed.error.cause : undefined; + yield* settleRunBeforeStart({ + signal: failed.signal, + status: "failed", + now: yield* DateTime.now, + providerInstanceId: run.providerInstanceId, + itemProviderThreadId: providerThread.id, + item: { + type: "error", + title: failed.title, + failure: makeProviderFailure({ + cause: failed.error, + message: + failed.message ?? + knownProviderFailureMessage(failed.error) ?? + (nestedCause instanceof Error + ? nestedCause.message + : typeof nestedCause === "string" + ? nestedCause + : failed.error.message), + class: "provider_error", + }), + }, + }); + }, + ); if (message.attachments.length === 0 && message.text.trimStart().startsWith("/")) { const isEmptyCompaction = message.text.trim().toLowerCase() === "/compact" && !projection.hasConversation; @@ -497,24 +583,29 @@ export const layer: Layer.Layer< worktreePath, branch, }); - yield* gitWorkflow.pruneWorktrees({ cwd: project.workspaceRoot }).pipe( - Effect.andThen( - gitWorkflow.createWorktree({ - cwd: project.workspaceRoot, - refName: branch, - path: worktreePath, - }), - ), - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.failCause(cause) - : Effect.logWarning("provider turn start failed to recreate worktree", { - threadId: projection.thread.id, - worktreePath, - cause: Cause.pretty(cause), - }), + const recreateResult = yield* Effect.result( + recreateMissingWorktree({ + cwd: project.workspaceRoot, + worktreePath, + branch, + }).pipe( + Effect.mapError((cause) => + cause._tag === "WorktreeRecreateNoBaseError" + ? cause + : new WorktreeRecreateError({ worktreePath, branch, cause }), + ), ), ); + if (recreateResult._tag === "Failure") { + if (input.willRetry === true) return yield* recreateResult.failure; + yield* settleStartFailure({ + signal: "worktree-recreate-failure", + title: "Couldn't recreate thread workspace", + error: recreateResult.failure, + message: recreateResult.failure.message, + }); + return; + } } } } @@ -550,37 +641,6 @@ export const layer: Layer.Layer< const existingSessionProjection = projection.providerSessions.find( (candidate) => candidate.id === providerSessionId, ); - const settleStartFailure = Effect.fn("ProviderTurnStartService.settleStartFailure")( - function* (failed: { - readonly signal: string; - readonly title: string; - readonly error: Error; - }) { - const nestedCause = "cause" in failed.error ? failed.error.cause : undefined; - yield* settleRunBeforeStart({ - signal: failed.signal, - status: "failed", - now: yield* DateTime.now, - providerInstanceId: run.providerInstanceId, - itemProviderThreadId: providerThread.id, - item: { - type: "error", - title: failed.title, - failure: makeProviderFailure({ - cause: failed.error, - message: - knownProviderFailureMessage(failed.error) ?? - (nestedCause instanceof Error - ? nestedCause.message - : typeof nestedCause === "string" - ? nestedCause - : failed.error.message), - class: "provider_error", - }), - }, - }); - }, - ); const failedRuns = new Map( projection.runs .filter( @@ -1036,6 +1096,9 @@ export const layer: Layer.Layer< text: message.text, records: message.context?.records ?? [], }); + // Codex and Claude parse /goal from the prompt, so it goes verbatim and history waits a turn. + const goalDriver = session.driver === "codex" || session.driver === "claudeAgent"; + const goalCommand = goalDriver && parseGoalCommand(message) !== null; // The provider turn marks cancellation work delivered; restart continuations use their own text or resume natively. const noteContinuation = isRestartNoteContinuation( run, @@ -1050,8 +1113,8 @@ export const layer: Layer.Layer< projection.messages .filter( (candidate) => - candidate.attachments.length === 0 && - candidate.text.trim().toLowerCase() === "/compact", + isCompactionCommandMessage(candidate) || + (goalDriver && parseGoalCommand(candidate) !== null), ) .map((candidate) => candidate.id), ), @@ -1199,7 +1262,7 @@ export const layer: Layer.Layer< ]; const delivery = yield* deliverContextHandoffs({ handoffs: [...effectiveHandoffs, ...retryHandoff], - deferInline: compact, + deferInline: compact || goalCommand, providerThread: runningProviderThread, budget: Effect.gen(function* () { return handoffBudget({ @@ -1253,7 +1316,10 @@ export const layer: Layer.Layer< ...(noteContinuation ? promptedInput : turnInput), message: { ...turnInput.message, - text: context === "" ? userText : `${context}\n\nUser message:\n${userText}`, + text: + context === "" || goalCommand + ? userText + : `${context}\n\nUser message:\n${userText}`, }, }).pipe( // Clear pending handoff markers for refused prompts so the next turn retains the native session. diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts index cc3225315620f..e557ecd770e1a 100644 --- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts @@ -139,7 +139,7 @@ type CommandExecution = Extract command.test(input))) return []; const script = shellScript(input); const code = shellCode(script); diff --git a/apps/server/src/orchestration-v2/ResourceCleanupService.ts b/apps/server/src/orchestration-v2/ResourceCleanupService.ts index 2fbb7d7f1c02c..4ad8a6e8951ae 100644 --- a/apps/server/src/orchestration-v2/ResourceCleanupService.ts +++ b/apps/server/src/orchestration-v2/ResourceCleanupService.ts @@ -39,23 +39,29 @@ export const layer = Layer.effect( const terminals = yield* TerminalManager.TerminalManager; const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService; return { - cleanupScheduledTasks: (threadId: ThreadId) => - scheduledTasks + cleanupScheduledTasks: Effect.fn("ResourceCleanupService.cleanupScheduledTasks")(function ( + threadId: ThreadId, + ) { + return scheduledTasks .deleteForThread(threadId) .pipe( Effect.mapError( (cause) => new ResourceCleanupError({ operation: "scheduled-tasks", threadId, cause }), ), - ), - cleanupTerminals: (threadId: string) => - terminals + ); + }), + cleanupTerminals: Effect.fn("ResourceCleanupService.cleanupTerminals")(function ( + threadId: string, + ) { + return terminals .close({ threadId, deleteHistory: true }) .pipe( Effect.mapError( (cause) => new ResourceCleanupError({ operation: "terminal", threadId, cause }), ), - ), + ); + }), // Coder: there is no browser preview, so a thread has no preview sessions to close. cleanupPreviews: () => Effect.void, // Coder: deleting or reverting a thread never deletes its attachments. diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 6caab3f2a847e..59b5c46880f55 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -923,13 +923,13 @@ export const layer: Layer.Layer< ordinalWithinScope: Math.max(0, input.run.ordinal - 1), }) .pipe( - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.failCause(cause) - : Effect.logWarning( - "orchestration V2 checkpoint baseline capture failed; starting provider without a baseline", - { runId: input.run.id }, - ), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (_cause) => + Effect.logWarning( + "orchestration V2 checkpoint baseline capture failed; starting provider without a baseline", + { runId: input.run.id }, + ), ), ); if ( diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.ts b/apps/server/src/orchestration-v2/RuntimePolicy.ts index c5b568b8f7e43..d8b545d16e902 100644 --- a/apps/server/src/orchestration-v2/RuntimePolicy.ts +++ b/apps/server/src/orchestration-v2/RuntimePolicy.ts @@ -53,12 +53,13 @@ export class RuntimePolicyV2 extends Context.Service = Layer.succeed(RuntimePolicyV2, { - resolve: (input) => - Effect.succeed({ + resolve: Effect.fn("RuntimePolicyV2.resolve")(function (input) { + return Effect.succeed({ runtimeMode: input.thread.runtimeMode, interactionMode: input.thread.interactionMode, cwd: input.thread.worktreePath, - }), + }); + }), }); function providerRuntimeMode( diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 1a5ee50872706..2cc6ee6f825b2 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -547,7 +547,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* yield* Fiber.join(running); return threadId; }); - return { events, started, steered, layer, startFirstTurn }; + return { cwd, events, started, steered, layer, startFirstTurn }; }); it.effect("sends a selected held message once and preserves the remaining queue order", () => @@ -1048,3 +1048,218 @@ it.effect("queues a plain send behind the stopped queue and releases its hold", }), ), ); + +const goalHarness = Effect.fn("goalHarness")(function* (name: string) { + const harness = yield* nextTurnSelectionHarness(name); + const send = (id: string, text: string, delivery: "queue" | "auto") => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(id), + threadId: ThreadId.make(`thread:${name}`), + messageId: MessageId.make(`message:${id}`), + text, + attachments: [], + modelSelection: runSelection, + ...(delivery === "queue" + ? { dispatchMode: { type: "queue_after_active" } } + : { dispatchMode: { type: "start_immediately" }, deliveryIntent: "auto" }), + createdBy: "user", + creationSource: "web", + }); + }); + const read = (threadId: ThreadId) => + Effect.gen(function* () { + const projection = yield* (yield* Orchestrator.OrchestratorV2).getThreadProjection(threadId); + const textOf = (run: (typeof projection.runs)[number]) => + projection.messages.find((message) => message.id === run.userMessageId)?.text; + return { + queue: projection.runs + .filter((run) => run.status === "queued") + .toSorted((left, right) => (left.queuePosition ?? 0) - (right.queuePosition ?? 0)) + .map(textOf), + started: harness.started.map((turn) => turn.message.text), + stopRequested: projection.turnItems.some( + (item) => + item.type === "run_interrupt_request" && item.runId === harness.started[0]?.runId, + ), + }; + }); + return { ...harness, send, read }; +}); + +it.effect("stops the running turn and starts a goal sent into it next", () => + Effect.scoped( + Effect.gen(function* () { + const { steered, layer, startFirstTurn, send, read } = yield* goalHarness("goal-steer"); + yield* Effect.gen(function* () { + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* send("queued", "queued", "queue"); + yield* send("goal", "/goal all tests pass", "auto"); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: ["queued"], + started: ["first", "/goal all tests pass"], + stopRequested: true, + }); + }).pipe(Effect.provide(layer)); + }), + ), +); + +it.effect("queues a goal clear without stopping work when no goal drives it", () => + Effect.scoped( + Effect.gen(function* () { + const { steered, layer, startFirstTurn, send, read } = yield* goalHarness("goal-clear"); + yield* Effect.gen(function* () { + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* send("queued", "queued", "queue"); + yield* send("clear", "/goal clear", "auto"); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: ["queued", "/goal clear"], + started: ["first"], + stopRequested: false, + }); + }).pipe(Effect.provide(layer)); + }), + ), +); + +it.effect("promotes a queued goal by stopping the running turn", () => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn, send, read } = + yield* goalHarness("goal-promote"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* send("queued", "queued", "queue"); + yield* send("goal", "/goal ship it", "queue"); + const goalRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === MessageId.make("message:goal"), + )!; + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: goalRun.id, + targetRunId: started[0]!.runId, + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: ["queued"], + started: ["first", "/goal ship it"], + stopRequested: true, + }); + }).pipe(Effect.provide(layer)); + }), + ), +); + +it.effect("stops a turn that is still starting when a goal is sent into it", () => + Effect.scoped( + Effect.gen(function* () { + const { cwd, layer, send, started } = yield* goalHarness("goal-during-start"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make("thread:goal-during-start"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make("project:goal-during-start"), + title: "Goal during start", + modelSelection: runSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + // The stopped run's end starts the queue, which then needs one more drain. + const goalStarting = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => event.type === "run.updated" && event.payload.status === "starting", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped({ startImmediately: true }), + ); + yield* send("first", "first", "auto"); + yield* send("goal", "/goal all tests pass", "auto"); + yield* worker.drain(); + yield* Fiber.join(goalStarting); + yield* worker.drain(); + + const projection = yield* orchestrator.getThreadProjection(threadId); + const statusOf = (text: string) => + projection.runs.find( + (run) => + projection.messages.find((message) => message.id === run.userMessageId)?.text === + text, + )?.status; + assert.equal(statusOf("first"), "interrupted"); + assert.deepEqual( + started.map((turn) => turn.message.text), + ["/goal all tests pass"], + ); + }).pipe(Effect.provide(layer)); + }), + ), +); + +it.effect("stops the running turn when a goal clear ends the goal driving it", () => + Effect.scoped( + Effect.gen(function* () { + const { events, layer, startFirstTurn, send, read, steered } = + yield* goalHarness("goal-clear-active"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const providerThread = (yield* orchestrator.getThreadProjection(threadId)) + .providerThreads[0]!; + const goalSeen = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "provider-thread.updated" && event.payload.goal?.status === "active", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped({ startImmediately: true }), + ); + yield* Queue.offer(events, { + type: "provider_thread.updated", + driver, + providerThread: { + ...providerThread, + goal: { objective: "all tests pass", status: "active" }, + }, + }); + yield* Fiber.join(goalSeen); + yield* send("clear", "/goal clear", "auto"); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: [], + started: ["first", "/goal clear"], + stopRequested: true, + }); + }).pipe(Effect.provide(layer)); + }), + ), +); diff --git a/apps/server/src/orchestration-v2/ThreadLifecycleService.ts b/apps/server/src/orchestration-v2/ThreadLifecycleService.ts index fad7693ba220e..dd0c94538eff0 100644 --- a/apps/server/src/orchestration-v2/ThreadLifecycleService.ts +++ b/apps/server/src/orchestration-v2/ThreadLifecycleService.ts @@ -88,54 +88,61 @@ const make = Effect.gen(function* () { ); return ThreadLifecycleService.of({ - archive: (input) => - dispatch("archive", input.threadId, { + archive: Effect.fn("ThreadLifecycleService.archive")(function (input) { + return dispatch("archive", input.threadId, { type: "thread.archive", commandId: input.commandId, threadId: input.threadId, - }), - unarchive: (input) => - dispatch("unarchive", input.threadId, { + }); + }), + unarchive: Effect.fn("ThreadLifecycleService.unarchive")(function (input) { + return dispatch("unarchive", input.threadId, { type: "thread.unarchive", commandId: input.commandId, threadId: input.threadId, - }), - delete: (input) => - dispatch("delete", input.threadId, { + }); + }), + delete: Effect.fn("ThreadLifecycleService.delete")(function (input) { + return dispatch("delete", input.threadId, { type: "thread.delete", commandId: input.commandId, threadId: input.threadId, - }), - updateMetadata: (input) => - dispatch("update-metadata", input.threadId, { + }); + }), + updateMetadata: Effect.fn("ThreadLifecycleService.updateMetadata")(function (input) { + return dispatch("update-metadata", input.threadId, { type: "thread.metadata.update", commandId: input.commandId, threadId: input.threadId, ...(input.title === undefined ? {} : { title: input.title }), ...(input.branch === undefined ? {} : { branch: input.branch }), ...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }), - }), - setRuntimeMode: (input) => - dispatch("set-runtime-mode", input.threadId, { + }); + }), + setRuntimeMode: Effect.fn("ThreadLifecycleService.setRuntimeMode")(function (input) { + return dispatch("set-runtime-mode", input.threadId, { type: "thread.runtime-mode.set", commandId: input.commandId, threadId: input.threadId, runtimeMode: input.runtimeMode, - }), - setInteractionMode: (input) => - dispatch("set-interaction-mode", input.threadId, { + }); + }), + setInteractionMode: Effect.fn("ThreadLifecycleService.setInteractionMode")(function (input) { + return dispatch("set-interaction-mode", input.threadId, { type: "thread.interaction-mode.set", commandId: input.commandId, threadId: input.threadId, interactionMode: input.interactionMode, - }), - setModelSelection: (input) => - dispatch("set-model-selection", input.threadId, { + }); + }), + setModelSelection: Effect.fn("ThreadLifecycleService.setModelSelection")(function (input) { + return dispatch("set-model-selection", input.threadId, { type: "thread.model-selection.set", commandId: input.commandId, threadId: input.threadId, modelSelection: input.modelSelection, - }), + }); + }), }); }); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 5cc26ff621df7..5a71ce49a2b08 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -708,15 +708,14 @@ const make = Effect.gen(function* () { cause, }), ), - Effect.flatMap((projection) => - projection.thread.projectId === input.projectId && projection.thread.deletedAt === null - ? Effect.succeed(projection) - : Effect.fail( - new ThreadManagementThreadNotFoundError({ - projectId: input.projectId, - threadId: input.threadId, - }), - ), + Effect.filterOrFail( + (projection) => + projection.thread.projectId === input.projectId && projection.thread.deletedAt === null, + (_projection) => + new ThreadManagementThreadNotFoundError({ + projectId: input.projectId, + threadId: input.threadId, + }), ), ); @@ -735,15 +734,14 @@ const make = Effect.gen(function* () { cause, }), ), - Effect.flatMap((projection) => - projection.thread.projectId === input.projectId && projection.thread.deletedAt === null - ? Effect.succeed(projection) - : Effect.fail( - new ThreadManagementThreadNotFoundError({ - projectId: input.projectId, - threadId: input.threadId, - }), - ), + Effect.filterOrFail( + (projection) => + projection.thread.projectId === input.projectId && projection.thread.deletedAt === null, + (_projection) => + new ThreadManagementThreadNotFoundError({ + projectId: input.projectId, + threadId: input.threadId, + }), ), ); @@ -1207,34 +1205,46 @@ const make = Effect.gen(function* () { Effect.as(orchestrator.searchThreadStream(input)), ), ), - searchThread: (input) => - ensureProjectionTranscript(input.threadId).pipe( + searchThread: Effect.fn("ThreadManagementService.searchThread")(function (input) { + return ensureProjectionTranscript(input.threadId).pipe( Effect.andThen(orchestrator.searchThread(input)), - ), + ); + }), dispatch, - getThreadHistoryPage: (threadId, cursor, throughEntryId, conversationOnly) => - ensureProjectionTranscript(threadId).pipe( - Effect.andThen( - orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly), - ), - ), - getTimelinePage: (threadId, options) => - ensureProjectionTranscript(threadId).pipe( - Effect.andThen(orchestrator.getTimelinePage(threadId, options)), - ), - getMessageCount: (threadId) => - ensureProjectionTranscript(threadId).pipe( + getThreadHistoryPage: Effect.fn("ThreadManagementService.getThreadHistoryPage")( + function (threadId, cursor, throughEntryId, conversationOnly) { + return ensureProjectionTranscript(threadId).pipe( + Effect.andThen( + orchestrator.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly), + ), + ); + }, + ), + getTimelinePage: Effect.fn("ThreadManagementService.getTimelinePage")( + function (threadId, options) { + return ensureProjectionTranscript(threadId).pipe( + Effect.andThen(orchestrator.getTimelinePage(threadId, options)), + ); + }, + ), + getMessageCount: Effect.fn("ThreadManagementService.getMessageCount")(function (threadId) { + return ensureProjectionTranscript(threadId).pipe( Effect.andThen(orchestrator.getMessageCount(threadId)), - ), - getTurnItem: (input) => - ensureProjectionTranscript(input.threadId).pipe( + ); + }), + getTurnItem: Effect.fn("ThreadManagementService.getTurnItem")(function (input) { + return ensureProjectionTranscript(input.threadId).pipe( Effect.andThen(orchestrator.getTurnItem(input)), Effect.map((item) => ({ item: item === null ? null : projectTurnItemForDetail(item) })), - ), - getThreadRecords: (threadId, fields, filter) => - ensureProjectionTranscript(threadId).pipe( - Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)), - ), + ); + }), + getThreadRecords: Effect.fn("ThreadManagementService.getThreadRecords")( + function (threadId, fields, filter) { + return ensureProjectionTranscript(threadId).pipe( + Effect.andThen(orchestrator.getThreadRecords(threadId, fields, filter)), + ); + }, + ), getThreadProjection, getCheckpointContext, getThreadSnapshot, @@ -1273,7 +1283,9 @@ const layerLegacyV1ThreadImporterNoop = Layer.succeed( LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({ pendingThreadCount: Effect.succeed(0), reconcileShells: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }), - ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }), + ensureTranscript: Effect.fn("LegacyV1ThreadImporter.ensureTranscript")(function () { + return Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }); + }), importPendingTranscripts: Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }), }), ); diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts index 4ff74ccf3a872..7b3c09ba15b8a 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts @@ -318,13 +318,13 @@ export const make = Effect.gen(function* () { }); pendingBackfill.delete(thread.id); }).pipe( - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.failCause(cause) - : Effect.logWarning("thread pull request update failed", { - threadId: thread.id, - cause: Cause.pretty(cause), - }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("thread pull request update failed", { + threadId: thread.id, + cause: Cause.pretty(cause), + }).pipe(Effect.tap(() => Effect.sync(() => failBackfill([thread])))), ), ), { discard: true }, diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 35ed1d9721348..1077f341f61b2 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -350,13 +350,13 @@ export const make = Effect.gen(function* () { }, (effect, thread) => effect.pipe( - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.failCause(cause) - : Effect.logWarning("automatic thread settlement skipped", { - threadId: thread.id, - cause: Cause.pretty(cause), - }).pipe(Effect.as(null)), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("automatic thread settlement skipped", { + threadId: thread.id, + cause: Cause.pretty(cause), + }).pipe(Effect.as(null)), ), ), ); @@ -507,13 +507,13 @@ export const make = Effect.gen(function* () { discard: true, }); }).pipe( - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.failCause(cause) - : Effect.logWarning("automatic thread settlement skipped", { - threadIds: group.map((thread) => thread.id), - cause: Cause.pretty(cause), - }), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("automatic thread settlement skipped", { + threadIds: group.map((thread) => thread.id), + cause: Cause.pretty(cause), + }), ), ), { concurrency: 8, discard: true }, @@ -525,12 +525,12 @@ export const make = Effect.gen(function* () { threadId?: ThreadId, ) => sweep(mergedPullRequest, threadId).pipe( - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.failCause(cause) - : Effect.logWarning("automatic thread settlement sweep failed", { - cause: Cause.pretty(cause), - }), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("automatic thread settlement sweep failed", { + cause: Cause.pretty(cause), + }), ), ); // A thread that just stopped must not wait behind a full sweep or another thread's host @@ -590,13 +590,13 @@ export const make = Effect.gen(function* () { }, (effect, threadId) => effect.pipe( - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) - ? Effect.failCause(cause) - : Effect.logWarning("cleaning up a settled thread failed", { - threadId, - cause: Cause.pretty(cause), - }), + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Effect.logWarning("cleaning up a settled thread failed", { + threadId, + cause: Cause.pretty(cause), + }), ), ), ); diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts index a2e6aa599bba1..b73f6a2ab061a 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts @@ -90,15 +90,15 @@ const make = Effect.gen(function* () { thread: OrchestrationV2AppThread, ) { let title: string | undefined; - let history: Array = []; + const history: Array> = []; let forkedFrom = thread.forkedFrom; while (forkedFrom?.type === "run") { const source = yield* messagesThroughRun(forkedFrom.threadId, forkedFrom.runId); - history = [...source.messages, ...history]; + history.push(source.messages); title ??= source.thread.title; forkedFrom = source.thread.forkedFrom; } - const context = formatThreadTitleContext(history); + const context = formatThreadTitleContext(history.reverse().flat()); return title === undefined || context.message.length === 0 ? undefined : { title, history: context.message }; diff --git a/apps/server/src/orchestration-v2/TurnItemPositionStore.ts b/apps/server/src/orchestration-v2/TurnItemPositionStore.ts index a004191e09525..03636b34153c9 100644 --- a/apps/server/src/orchestration-v2/TurnItemPositionStore.ts +++ b/apps/server/src/orchestration-v2/TurnItemPositionStore.ts @@ -103,13 +103,15 @@ export const layer: Layer.Layer - allocate({ + // Per-event normalization shares the enclosing orchestration span. + normalize: Effect.fnUntraced(function* (item, runOrdinal) { + return yield* allocate({ threadId: item.threadId, turnItemId: item.id, runId: item.runId, ...(runOrdinal === undefined ? {} : { runOrdinal }), - }).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal }))), + }).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal }))); + }), }); }), ); diff --git a/apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.ts b/apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.ts index 4ce58753a793e..51951bfc3ad30 100644 --- a/apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.ts +++ b/apps/server/src/orchestration-v2/testkit/CommandOutputRecorder.ts @@ -34,14 +34,15 @@ export const layer: Layer.Layer< CommandOutputHub.CommandOutputHub, CommandOutputHub.CommandOutputHub.of({ ...hub, - append: (input) => - Effect.sync(() => { + append: Effect.fn("CommandOutputHub.append")(function (input) { + return Effect.sync(() => { const previous = recorded.get(input.itemId); recorded.set(input.itemId, { chunks: (previous?.chunks ?? 0) + 1, output: appendTerminalOutput(previous?.output ?? EMPTY_TERMINAL_OUTPUT, input.chunk), }); - }).pipe(Effect.andThen(hub.append(input))), + }).pipe(Effect.andThen(hub.append(input))); + }), }), ).pipe( Context.add(CommandOutputRecorder, { diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 0404496693fa7..77e8bae8f085f 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -279,19 +279,18 @@ export function runOrchestratorV2Scenario( const capturedShellSnapshots = new Map(); let anonymousBackgroundDispatchIndex = 0; - const awaitDispatch = (key: string) => - Effect.gen(function* () { - const fiber = backgroundDispatches.get(key); - if (!fiber) { - return yield* new OrchestratorV2ScenarioStepError({ - scenario: scenario.name, - step: `await:${key}`, - }); - } - const events = yield* Fiber.join(fiber); - backgroundDispatches.delete(key); - storedEventGroups.push(events); - }); + const awaitDispatch = Effect.fn("awaitDispatch")(function* (key: string) { + const fiber = backgroundDispatches.get(key); + if (!fiber) { + return yield* new OrchestratorV2ScenarioStepError({ + scenario: scenario.name, + step: `await:${key}`, + }); + } + const events = yield* Fiber.join(fiber); + backgroundDispatches.delete(key); + storedEventGroups.push(events); + }); const waitForPendingRuntimeRequest = ( threadId: ThreadId, diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index a7ad0421bcccb..64a95e315bc8b 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -372,7 +372,9 @@ export function layerWithRegistry( const layerThreadTitleRegenerationTest = Layer.succeed( ThreadTitleRegenerationService.ThreadTitleRegenerationService, ThreadTitleRegenerationService.ThreadTitleRegenerationService.of({ - execute: () => Effect.void, + execute: Effect.fn("ThreadTitleRegenerationService.execute")(function () { + return Effect.void; + }), }), ); const layerOrchestratorProvided = Orchestrator.layer.pipe( diff --git a/apps/server/src/persistence/PullRequestFilesViewed.ts b/apps/server/src/persistence/PullRequestFilesViewed.ts index f3673ff3fd12b..476643c1f0b36 100644 --- a/apps/server/src/persistence/PullRequestFilesViewed.ts +++ b/apps/server/src/persistence/PullRequestFilesViewed.ts @@ -84,18 +84,19 @@ const make = Effect.gen(function* () { }); return PullRequestFilesViewedRepository.of({ - list: (input) => - listRows(input).pipe( + list: Effect.fn("PullRequestFilesViewedRepository.list")(function (input) { + return listRows(input).pipe( NodeSqliteClient.readOnly, Effect.map((rows) => ({ files: rows.slice(0, MAX_FILES_VIEWED_ROWS), truncated: rows.length > MAX_FILES_VIEWED_ROWS, })), Effect.mapError(toSqlOrDecodeError("listPullRequestFilesViewed", "PullRequestFileViewed")), - ), + ); + }), - set: (input) => - sql + set: Effect.fn("PullRequestFilesViewedRepository.set")(function (input) { + return sql .withTransaction( Effect.forEach( input.files, @@ -141,7 +142,8 @@ const make = Effect.gen(function* () { Effect.mapError( (cause) => new PersistenceSqlError({ operation: "setPullRequestFilesViewed", cause }), ), - ), + ); + }), }); }); diff --git a/apps/server/src/persistence/PullRequestReviewGuides.ts b/apps/server/src/persistence/PullRequestReviewGuides.ts index 6dd2780eceb20..0a12b3f6f74a7 100644 --- a/apps/server/src/persistence/PullRequestReviewGuides.ts +++ b/apps/server/src/persistence/PullRequestReviewGuides.ts @@ -51,8 +51,8 @@ const make = Effect.gen(function* () { const encodeGuide = Schema.encodeEffect(Schema.fromJsonString(PullRequestReviewGuide)); return PullRequestReviewGuideRepository.of({ - get: (key) => - findGuide(key).pipe( + get: Effect.fn("PullRequestReviewGuideRepository.get")(function (key) { + return findGuide(key).pipe( NodeSqliteClient.readOnly, Effect.map(Option.map((row) => row.guide)), Effect.mapError((cause) => @@ -60,9 +60,10 @@ const make = Effect.gen(function* () { ? PersistenceDecodeError.fromSchemaError("PullRequestReviewGuide", cause) : new PersistenceSqlError({ operation: "getPullRequestReviewGuide", cause }), ), - ), - put: (key, guide) => - encodeGuide(guide).pipe( + ); + }), + put: Effect.fn("PullRequestReviewGuideRepository.put")(function (key, guide) { + return encodeGuide(guide).pipe( Effect.mapError((cause) => PersistenceDecodeError.fromSchemaError("PullRequestReviewGuide", cause), ), @@ -78,7 +79,8 @@ const make = Effect.gen(function* () { ), ), Effect.asVoid, - ), + ); + }), }); }); diff --git a/apps/server/src/persistence/initializeV2Database.ts b/apps/server/src/persistence/initializeV2Database.ts index 7f63bb9c4c137..755907b5076f9 100644 --- a/apps/server/src/persistence/initializeV2Database.ts +++ b/apps/server/src/persistence/initializeV2Database.ts @@ -39,13 +39,12 @@ export const initializeV2Database = Effect.fn("initializeV2Database")(function* } }); // Publish only a complete snapshot, without replacing an existing V2 database. - yield* fs - .link(snapshotPath, destinationPath) - .pipe( - Effect.catch((error) => - error.reason._tag === "AlreadyExists" ? Effect.void : Effect.fail(error), - ), - ); + yield* fs.link(snapshotPath, destinationPath).pipe( + Effect.catchIf( + (error) => error.reason._tag === "AlreadyExists", + (_error) => Effect.void, + ), + ); }).pipe( Effect.scoped, Effect.mapError((cause) => new V2DatabaseImportError({ sourcePath, destinationPath, cause })), diff --git a/apps/server/src/project/ProjectCloneTracker.ts b/apps/server/src/project/ProjectCloneTracker.ts index 8cad093efff60..4a0c99795155c 100644 --- a/apps/server/src/project/ProjectCloneTracker.ts +++ b/apps/server/src/project/ProjectCloneTracker.ts @@ -417,11 +417,20 @@ export const make = Effect.gen(function* () { { bufferSize: 1, strategy: "sliding" }, ); + // Forwarders retain the underlying operation spans. return ProjectCloneTracker.of({ - start: (input, hooks) => locked(start(input, hooks)), - cancel: (projectId) => locked(cancel(projectId)), - retry: (projectId) => locked(retry(projectId)), - discard: (projectId) => locked(discard(projectId)), + start: Effect.fnUntraced(function* (input, hooks) { + return yield* locked(start(input, hooks)); + }), + cancel: Effect.fnUntraced(function* (projectId) { + return yield* locked(cancel(projectId)); + }), + retry: Effect.fnUntraced(function* (projectId) { + return yield* locked(retry(projectId)); + }), + discard: Effect.fnUntraced(function* (projectId) { + return yield* locked(discard(projectId)); + }), get, stream, }); diff --git a/apps/server/src/project/ProjectEnrichmentService.test.ts b/apps/server/src/project/ProjectEnrichmentService.test.ts index 492d1c43419ab..6da9ae31203bf 100644 --- a/apps/server/src/project/ProjectEnrichmentService.test.ts +++ b/apps/server/src/project/ProjectEnrichmentService.test.ts @@ -25,12 +25,16 @@ const waitForAvailable = Effect.fn("ProjectEnrichmentServiceTest.waitForAvailabl workspaceRoot: string, predicate: (value: ProjectEnrichment.ProjectEnrichment) => boolean, ) { - for (let attempt = 0; attempt < 100; attempt += 1) { - const available = yield* service.peek(workspaceRoot); - if (predicate(available)) return available; - yield* Effect.yieldNow; - } - return yield* Effect.die(`Project metadata for ${workspaceRoot} was not resolved in time.`); + return yield* Effect.scoped( + Effect.gen(function* () { + const changes = yield* service.subscribeChanges; + for (;;) { + const available = yield* service.peek(workspaceRoot); + if (predicate(available)) return available; + yield* PubSub.take(changes); + } + }), + ); }); const layer = ( diff --git a/apps/server/src/project/ProjectService.test.ts b/apps/server/src/project/ProjectService.test.ts index 43ebde7086ca5..2266c415b726a 100644 --- a/apps/server/src/project/ProjectService.test.ts +++ b/apps/server/src/project/ProjectService.test.ts @@ -1,3 +1,6 @@ +import * as Context from "effect/Context"; +import * as Queue from "effect/Queue"; +import * as Tracer from "effect/Tracer"; import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { CommandId, type Project, ProjectId, ProviderInstanceId } from "@t3tools/contracts"; @@ -51,6 +54,35 @@ const layerMetadata = Layer.merge( }), ); +class EnrichmentCompletions extends Context.Service>()( + "t3/project/ProjectService.test/EnrichmentCompletions", +) {} + +const layerEnrichmentCompletions = Layer.effectContext( + Effect.gen(function* () { + const completions = yield* Queue.unbounded(); + const tracer = Tracer.make({ + span: (options) => { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (...args) => { + end(...args); + if ( + span.name === "ProjectEnrichmentService.resolveRepositoryIdentity" || + span.name === "ProjectEnrichmentService.resolveFavicon" + ) { + Queue.offerUnsafe(completions, undefined); + } + }; + return span; + }, + }); + return Context.make(EnrichmentCompletions, completions).pipe( + Context.add(Tracer.Tracer, tracer), + ); + }), +); + const layerTestFor = ( projectMetadataLayer: Layer.Layer< | ProjectFaviconResolver.ProjectFaviconResolver @@ -65,6 +97,7 @@ const layerTestFor = ( Layer.provideMerge(ServerSettings.layerTest()), Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "project-service-test-" })), Layer.provide(NodeServices.layer), + Layer.provideMerge(layerEnrichmentCompletions), ); const layerTest = layerTestFor(layerMetadata); @@ -91,12 +124,16 @@ const waitForProject = Effect.fn("ProjectServiceTest.waitForProject")(function* projectId: ProjectId, predicate: (project: Project) => boolean, ) { - for (let attempt = 0; attempt < 100; attempt += 1) { - const project = Option.getOrThrow(yield* service.getById(projectId)); - if (predicate(project)) return project; - yield* Effect.yieldNow; - } - return yield* Effect.die(`Project ${projectId} was not enriched in time.`); + return yield* Effect.scoped( + Effect.gen(function* () { + const completions = yield* EnrichmentCompletions; + for (;;) { + const project = Option.getOrThrow(yield* service.getById(projectId)); + if (predicate(project)) return project; + yield* Queue.take(completions); + } + }), + ); }); it.layer(layerTest)("ProjectService", (it) => { diff --git a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts index 06a0b456dedf5..e98a8276510e9 100644 --- a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts +++ b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts @@ -14,6 +14,8 @@ import { // Coder: the probe runs the workspace CLI transport, not the SDK query. vi.mock("./Drivers/ClaudeCli.ts", { spy: true }); +const decodeClaudeSettings = Schema.decodeEffect(ClaudeSettings); + it("drops strict MCP mode, and only that, next to an administrator's managed-mcp.json", () => { const options = buildClaudeCapabilitiesProbeQueryOptions({ executablePath: "/usr/bin/claude", @@ -32,7 +34,7 @@ it("drops strict MCP mode, and only that, next to an administrator's managed-mcp it.effect("reports a deleted worktree's scan as finished, not pending", () => Effect.gen(function* () { const snapshot = yield* probeClaudeWorkspaceSnapshot( - yield* Schema.decodeEffect(ClaudeSettings)({}), + yield* decodeClaudeSettings({}), { skills: [], slashCommands: [] } as unknown as ServerProvider, "/nonexistent/t3-deleted-worktree", { HOME: "/nonexistent/t3-home" }, diff --git a/apps/server/src/provider/ClaudeModelCatalog.ts b/apps/server/src/provider/ClaudeModelCatalog.ts index db409077756a3..f67628efb83a3 100644 --- a/apps/server/src/provider/ClaudeModelCatalog.ts +++ b/apps/server/src/provider/ClaudeModelCatalog.ts @@ -59,23 +59,21 @@ function tryResolveClaudeModelCatalog( }; } -const BUNDLED_CLAUDE_PROVIDER_CATALOG = - resolveProviderCatalog(BUNDLED_MODEL_MANIFEST, CLAUDE) ?? undefined; - +/** Resolve the fallback on each read so its new-model badges can expire. */ export function resolveClaudeModelCatalog( catalog: ModelCatalog.ProviderCatalog | undefined, ): ClaudeModelCatalog { return ( tryResolveClaudeModelCatalog(catalog) ?? - tryResolveClaudeModelCatalog(BUNDLED_CLAUDE_PROVIDER_CATALOG) ?? { + tryResolveClaudeModelCatalog( + resolveProviderCatalog(BUNDLED_MODEL_MANIFEST, CLAUDE) ?? undefined, + ) ?? { models: [], } ); } -export const BUNDLED_CLAUDE_MODEL_CATALOG = resolveClaudeModelCatalog( - BUNDLED_CLAUDE_PROVIDER_CATALOG, -); +export const BUNDLED_CLAUDE_MODEL_CATALOG = resolveClaudeModelCatalog(undefined); export function scopeClaudeModelCatalog( catalog: ClaudeModelCatalog, diff --git a/apps/server/src/provider/ModelManifest.test.ts b/apps/server/src/provider/ModelManifest.test.ts index 1489d3140c709..a27bb54998701 100644 --- a/apps/server/src/provider/ModelManifest.test.ts +++ b/apps/server/src/provider/ModelManifest.test.ts @@ -1,10 +1,94 @@ import { assert, describe, it } from "@effect/vitest"; import { ProviderDriverKind } from "@t3tools/contracts"; +import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; import * as ModelManifest from "./ModelManifest.ts"; describe("resolveProviderCatalog", () => { + it.each([ + { releasedAt: "2026-01-01", now: "2026-01-01T00:00:00Z", badge: "new" }, + { releasedAt: "2026-01-01", now: "2026-01-07T23:59:59.999Z", badge: "new" }, + { releasedAt: "2026-01-01", now: "2026-01-08T00:00:00Z", badge: undefined }, + { releasedAt: "2026-01-01", now: "2026-02-01T00:00:00Z", badge: undefined }, + { releasedAt: "2026-01-02T00:00:00Z", now: "2026-01-01T00:00:00Z", badge: undefined }, + { releasedAt: undefined, now: "2026-01-01T00:00:00Z", badge: undefined }, + { releasedAt: "invalid", now: "2026-01-01T00:00:00Z", badge: undefined }, + ])("derives the new badge from releasedAt=$releasedAt at $now", ({ releasedAt, now, badge }) => { + const manifest: ModelManifest.ModelManifestData = { + version: 1, + currentModels: {}, + providers: { + synthetic: { + profiles: {}, + models: [ + { + slug: "model-next", + name: "Model Next", + status: "current", + ...(releasedAt === undefined ? {} : { releasedAt }), + }, + { + slug: "model-legacy", + name: "Model Legacy", + status: "legacy", + releasedAt: now, + }, + ], + }, + }, + }; + const catalog = ModelManifest.resolveProviderCatalog( + manifest, + ProviderDriverKind.make("synthetic"), + Date.parse(now), + ); + assert.strictEqual(catalog?.models[0]?.badge, badge); + assert.strictEqual(catalog?.models[1]?.badge, undefined); + }); + + it.effect("expires badges when rereading a cached manifest without a refresh", () => { + const manifest: ModelManifest.ModelManifestData = { + version: 1, + currentModels: {}, + providers: { + synthetic: { + profiles: {}, + models: [ + { + slug: "model-next", + name: "Model Next", + status: "current", + releasedAt: "1970-01-01T00:00:00Z", + }, + ], + }, + }, + }; + return Effect.gen(function* () { + const service = yield* ModelCatalog.ModelCatalog; + const readCatalog = service.current(ProviderDriverKind.make("synthetic")); + assert.strictEqual((yield* readCatalog)?.models[0]?.badge, "new"); + yield* TestClock.adjust("7 days"); + assert.strictEqual((yield* readCatalog)?.models[0]?.badge, undefined); + }).pipe( + Effect.provide( + ModelManifest.layerModelCatalog.pipe( + Layer.provide( + Layer.succeed(ModelManifest.ModelManifest, { + current: Effect.succeed(manifest), + refresh: Effect.die("Catalog reads must not refresh the manifest"), + forceRefresh: Effect.die("Catalog reads must not refresh the manifest"), + refreshInBackground: Effect.die("Catalog reads must not refresh the manifest"), + }), + ), + ), + ), + ); + }); + it("rejects invalid catalog references", () => { const invalidCatalog = (input: { readonly models: NonNullable[string]["models"]; diff --git a/apps/server/src/provider/ModelManifest.ts b/apps/server/src/provider/ModelManifest.ts index 4647a4131fe07..5060285ca8093 100644 --- a/apps/server/src/provider/ModelManifest.ts +++ b/apps/server/src/provider/ModelManifest.ts @@ -4,7 +4,9 @@ import { TrimmedNonEmptyString, type ProviderDriverKind, } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -14,6 +16,8 @@ import bundledManifestJson from "./model-manifest.json" with { type: "json" }; import { ProviderCompatibilityPolicy } from "./providerCompatibility.ts"; import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog"; +const MODEL_NEW_BADGE_DURATION_MS = 7 * 24 * 60 * 60 * 1000; + const ManifestModelStatus = Schema.Literals(["current", "legacy"]); const ManifestModelProfile = Schema.Struct({ @@ -28,7 +32,8 @@ const ManifestProviderModel = Schema.Struct({ subProvider: Schema.optional(TrimmedNonEmptyString), aliases: Schema.optional(Schema.Array(TrimmedNonEmptyString)), status: ManifestModelStatus, - badge: Schema.optional(Schema.Literal("new")), + /** ISO date or timestamp of the model's public release, as published by its provider. */ + releasedAt: Schema.optional(Schema.String), profile: Schema.optional(TrimmedNonEmptyString), adapter: Schema.optional(Schema.Unknown), }); @@ -85,6 +90,7 @@ export const BUNDLED_MODEL_MANIFEST: ModelManifestData = export function resolveProviderCatalog( manifest: ModelManifestData, driverKind: ProviderDriverKind, + nowMs = DateTime.toEpochMillis(DateTime.nowUnsafe()), ): ModelCatalog.ProviderCatalog | null { const catalog = manifest.providers?.[driverKind]; if (!catalog) return null; @@ -98,13 +104,19 @@ export function resolveProviderCatalog( const profile = entry.profile ? catalog.profiles[entry.profile] : undefined; if (entry.profile && !profile) return null; + const releasedAtMs = entry.releasedAt === undefined ? NaN : Date.parse(entry.releasedAt); + const showNewBadge = + entry.status === "current" && + nowMs >= releasedAtMs && + nowMs - releasedAtMs < MODEL_NEW_BADGE_DURATION_MS; + models.push({ slug: entry.slug, name: entry.name, ...(entry.shortName ? { shortName: entry.shortName } : {}), ...(entry.subProvider ? { subProvider: entry.subProvider } : {}), ...(entry.aliases ? { aliases: entry.aliases } : {}), - ...(entry.badge ? { badge: entry.badge } : {}), + ...(showNewBadge ? { badge: "new" as const } : {}), status: entry.status, capabilities: profile?.capabilities ?? null, adapter: entry.adapter, @@ -152,10 +164,11 @@ export const layerModelCatalog = Layer.effect( Effect.gen(function* () { const manifest = yield* ModelManifest; return ModelCatalog.ModelCatalog.of({ - current: (driverKind) => - manifest.current.pipe( - Effect.map((data) => resolveProviderCatalog(data, driverKind) ?? undefined), - ), + current: Effect.fn("ModelCatalog.current")(function* (driverKind: ProviderDriverKind) { + const data = yield* manifest.current; + const nowMs = yield* Clock.currentTimeMillis; + return resolveProviderCatalog(data, driverKind, nowMs) ?? undefined; + }), bundled: (driverKind) => resolveProviderCatalog(BUNDLED_MODEL_MANIFEST, driverKind) ?? undefined, refreshInBackground: manifest.refreshInBackground, diff --git a/apps/server/src/provider/ProviderHostLive.ts b/apps/server/src/provider/ProviderHostLive.ts index d28179064a258..614ed156ff615 100644 --- a/apps/server/src/provider/ProviderHostLive.ts +++ b/apps/server/src/provider/ProviderHostLive.ts @@ -35,14 +35,17 @@ export const layer = Layer.effect( shouldRunBackgroundWork: backgroundPolicy.shouldRunScopeWork, resolveAttachmentPath: (attachment) => resolveAttachmentPath({ attachmentsDir: config.attachmentsDir, attachment }), - resolveExtractedTextPath: (path) => - DocumentText.resolveExtractedTextPath(path).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - ), + // DocumentText owns the path-resolution span. + resolveExtractedTextPath: Effect.fnUntraced( + function* (path) { + return yield* DocumentText.resolveExtractedTextPath(path); + }, + Effect.provideService(FileSystem.FileSystem, fileSystem), + ), // Coder: providers authenticate through the workspace's own configuration, and T3 Coder // never stores provider credentials: nothing is stored and writes fail. - credentials: (namespace, bindingId) => - Effect.succeed({ + credentials: Effect.fn("ProviderHost.credentials")(function (namespace, bindingId) { + return Effect.succeed({ binding: { owner: "t3" as const, key: `${namespace}:${bindingId}` }, get: Effect.succeed(Option.none()), set: (_credentials: Uint8Array) => @@ -58,7 +61,8 @@ export const layer = Layer.effect( cause: "T3 Coder does not store provider credentials.", }), ), - }), + }); + }), }); }), ); diff --git a/apps/server/src/provider/model-manifest.json b/apps/server/src/provider/model-manifest.json index e62f661fcfc2c..ce0a47fe56f48 100644 --- a/apps/server/src/provider/model-manifest.json +++ b/apps/server/src/provider/model-manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "updatedAt": "2026-10-21T06:20:00Z", + "updatedAt": "2026-10-26T20:00:36Z", "compatibility": [ { "driver": "codex", @@ -773,7 +773,7 @@ "name": "Claude Haiku 5.5", "aliases": ["haiku", "haiku-5.5", "claude-haiku-5.5"], "status": "current", - "badge": "new", + "releasedAt": "2026-10-07", "profile": "haiku-5-5", "adapter": { "claudeCode": { "minVersion": "2.1.293" } } }, diff --git a/apps/server/src/pullRequest/PullRequestReadCache.test.ts b/apps/server/src/pullRequest/PullRequestReadCache.test.ts index 2d2fcfc1f05a8..2485be7a97a30 100644 --- a/apps/server/src/pullRequest/PullRequestReadCache.test.ts +++ b/apps/server/src/pullRequest/PullRequestReadCache.test.ts @@ -1,3 +1,5 @@ +import * as NodeV8 from "node:v8"; +import * as NodeVM from "node:vm"; import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { PullRequestOperationError } from "@t3tools/contracts"; @@ -8,6 +10,9 @@ import * as FileSystem from "effect/FileSystem"; import * as KeyValueStore from "effect/persistence/KeyValueStore"; import * as PullRequestReadCache from "./PullRequestReadCache.ts"; +NodeV8.setFlagsFromString("--expose-gc"); +const collectGarbage = NodeVM.runInNewContext("gc") as () => void; + const cacheLayer = (directory: string) => PullRequestReadCache.make.pipe(Effect.provide(KeyValueStore.layerFileSystem(directory))); @@ -147,6 +152,32 @@ it.layer(NodeServices.layer)("PR filesystem cache", (it) => { }).pipe(Effect.provide(KeyValueStore.layerMemory)), ); + it.effect("does not keep a caller's data alive after its reads and invalidations", () => + Effect.gen(function* () { + const cache = yield* PullRequestReadCache.make; + const sweeps: Array> = []; + // Like a sync sweep: an Effect.fn made per run that closes over that run's data. + const sweep = Effect.fn("sweep")(function* (index: number) { + const groups = new Map( + Array.from({ length: 1_000 }, (_, id) => [`group-${id}`, id]), + ); + sweeps.push(new WeakRef(groups)); + const read = Effect.fn("read")(function* (pr: string) { + const size = groups.size; + yield* cache.invalidate(pr); + const answer = yield* cache.get(`${pr}-${index}`, Effect.succeed("answer"), [pr]); + return size + answer.length; + }); + yield* Effect.forEach(["pr-1", "pr-2"], read, { discard: true }); + }); + for (let index = 0; index < 5; index++) yield* sweep(index); + // WeakRef targets stay alive until the current job ends, so yield before collecting. + yield* Effect.yieldNow; + collectGarbage(); + assert.strictEqual(sweeps.filter((sweepData) => sweepData.deref() !== undefined).length, 0); + }).pipe(Effect.provide(KeyValueStore.layerMemory)), + ); + it.effect("cancels abandoned reads without blocking invalidation", () => Effect.gen(function* () { const cache = yield* PullRequestReadCache.make; diff --git a/apps/server/src/pullRequest/PullRequestReadCache.ts b/apps/server/src/pullRequest/PullRequestReadCache.ts index 649a1cea80d3f..62ac7da3789d6 100644 --- a/apps/server/src/pullRequest/PullRequestReadCache.ts +++ b/apps/server/src/pullRequest/PullRequestReadCache.ts @@ -21,6 +21,7 @@ import * as Persistable from "effect/persistence/Persistable"; import * as PersistedCache from "effect/persistence/PersistedCache"; import * as Persistence from "effect/persistence/Persistence"; import * as ServerConfig from "../config.ts"; +import { detachStackFrame } from "../git/detachStackFrame.ts"; import { forkParked } from "../serverActivation.ts"; const CONCURRENT_READS = 512; @@ -124,6 +125,8 @@ export const make = Effect.gen(function* () { }), { capacity: CONCURRENT_READS, timeToLive: () => Duration.zero }, ); + // A cache entry keeps the fiber that filled it, whose lazy stack frames would keep the caller's + // data (e.g. a whole sync sweep) alive until eviction. return PullRequestReadCache.of({ get: Effect.fn("PullRequestReadCache.get")(function* (key, lookup, scopes = []) { if (!enabled) return yield* lookup; @@ -151,7 +154,7 @@ export const make = Effect.gen(function* () { }), lock.withPermits(1), ); - }), + }, detachStackFrame), invalidate: Effect.fn("PullRequestReadCache.invalidate")( function* (scope) { const now = clock.currentTimeMillisUnsafe(); @@ -170,6 +173,7 @@ export const make = Effect.gen(function* () { }), Effect.uninterruptible, lock.withPermits(CONCURRENT_READS), + detachStackFrame, ), }); }); diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index fb1b6fbf05c5b..d93d89d759bf0 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -2837,8 +2837,9 @@ export const make = Effect.gen(function* () { ]); // A replacement reader can join a lookup still finishing its previous reader's cancellation. return Cache.get(listCache, key).pipe( - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) ? Cache.get(listCache, key) : Effect.failCause(cause), + Effect.catchCauseIf( + (cause) => Cause.hasInterruptsOnly(cause), + (_cause) => Cache.get(listCache, key), ), ); }; @@ -3268,8 +3269,9 @@ export const make = Effect.gen(function* () { if (missing.size === 0) return { stats: held }; const key = statsBatchKey(missing.values()); const { result, at } = yield* Cache.get(listStatsCache, key).pipe( - Effect.catchCause((cause) => - Cause.hasInterruptsOnly(cause) ? Cache.get(listStatsCache, key) : Effect.failCause(cause), + Effect.catchCauseIf( + (cause) => Cause.hasInterruptsOnly(cause), + (_cause) => Cache.get(listStatsCache, key), ), ); for (const [key, ref] of missing) { @@ -3495,10 +3497,13 @@ export const make = Effect.gen(function* () { return PullRequestService.of({ list, filterOptions, - listStats: (input) => - Effect.forEach(input.refs, (ref) => canonicalRef(ref).pipe(Effect.option)).pipe( - Effect.flatMap((refs) => listStats({ ...input, refs: refs.flatMap(Option.toArray) })), - ), + // The local operation owns the span; this wrapper only canonicalizes refs. + listStats: Effect.fnUntraced(function* (input) { + const refs = yield* Effect.forEach(input.refs, (ref) => + canonicalRef(ref).pipe(Effect.option), + ); + return yield* listStats({ ...input, refs: refs.flatMap(Option.toArray) }); + }), summary: canonicalized(summary), stack: canonicalized(stack), subscribeMerges: PubSub.subscribe(mergedPullRequests).pipe( diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts index 127f61444029a..48d3024d4f938 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts @@ -503,6 +503,20 @@ it.effect.each(queuedDeliveryCases)( ({ reason, apply }) => Effect.gen(function* () { const gate = yield* Deferred.make(); + const deliveryReleased = yield* Deferred.make(); + const tracer = Tracer.make({ + span: (options) => { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (...args) => { + end(...args); + if (span.name === "ScheduledTaskService.releaseFailedDelivery") { + Deferred.doneUnsafe(deliveryReleased, Effect.void); + } + }; + return span; + }, + }); yield* withService( ({ service, launches }) => Effect.gen(function* () { @@ -513,23 +527,17 @@ it.effect.each(queuedDeliveryCases)( yield* apply(service, task.id); yield* Deferred.succeed(gate, undefined); const deliveryId = queued._tag === "accepted" ? queued.deliveryId : undefined; - let delivery = (yield* service.getWebhookDelivery({ + yield* Deferred.await(deliveryReleased); + const delivery = (yield* service.getWebhookDelivery({ id: task.id, deliveryId: deliveryId!, })).delivery; - while (delivery.outcome === "accepted") { - yield* Effect.yieldNow; - delivery = (yield* service.getWebhookDelivery({ - id: task.id, - deliveryId: deliveryId!, - })).delivery; - } assert.equal(delivery.outcome, "dispatch_failed"); assert.equal(delivery.error, reason); assert.equal(yield* Queue.size(launches), 0); }), { gate }, - ); + ).pipe(Effect.withTracer(tracer)); }), ); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index c1da193f012c8..6f4e87f44705e 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1542,10 +1542,14 @@ it.layer(NodeServices.layer)("server settings", (it) => { runOnWorktreeCreate: false, }; const model = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.5"); - const modelJson = yield* Schema.encodeEffect(Schema.fromJsonString(ModelSelection))(model); - const scriptsJson = yield* Schema.encodeEffect( + const encodeModelSelection = Schema.encodeEffect(Schema.fromJsonString(ModelSelection)); + + const modelJson = yield* encodeModelSelection(model); + const encodeProjectScripts = Schema.encodeEffect( Schema.fromJsonString(Schema.Array(ProjectScript)), - )([script]); + ); + + const scriptsJson = yield* encodeProjectScripts([script]); for (const [projectId, modelColumn, envMode, autoPull, scripts] of [ [legacyProject, modelJson, "worktree", 1, scriptsJson], [scriptedProject, null, null, 0, scriptsJson], diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index 09d8937465281..36f5e7642ae60 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -71,6 +71,7 @@ export class SourceControlProviderRegistry extends Context.Service< function unsupportedProvider( kind: SourceControlProviderKind, ): SourceControlProvider.SourceControlProvider["Service"] { + // Binding context does not create a second provider-operation span. return SourceControlProvider.SourceControlProvider.of({ kind, // Unknown hosts have no readable change requests; return none to avoid poll warnings on every refresh. @@ -195,37 +196,45 @@ function bindProviderContext( return SourceControlProvider.SourceControlProvider.of({ ...provider, - listChangeRequests: (input) => - provider.listChangeRequests({ + listChangeRequests: Effect.fnUntraced(function* (input) { + return yield* provider.listChangeRequests({ ...input, context: input.context ?? context, - }), - getChangeRequest: (input) => - provider.getChangeRequest({ + }); + }), + getChangeRequest: Effect.fnUntraced(function* (input) { + return yield* provider.getChangeRequest({ ...input, context: input.context ?? context, - }), - createChangeRequest: (input) => - provider.createChangeRequest({ + }); + }), + createChangeRequest: Effect.fnUntraced(function* (input) { + return yield* provider.createChangeRequest({ ...input, context: input.context ?? context, - }), - getRepositoryCloneUrls: (input) => - provider.getRepositoryCloneUrls({ + }); + }), + getRepositoryCloneUrls: Effect.fnUntraced(function* (input) { + return yield* provider.getRepositoryCloneUrls({ ...input, context: input.context ?? context, - }), - createRepository: (input) => provider.createRepository(input), - getDefaultBranch: (input) => - provider.getDefaultBranch({ + }); + }), + createRepository: Effect.fnUntraced(function* (input) { + return yield* provider.createRepository(input); + }), + getDefaultBranch: Effect.fnUntraced(function* (input) { + return yield* provider.getDefaultBranch({ ...input, context: input.context ?? context, - }), - checkoutChangeRequest: (input) => - provider.checkoutChangeRequest({ + }); + }), + checkoutChangeRequest: Effect.fnUntraced(function* (input) { + return yield* provider.checkoutChangeRequest({ ...input, context: input.context ?? context, - }), + }); + }), }); } @@ -336,7 +345,9 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit }, get, resolveHandle, - resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)), + resolve: Effect.fn("SourceControlProviderRegistry.resolve")(function (input) { + return resolveHandle(input).pipe(Effect.map((handle) => handle.provider)); + }), discover: Effect.forEach( discoverySpecs, (spec) => diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.ts index c1f70fc65f094..33493ff2211af 100644 --- a/apps/server/src/sourceControl/SourceControlRepositoryService.ts +++ b/apps/server/src/sourceControl/SourceControlRepositoryService.ts @@ -395,6 +395,7 @@ export const make = Effect.gen(function* () { options, ).pipe( Effect.as(prepared.remoteUrl), + // @effect-diagnostics-next-line catchConditionalRefailToCatchIf:off - The condition also narrows httpsUrl for the fallback closure. Effect.catch((sshError) => httpsUrl === null || !isSshRejection(sshError) ? Effect.fail(sshError) @@ -533,29 +534,39 @@ export const make = Effect.gen(function* () { }, ); + // Forwarders retain the underlying operation spans. return SourceControlRepositoryService.of({ - lookupRepository: (input) => - lookupRepository(input).pipe(mapRepositoryError("lookupRepository", input.provider)), - prepareClone: (input) => - prepareClone(input).pipe( + lookupRepository: Effect.fnUntraced(function* (input) { + return yield* lookupRepository(input).pipe( + mapRepositoryError("lookupRepository", input.provider), + ); + }), + prepareClone: Effect.fnUntraced(function* (input) { + return yield* prepareClone(input).pipe( mapRepositoryError( "cloneRepository", input.provider ?? SourceControlProviderKind.make("unknown"), ), - ), - cloneRepository: (input, options) => - cloneRepository(input, options).pipe( + ); + }), + cloneRepository: Effect.fnUntraced(function* (input, options) { + return yield* cloneRepository(input, options).pipe( mapRepositoryError( "cloneRepository", input.provider ?? SourceControlProviderKind.make("unknown"), ), - ), - discardClone: (destinationPath) => - discardClone(destinationPath).pipe( + ); + }), + discardClone: Effect.fnUntraced(function* (destinationPath) { + return yield* discardClone(destinationPath).pipe( mapRepositoryError("discardClone", SourceControlProviderKind.make("unknown")), - ), - publishRepository: (input) => - publishRepository(input).pipe(mapRepositoryError("publishRepository", input.provider)), + ); + }), + publishRepository: Effect.fnUntraced(function* (input) { + return yield* publishRepository(input).pipe( + mapRepositoryError("publishRepository", input.provider), + ); + }), }); }); diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.ts index aedd2cc4077c4..96f266c6f8959 100644 --- a/apps/server/src/textGeneration/TextGeneration.ts +++ b/apps/server/src/textGeneration/TextGeneration.ts @@ -57,24 +57,30 @@ export const make = Effect.gen(function* () { const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; const sourceControl = yield* SourceControlProviderRegistry.SourceControlProviderRegistry; return TextGeneration.of({ - generateCommitMessage: (input) => - resolveInstance(registry, "generateCommitMessage", input.modelSelection.instanceId).pipe( - Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)), - ), - generatePrContent: (input) => - resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe( + generateCommitMessage: Effect.fn("TextGeneration.generateCommitMessage")(function (input) { + return resolveInstance( + registry, + "generateCommitMessage", + input.modelSelection.instanceId, + ).pipe(Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input))); + }), + generatePrContent: Effect.fn("TextGeneration.generatePrContent")(function (input) { + return resolveInstance(registry, "generatePrContent", input.modelSelection.instanceId).pipe( Effect.flatMap((textGeneration) => textGeneration.generatePrContent(input)), - ), - generateBranchName: (input) => - resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe( + ); + }), + generateBranchName: Effect.fn("TextGeneration.generateBranchName")(function (input) { + return resolveInstance(registry, "generateBranchName", input.modelSelection.instanceId).pipe( Effect.flatMap((textGeneration) => textGeneration.generateBranchName(input)), - ), - generateReviewGuide: (input) => - resolveInstance(registry, "generateReviewGuide", input.modelSelection.instanceId).pipe( + ); + }), + generateReviewGuide: Effect.fn("TextGeneration.generateReviewGuide")(function (input) { + return resolveInstance(registry, "generateReviewGuide", input.modelSelection.instanceId).pipe( Effect.flatMap((textGeneration) => textGeneration.generateReviewGuide(input)), - ), - generateThreadTitle: (input) => - resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe( + ); + }), + generateThreadTitle: Effect.fn("TextGeneration.generateThreadTitle")(function (input) { + return resolveInstance(registry, "generateThreadTitle", input.modelSelection.instanceId).pipe( Effect.flatMap((textGeneration) => Effect.gen(function* () { const linkedContext = @@ -88,7 +94,8 @@ export const make = Effect.gen(function* () { return yield* textGeneration.generateThreadTitle({ ...input, linkedContext }); }), ), - ), + ); + }), }); }); diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index da59fb3dc6801..ba695684f333f 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -1784,9 +1784,11 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { baseRef: initialBranch, }); const branch = preview.sources.find((source) => source.kind === "branch-range")!; + const decodeReviewDiffPreviewInput = Schema.decodeEffect(ReviewDiffPreviewInput); + for (const path of ["renamed.md", "[literal].txt", " leading.txt", "mode-only.sh"]) { const stat = branch.files!.find((file) => file.path === path)!; - const request = yield* Schema.decodeEffect(ReviewDiffPreviewInput)({ + const request = yield* decodeReviewDiffPreviewInput({ cwd, baseRef: initialBranch, file: { path, previousPath: stat.previousPath, sourceKind: "branch-range" }, diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 08d5b820f4e65..68e4b18d5b806 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -3744,7 +3744,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* operation: "GitVcsDriver.createWorktree", command: "git worktree add", cwd: input.cwd, - detail: `The worktree location "${options?.worktreesDirectory}" must be an absolute folder on this machine, not a drive root. Change it in Settings → Storage.`, + detail: `The worktree location "${options?.worktreesDirectory}" must be an absolute folder on this machine, not a drive root. Change it in Settings → Worktrees.`, }); } worktreePath = path.join(parentDir, repoName, sanitizedBranch); @@ -4001,8 +4001,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }, ); return run.pipe( - Effect.flatMap((result) => - result.exitCode !== 0 && isRefLockFailure(result.stderr) ? run : Effect.succeed(result), + Effect.filterOrElse( + (result) => !(result.exitCode !== 0 && isRefLockFailure(result.stderr)), + (_result) => run, ), ); }; @@ -4424,7 +4425,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "branch", "--list", "--no-column", - "--format=%(refname:short)", + "--format=%(refname:lstrip=2)", ]).pipe( Effect.map((stdout) => { const branchNames: Array = []; @@ -4478,6 +4479,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), ); + // Forwarders retain the underlying Git operation spans. return GitVcsDriver.GitVcsDriver.of({ execute, status, @@ -4485,11 +4487,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* statusDetailsLocal, statusDetailsRemote, prepareCommitContext, - commit: (cwd, subject, body, options) => - withListRefsInvalidation(cwd, commit(cwd, subject, body, options)), - pushCurrentBranch: (cwd, fallbackBranch, options) => - withListRefsInvalidation(cwd, pushCurrentBranch(cwd, fallbackBranch, options)), - pullCurrentBranch: (cwd) => withListRefsInvalidation(cwd, pullCurrentBranch(cwd)), + commit: Effect.fnUntraced(function* (cwd, subject, body, options) { + return yield* withListRefsInvalidation(cwd, commit(cwd, subject, body, options)); + }), + pushCurrentBranch: Effect.fnUntraced(function* (cwd, fallbackBranch, options) { + return yield* withListRefsInvalidation(cwd, pushCurrentBranch(cwd, fallbackBranch, options)); + }), + pullCurrentBranch: Effect.fnUntraced(function* (cwd) { + return yield* withListRefsInvalidation(cwd, pullCurrentBranch(cwd)); + }), readRangeContext, // Coder: index-preserving ref-only polling. refStatusLocal, @@ -4499,18 +4505,24 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* readBranchBase, resolveBranchName, listRefs, - createWorktree: (input, options) => - withListRefsInvalidation(input.cwd, createWorktree(input, options)), - fetchRefIntoBranch: (input) => withListRefsInvalidation(input.cwd, fetchRefIntoBranch(input)), + createWorktree: Effect.fnUntraced(function* (input, options) { + return yield* withListRefsInvalidation(input.cwd, createWorktree(input, options)); + }), + fetchRefIntoBranch: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, fetchRefIntoBranch(input)); + }), fetchRefCommit, resolveCommit, - refreshCheckedOutBranch: (input) => - withListRefsInvalidation(input.cwd, refreshCheckedOutBranch(input)), - ensureRemote: (input) => withListRefsInvalidation(input.cwd, ensureRemote(input)), + refreshCheckedOutBranch: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, refreshCheckedOutBranch(input)); + }), + ensureRemote: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, ensureRemote(input)); + }), resolvePrimaryRemoteName, resolveDefaultBranchName, - fetchRemote: (input) => - withListRefsInvalidation( + fetchRemote: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation( input.cwd, fetchRemote(input).pipe( Effect.flatMap((fetched) => @@ -4519,25 +4531,46 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : fetchRemote({ cwd: input.cwd, remoteName: input.remoteName }).pipe(Effect.asVoid), ), ), - ), + ); + }), remoteExists, remoteBranchExists, resolveRemoteTrackingCommit, resolveWorktreeBaseRemote, - fetchWorktreeBaseCommit: (input) => - withListRefsInvalidation(input.cwd, fetchWorktreeBaseCommit(input)), - fetchRemoteBranch: (input) => withListRefsInvalidation(input.cwd, fetchRemoteBranch(input)), - fetchRemoteTrackingBranch: (input) => - withListRefsInvalidation(input.cwd, fetchRemoteTrackingBranch(input)), - setBranchUpstream: (input) => withListRefsInvalidation(input.cwd, setBranchUpstream(input)), - removeWorktree: (input) => withListRefsInvalidation(input.cwd, removeWorktree(input)), - pruneWorktrees: (input) => withListRefsInvalidation(input.cwd, pruneWorktrees(input)), + fetchWorktreeBaseCommit: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, fetchWorktreeBaseCommit(input)); + }), + fetchRemoteBranch: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, fetchRemoteBranch(input)); + }), + fetchRemoteTrackingBranch: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, fetchRemoteTrackingBranch(input)); + }), + setBranchUpstream: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, setBranchUpstream(input)); + }), + removeWorktree: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, removeWorktree(input)); + }), + pruneWorktrees: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, pruneWorktrees(input)); + }), // Coder: worktree moves invalidate the same refs cache as other mutations. - moveWorktree: (input) => withListRefsInvalidation(input.cwd, moveWorktree(input)), - deleteLocalBranch: (input) => withListRefsInvalidation(input.cwd, deleteLocalBranch(input)), - renameBranch: (input) => withListRefsInvalidation(input.cwd, renameBranch(input)), - createRef: (input) => withListRefsInvalidation(input.cwd, createRef(input)), - switchRef: (input) => withListRefsInvalidation(input.cwd, switchRef(input)), + moveWorktree: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, moveWorktree(input)); + }), + deleteLocalBranch: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, deleteLocalBranch(input)); + }), + renameBranch: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, renameBranch(input)); + }), + createRef: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, createRef(input)); + }), + switchRef: Effect.fnUntraced(function* (input) { + return yield* withListRefsInvalidation(input.cwd, switchRef(input)); + }), initRepo: initRepoWithListRefsInvalidation, listLocalBranchNames, listWorktreePaths, diff --git a/apps/web/index.html b/apps/web/index.html index 6c01298b624d9..13518deb6e5d1 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -439,29 +439,234 @@ object-fit: contain; } + /* App CSS locks body and #root scrolling once main loads, so the error screen scrolls itself. */ + #boot-shell:has(> #boot-error) { + height: 100%; + overflow-x: hidden; + overflow-y: auto; + } + #boot-error { - display: grid; - justify-items: center; - gap: 16px; - max-width: 600px; - padding: 24px; - text-align: center; + --boot-error-fg: #262626; + --boot-error-bg: #ffffff; + --boot-error-line: color-mix(in srgb, currentColor 12%, transparent); + display: flex; + flex-direction: column; + align-items: flex-start; + align-self: flex-start; + width: min(400px, calc(100% - 48px)); + padding: clamp(24px, 22vh, 220px) 0 24px; + font-size: 13px; + line-height: 20px; } - #boot-error p { + html.dark #boot-error { + --boot-error-fg: #f5f5f5; + --boot-error-bg: #0a0a0a; + } + + html[data-theme-selected="true"] #boot-error { + --boot-error-fg: var(--boot-foreground); + --boot-error-bg: var(--boot-background); + } + + #boot-error h1 { margin: 0; + font-size: 15px; + font-weight: 600; + line-height: 22px; + } + + #boot-error p { + margin: 4px 0 0; + opacity: 0.7; + overflow-wrap: anywhere; + text-wrap: pretty; + } + + #boot-error code, + #boot-error pre { + font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; + font-size: 12px; overflow-wrap: anywhere; } + #boot-error a { + color: inherit; + text-decoration-line: underline; + text-decoration-color: color-mix(in srgb, currentColor 40%, transparent); + text-underline-offset: 3px; + } + + #boot-error a:hover { + text-decoration-color: currentColor; + } + #boot-error button { - padding: 8px 16px; - border: 1px solid currentColor; - border-radius: 4px; + height: 32px; + padding: 0 14px; + border: 1px solid var(--boot-error-line); + border-radius: 6px; background: transparent; color: inherit; font: inherit; + font-weight: 500; cursor: pointer; } + + #boot-error button[aria-disabled="true"] { + opacity: 0.6; + cursor: default; + } + + #boot-error :is(button, a, summary, pre):focus-visible { + outline: 2px solid var(--boot-error-fg); + outline-offset: 2px; + } + + #boot-error-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 16px; + } + + #boot-error #boot-error-reload { + border-color: var(--boot-error-fg); + background: var(--boot-error-fg); + color: var(--boot-error-bg); + } + + #boot-error-reload:hover { + opacity: 0.9; + } + + #boot-error #boot-error-update-note { + margin-top: 8px; + font-size: 12px; + line-height: 18px; + } + + #boot-error details { + width: 100%; + margin-top: 32px; + } + + #boot-error summary { + display: inline-flex; + align-items: center; + gap: 8px; + border-radius: 4px; + list-style: none; + opacity: 0.7; + cursor: pointer; + } + + #boot-error summary::-webkit-details-marker { + display: none; + } + + #boot-error summary::before { + content: ""; + width: 5px; + height: 5px; + border-right: 1.5px solid currentColor; + border-bottom: 1.5px solid currentColor; + transform: rotate(-45deg); + } + + #boot-error details[open] summary::before { + transform: rotate(45deg); + } + + #boot-error summary:hover, + #boot-error details[open] summary { + opacity: 1; + } + + #boot-error details > :not(summary) { + display: grid; + gap: 8px; + margin-top: 20px; + } + + #boot-error details > a { + display: block; + width: fit-content; + } + + #boot-error details p { + margin: 0; + font-size: 12px; + line-height: 18px; + } + + #boot-error-command { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 4px 4px 10px; + border: 1px solid var(--boot-error-line); + border-radius: 6px; + } + + #boot-error-command code { + flex: 1; + min-width: 0; + opacity: 0.8; + } + + #boot-error .boot-error-icon { + display: grid; + flex: none; + place-items: center; + min-width: 24px; + height: 24px; + padding: 0 4px; + border: 0; + border-radius: 4px; + font-size: 12px; + font-weight: 400; + opacity: 0.7; + } + + #boot-error .boot-error-icon:hover { + opacity: 1; + background: color-mix(in srgb, currentColor 8%, transparent); + } + + #boot-error-details { + max-height: 200px; + margin: 0; + padding: 10px 12px; + overflow: auto; + border: 1px solid var(--boot-error-line); + border-radius: 6px; + font-size: 11px; + line-height: 16px; + white-space: pre-wrap; + opacity: 0.8; + } + + #boot-error-report { + display: flex; + align-items: center; + gap: 16px; + } + + #boot-error-report button { + height: 28px; + padding: 0 10px; + } + + .boot-error-sr { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; + } T3 Code (Beta) diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index 7860b2cf31e0b..55a47141e6fe7 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -6,21 +6,28 @@ import { applyAppearanceContrast } from "./appearanceContrast"; import { applyAppearanceFontVariables } from "./appearanceFonts"; import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention"; import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer"; +import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToast"; import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast"; import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation"; +import { startSlowRpcRequestToasts } from "./components/SlowRpcRequestToastCoordinator"; import { startThreadNotifications } from "./components/ThreadNotificationCoordinator"; +import { startGuideRunNotifications } from "./components/pullRequest/guide/PullRequestGuideRunCoordinator"; import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding"; import { resolveServerBackedAppDisplayName } from "./branding.logic"; -import { useComposerDraftStore } from "./composerDraftStore"; +import { subscribeDraftThreadPromotion, useComposerDraftStore } from "./composerDraftStore"; +import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme"; import { getClientSettings, startModelPreferencesMigration, subscribeClientSettings, } from "./hooks/useSettings"; +import { syncBrowserChromeTheme } from "./hooks/useTheme"; import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration"; import { getRouter, type AppRouter } from "./router"; import { appAtomRegistry } from "./rpc/atomRegistry"; import { primaryServerConfigAtom } from "./state/server"; +import { installChatRouteCommands } from "./shortcuts/chatRouteCommands"; +import { environmentThreadShells } from "./state/threads"; import { resolveThreadRouteTarget } from "./threadRoutes"; /** Writes appearance settings onto the document, touching only the groups that changed. */ @@ -90,6 +97,17 @@ function startDocumentTitle(): void { ); } +/** + * Each route paints its own surface, which the browser chrome samples once it is on screen. + * onRendered only fires for a new href; onResolved also covers `router.invalidate()`, which + * can swap the root between the bare outlet and the shell at the same address. + */ +function startBrowserChromeThemeSync(router: AppRouter): void { + const resync = () => window.requestAnimationFrame(syncBrowserChromeTheme); + router.subscribe("onRendered", resync); + router.subscribe("onResolved", resync); +} + /** Chat overlays belong to the thread they were opened in, so leaving its route drops them. */ function startThreadOverlayRetention(router: AppRouter): void { router.subscribe("onResolved", () => { @@ -114,20 +132,33 @@ function startThreadOverlayRetention(router: AppRouter): void { */ export function startAppServices(): AppRouter { // Coder: a browser behind the loopback gateway only. There is no provider auth delivery, - // Electron shell, default-theme adoption, agent-opened browser preview, SSH password prompt, - // host-freeze toast, pairing-permission notice, or desktop update notice. + // Electron shell or desktop paste-as-text, default-theme adoption, agent-opened browser preview, + // preview title recording or browser profile reporting, Open in editor command, SSH password + // prompt, host-freeze toast, pairing-permission notice, or desktop update notice. const router = getRouter(createBrowserHistory()); startClientAppearance(); startDocumentTitle(); + startEnvironmentThemeRepaint(); + startBrowserChromeThemeSync(router); startModelPreferencesMigration(); + installChatRouteCommands(router); startThreadOverlayRetention(router); + // Drafts promote as their server threads arrive, wherever the user is. + subscribeDraftThreadPromotion({ + registry: appAtomRegistry, + threadShellAtom: environmentThreadShells.quietThreadShellAtom, + threadRefsAtom: environmentThreadShells.threadRefsAtom, + }); startMainAppLocationTracking(router); startBackgroundThreadAnnouncements(appAtomRegistry, router); startThreadVisitedMigration(appAtomRegistry); + startKeybindingsUpdateToasts(); + startSlowRpcRequestToasts(); startLegacyThreadMigrationToast(); startThreadNotifications(appAtomRegistry, router); + startGuideRunNotifications(appAtomRegistry, router); return router; } diff --git a/apps/web/src/coder/workspaceNetwork.test.ts b/apps/web/src/coder/workspaceNetwork.test.ts index 72943d8677db0..1bede8b3cc5c3 100644 --- a/apps/web/src/coder/workspaceNetwork.test.ts +++ b/apps/web/src/coder/workspaceNetwork.test.ts @@ -1,10 +1,7 @@ import { EnvironmentId } from "@t3tools/contracts"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { - removeCoderWorkspaceEnvironment, - setCoderWorkspaceEnvironment, -} from "./environmentStore"; +import { removeCoderWorkspaceEnvironment, setCoderWorkspaceEnvironment } from "./environmentStore"; import { FAST_PROBE_INTERVAL_MS, NOMINAL_PROBE_INTERVAL_MS, diff --git a/apps/web/src/components/ChatMarkdown.test.tsx b/apps/web/src/components/ChatMarkdown.test.tsx index 706507e96782b..98b91f0bd423b 100644 --- a/apps/web/src/components/ChatMarkdown.test.tsx +++ b/apps/web/src/components/ChatMarkdown.test.tsx @@ -596,8 +596,18 @@ describe("ChatMarkdown skill chips", () => { cwd="/tmp/project" text={text} skills={[ - { name: "2spec", displayName: "2Spec" }, - { name: "20k", displayName: "MoneySkill" }, + { + name: "2spec", + displayName: "2Spec", + path: "/skills/2spec/SKILL.md", + enabled: true, + }, + { + name: "20k", + displayName: "MoneySkill", + path: "/skills/20k/SKILL.md", + enabled: true, + }, ]} />, ); @@ -1289,7 +1299,14 @@ it.each([ ])( "highlights the indexed occurrences of $query in $text", async ({ text, query, count, lineBreaks, user, withTemplate }) => { - const skills = [{ name: "test-t3-app", displayName: "T3 App Testing" }]; + const skills = [ + { + name: "test-t3-app", + displayName: "T3 App Testing", + path: "/skills/test-t3-app/SKILL.md", + enabled: true, + }, + ]; const highlights = new Map>(); vi.stubGlobal( "Highlight", diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 8070ae4f3b98d..a6a4563313e0b 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -185,7 +185,7 @@ interface ChatMarkdownProps { environmentId?: EnvironmentId | undefined; onTaskListChange?: ((input: { markerOffset: number; checked: boolean }) => void) | undefined; isStreaming?: boolean; - skills?: ReadonlyArray>; + skills?: ReadonlyArray; className?: string; lineBreaks?: boolean; parseRawHtml?: boolean; @@ -205,7 +205,7 @@ export interface ChatMarkdownContextReference { label: string; } -const EMPTY_MARKDOWN_SKILLS: ReadonlyArray> = []; +const EMPTY_MARKDOWN_SKILLS: ReadonlyArray = []; const EMPTY_REMARK_PLUGINS: NonNullable = []; const ARTIFACT_TEMPLATE_ICON_BY_KIND = { @@ -779,8 +779,8 @@ const CHAT_MARKDOWN_COMPONENTS = { return
{children}
; }, p: function MarkdownParagraph({ node: _node, children, ...props }) { - const { skills } = use(ChatMarkdownRendererContext); - return

{renderSkillInlineMarkdownChildren(children, skills)}

; + const { skills, threadRef } = use(ChatMarkdownRendererContext); + return

{renderSkillInlineMarkdownChildren(children, skills, threadRef)}

; }, blockquote: function MarkdownBlockquote({ node: _node, children, ...props }) { const alert = @@ -815,12 +815,12 @@ const CHAT_MARKDOWN_COMPONENTS = { ); }, li: function MarkdownListItem({ node, children, ...props }) { - const { skills } = use(ChatMarkdownRendererContext); + const { skills, threadRef } = use(ChatMarkdownRendererContext); // Resolve checkbox markers by offset to avoid rerendering list items on every streamed token. const isTaskItem = String(props.className ?? "").includes("task-list-item"); return (
  • - {renderSkillInlineMarkdownChildren(children, skills)} + {renderSkillInlineMarkdownChildren(children, skills, threadRef)}
  • ); }, diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 2dad0b9722ff8..6ea290d42282c 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -49,7 +49,6 @@ import { deriveComposerSendState, deriveLockedProvider, hasServerAcknowledgedLocalDispatch, - resolveDraftPromotionNavigationTarget, waitForRevertedMessage, } from "./ChatView.logic"; @@ -102,51 +101,6 @@ const readySession = { updatedAt: "2026-03-29T00:00:10.000Z", }; -describe("resolveDraftPromotionNavigationTarget", () => { - const serverThreadRef = { environmentId, threadId }; - const preparingRun = { - ...completedTurn, - status: "preparing" as const, - startedAt: null, - completedAt: null, - }; - - it("stays on the draft until the server owns the send", () => { - expect( - resolveDraftPromotionNavigationTarget({ - serverThreadRef, - serverThread: makeThread({ latestRun: preparingRun }), - backgroundSubmissionPending: false, - }), - ).toBeNull(); - expect( - resolveDraftPromotionNavigationTarget({ - serverThreadRef, - serverThread: makeThread(), - backgroundSubmissionPending: false, - }), - ).toBeNull(); - }); - - it("promotes a persisted send while its worktree is still preparing", () => { - const serverThread = makeThread({ latestRun: preparingRun, latestUserMessageAt: now }); - expect( - resolveDraftPromotionNavigationTarget({ - serverThreadRef, - serverThread, - backgroundSubmissionPending: false, - }), - ).toBe(serverThreadRef); - expect( - resolveDraftPromotionNavigationTarget({ - serverThreadRef, - serverThread, - backgroundSubmissionPending: true, - }), - ).toBeNull(); - }); -}); - describe("deriveComposerSendState", () => { it("keeps text sendable while excluding expired terminal pills", () => { const state = deriveComposerSendState({ diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index b087f646eada4..a359b9d33c9a8 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -102,7 +102,7 @@ type ThreadStructureRow = ThreadStructure["visibleTurnItems"][number]; export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project"; export const MAX_HIDDEN_MOUNTED_TERMINAL_THREADS = 10; -const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000; +export const ENVIRONMENT_RECONNECT_WARNING_GRACE_MS = 2_000; export function shouldOpenProactivePullRequest( previousTargetKey: string | null | undefined, @@ -399,36 +399,6 @@ export function resolveThreadSwitchTimeline(input: return { entries: input.nextEntries, displayThreadKey: input.activeThreadKey }; } -export function resolveDraftPromotionNavigationTarget(input: { - serverThreadRef: ScopedThreadRef | null; - serverThread: Pick | null | undefined; - backgroundSubmissionPending: boolean; -}): ScopedThreadRef | null { - if (input.backgroundSubmissionPending) { - return null; - } - const latestRun = input.serverThread?.latestRun ?? null; - const runStarted = latestRun?.startedAt != null; - const startupStopped = - latestRun?.status === "failed" || - latestRun?.status === "interrupted" || - latestRun?.status === "cancelled"; - const messagePersisted = input.serverThread?.latestUserMessageAt != null; - return runStarted || startupStopped || messagePersisted ? input.serverThreadRef : null; -} - -export function scheduleEnvironmentReconnectWarning(showWarning: () => void): () => void { - const timeoutId = globalThis.setTimeout(showWarning, ENVIRONMENT_RECONNECT_WARNING_GRACE_MS); - return () => globalThis.clearTimeout(timeoutId); -} - -export function hasEnvironmentReconnectWarningGraceElapsed( - activeEnvironmentId: EnvironmentId | null, - elapsedEnvironmentId: EnvironmentId | null, -): boolean { - return activeEnvironmentId !== null && activeEnvironmentId === elapsedEnvironmentId; -} - export function startNewThreadForProject( projectRef: ScopedProjectRef | null, handleNewThread: (projectRef: ScopedProjectRef) => Promise, @@ -880,7 +850,7 @@ export function recallCheckoutIsRepo( : sessionCheckoutIsRepo.get(checkoutIsRepoKey(environmentId, cwd)); } -export function threadHasStarted(thread: Thread | null | undefined): boolean { +function threadHasStarted(thread: Thread | null | undefined): boolean { return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime)); } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 4006b3fa3c39b..7583916519275 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,4 +1,5 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; +import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit"; import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays"; import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer"; import { announcedRun, isDetailBehindShell } from "./chat/threadActivityAnnouncement"; @@ -80,7 +81,10 @@ import { resolveWorkflowOpening, workflowOpeningParentThreadId, } from "@t3tools/client-runtime/state/subagentRuntime"; -import { threadSupportsProviderHandoff } from "@t3tools/client-runtime/state/thread-workflows"; +import { + getUserQueuedThreadRuns, + threadSupportsProviderHandoff, +} from "@t3tools/client-runtime/state/thread-workflows"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { HandoffRow } from "./chat/V2LifecycleRow"; import { @@ -117,8 +121,6 @@ import { useActiveThreadRef } from "../hooks/useActiveThreadRef"; import { composerRequiresModifier } from "../composer-logic"; import { derivePhase, - deriveActivePlanState, - selectComposerTasksPlan, deriveActiveWorkStartedAt, deriveCanInterruptRunningThread, findLatestProposedPlan, @@ -219,6 +221,7 @@ import { RevertConfirmHost, } from "./chat/ChatOverlayHosts"; import type { AssistantCitationRequest } from "./chat/AssistantCitationSource"; +import { useCitedHistory } from "./chat/citationProcedure"; import type { MessagesTimelineHistoryControls } from "./chat/MessagesTimeline"; import { ThreadTimeline } from "./chat/ThreadTimeline"; import { ProviderSubagentBar } from "./chat/ProviderSubagentBar"; @@ -306,6 +309,8 @@ import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers"; import { ChatRightPanel } from "./chat/ChatRightPanel"; import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting"; import { branchMismatchBannerItem } from "./chat/ThreadActivityBanners"; +import { ThreadNow } from "./chat/ThreadNow"; +import { useDelayedStatus } from "../hooks/useDelayedStatus"; import { useTimelineFollow } from "./chat/useTimelineFollow"; import { type EnvironmentUnavailableState, @@ -463,6 +468,8 @@ export default function ChatView(props: ChatViewProps) { status: threadStatus, }); const threadDetailLoading = threadSyncPhase === "loading"; + // Held back briefly, so a quick sync does not flash a status line at the end of the timeline. + const delayedThreadSyncPhase = useDelayedStatus(routeThreadKey, threadSyncPhase); const activeProviderThread = serverProjection?.providerThreads.find( (thread) => thread.id === serverProjection.thread.activeProviderThreadId, ); @@ -519,6 +526,7 @@ export default function ChatView(props: ChatViewProps) { ? { citation, key: citationLocation.key ?? citationLocation.href } : null; })() as AssistantCitationRequest | null; + const citationHistory = useCitedHistory(citationRequest); const { resolvedTheme } = useTheme(); const composerRuntimeMode = useComposerDraftStore( (store) => store.getComposerDraft(composerDraftTarget)?.runtimeMode ?? null, @@ -904,30 +912,6 @@ export default function ChatView(props: ChatViewProps) { ); const latestRunSettled = isLatestRunSettled(activeLatestRun, activeRuntime); - const activePlan = deriveActivePlanState(serverProjection, activeActivityRun?.runId); - const activeActivityRunSettled = isLatestRunSettled(activeActivityRun, activeRuntime); - const composerTasksPlan = selectComposerTasksPlan( - serverProjection, - activePlan, - activeActivityRun?.runId ?? null, - activeActivityRunSettled, - ); - const activeComposerTasksProgress = (() => { - if (!composerTasksPlan) return null; - const live = !activeActivityRunSettled && composerTasksPlan.runId === activeActivityRun?.runId; - const totalSteps = composerTasksPlan.steps.length; - if (totalSteps === 0) return null; - const completedSteps = composerTasksPlan.steps.filter( - (step) => step.status === "completed", - ).length; - const step = - composerTasksPlan.steps.find((candidate) => candidate.status === "inProgress")?.step ?? - composerTasksPlan.steps.find((candidate) => candidate.status === "pending")?.step ?? - composerTasksPlan.steps.at(-1)!.step; - return { step, completedSteps, totalSteps, live }; - })(); - const activeComposerTaskSteps = - activeComposerTasksProgress && composerTasksPlan ? composerTasksPlan.steps : null; const activeThreadEnvironmentId = activeThread?.environmentId; const activeThreadProjectId = activeThread?.projectId; const activeProjectRef = @@ -1158,7 +1142,6 @@ export default function ChatView(props: ChatViewProps) { } = usePendingThreadRequests({ environmentId, activeThreadId, - activeThread, serverProjection, supportsQuestionAttachments, composerDraftTarget, @@ -1810,9 +1793,7 @@ export default function ChatView(props: ChatViewProps) { const { showScrollToBottom, timelineLiveFollowEnabled, - cancelPositionRestoreRef, isTimelineAtLogicalEndStable, - cancelTimelineLiveFollowForUserNavigationStable, onComposerPageScrollKeyDownStable, onComposerPageScrollKeyUpStable, onComposerPageScrollReleaseStable, @@ -1820,16 +1801,17 @@ export default function ChatView(props: ChatViewProps) { onTimelineAnchorReadyStable, onTimelineAnchorSizeChangedStable, onToolOutputCollapsedAtEndStable, + onTimelineFooterGrowStable, onIsAtEndChangeStable, anchorNewTurn, + attachTimelineViewport, + attachComposerOverlay: attachFollowComposerOverlay, } = useTimelineFollow({ legendListRef, composerRef, - composerOverlayElement, composerTimelineInset, routeThreadKey, activeThreadKey, - activeThreadId: activeThread?.id, isServerThread, serverProjection, threadStatus, @@ -1998,22 +1980,11 @@ export default function ChatView(props: ChatViewProps) { modelStrip.offsetHeight + Number.parseFloat(getComputedStyle(modelStrip).marginTop), ) : 0; - const noticeStack = composerOverlayElement?.querySelector( - '[data-composer-banner-stack="true"]', - ); - const expandedNoticesHeight = noticeStack - ? Math.max( - 0, - noticeStack.getBoundingClientRect().height - - Number.parseFloat(getComputedStyle(noticeStack).minHeight), - ) - : 0; const nextInset = resolveComposerTimelineInset({ currentInset: composerTimelineInsetRef.current, overlayHeight: height, isResting, restingOnlyHeight, - expandedNoticesHeight, }); if (composerTimelineInsetRef.current !== nextInset) { composerTimelineInsetRef.current = nextInset; @@ -2039,9 +2010,8 @@ export default function ChatView(props: ChatViewProps) { const mainSurface = composerOverlayElement?.querySelector( '[data-chat-composer-main-surface="true"]', ); - const button = composerOverlayElement?.parentElement?.querySelector( - 'button[aria-label="Scroll to end"]', - ); + const button = + composerOverlayElement?.parentElement?.querySelector("[data-scroll-to-end]"); const clearance = composerOverlayElement && mainSurface && button ? resolveScrollToEndClearance({ @@ -2188,9 +2158,9 @@ export default function ChatView(props: ChatViewProps) { const { acknowledgeActiveThreadWoke, activeBranchMismatchKey, - backgroundWorkBanner, - childInputBanner, - goalBanner, + backgroundWorkNow, + childInputNow, + goalNow, handleSwitchCheckoutToThread, handleSwitchCheckoutToThreadStable, isRestoringThreadBranch, @@ -2343,23 +2313,14 @@ export default function ChatView(props: ChatViewProps) { : null; const composerBannerItems = (() => { const limitRecoveryItems = limitRecoveryBanner === null ? [] : [limitRecoveryBanner]; - const backgroundWorkItems = [childInputBanner, goalBanner, backgroundWorkBanner].filter( - (item) => item !== null, - ); const projectCloneItems = projectCloneBannerItem === null ? [] : [projectCloneBannerItem]; if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) { - return [ - ...limitRecoveryItems, - ...projectCloneItems, - ...systemComposerBannerItems, - ...backgroundWorkItems, - ]; + return [...limitRecoveryItems, ...projectCloneItems, ...systemComposerBannerItems]; } return [ ...limitRecoveryItems, ...projectCloneItems, ...systemComposerBannerItems, - ...backgroundWorkItems, branchMismatchBannerItem({ mismatchKey: activeBranchMismatchKey, mismatch: localCheckoutBranchMismatch, @@ -2662,6 +2623,9 @@ export default function ChatView(props: ChatViewProps) { threadId={activeThread.id} optimisticMessages={optimisticUserMessages} editingRunId={queuedRunEdit.editingRunId} + editBlockedReason={queuedRunEditBlockedReason({ + openQuestionCount: pendingUserInputs.length, + })} onEditQueuedRun={queuedRunEdit.beginEdit} onCancelEdit={queuedRunEdit.cancelEdit} /> @@ -2707,6 +2671,59 @@ export default function ChatView(props: ChatViewProps) { openExpandedImagePreview(routeThreadKey, preview); }; const onExpandTimelineImageStable = useStableCallback(onExpandTimelineImage); + const shownThreadSyncPhase = activeEnvironmentUnavailable ? null : delayedThreadSyncPhase; + const hasThreadNow = + childInputNow !== null || + backgroundWorkNow !== null || + goalNow !== null || + shownThreadSyncPhase !== null; + const queuedRunCount = serverProjection ? getUserQueuedThreadRuns(serverProjection).length : 0; + // The queue control is mounted for every server thread but joins the footer only while it shows + // something, by its own rule: an optimistic message stops counting once the server has it. + const hasQueuedTurns = + queuedRunCount > 0 || + optimisticUserMessages.some( + (message) => + message.inputIntent === "queued_turn" && + !serverProjection?.messages.some((committed) => committed.id === message.id), + ); + const scrollToEndSummary = + [ + childInputNow === null ? null : "Subagent waiting", + queuedRunCount === 0 ? null : `${queuedRunCount} queued`, + ] + .filter((part) => part !== null) + .join(" · ") || null; + // The end of the timeline holds the thread's present and next turns: what it is doing now, + // its lifecycle status, guest messages awaiting you, then your queued messages. + const timelineFooter = + pendingHandoff === null && + !hasThreadNow && + threadStatusLine === null && + !hasQueuedTurns ? null : ( + <> + {pendingHandoff === null ? null : ( +
    + +
    + )} + + {threadStatusLine} + {/* Coder: guest sharing is not carried, so no guest messages wait here. */} + {hasQueuedTurns ? queuedRunsControl : null} + + ); const pendingSidebarFileDrops = useSidebarPendingFileDropStore((state) => state.pending); const consumePendingFileDrop = useSidebarPendingFileDropStore( @@ -2922,7 +2939,7 @@ export default function ChatView(props: ChatViewProps) { readyMarkdownCwd={gitCwd} readyWorkspaceRoot={activeWorkspaceRoot ?? null} citationRequest={paintOnlyDisplayedTimeline ? null : citationRequest} - citationHistoryLoading={threadDetailLoading} + citationHistory={citationHistory} {...(!paintOnlyDisplayedTimeline ? { onCiteAssistantText: citeAssistantTextStable, @@ -2967,24 +2984,7 @@ export default function ChatView(props: ChatViewProps) { : {})} {...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})} isPreparingWorktree={!paintOnlyDisplayedTimeline && isPreparingWorktree} - footer={ - paintOnlyDisplayedTimeline || - (pendingHandoff === null && threadStatusLine === null) ? null : ( - <> - {pendingHandoff === null ? null : ( -
    - -
    - )} - {threadStatusLine} - - ) - } + footer={paintOnlyDisplayedTimeline ? null : timelineFooter} listRef={legendListRef} runs={paintOnlyDisplayedTimeline ? [] : (serverProjection?.runs ?? [])} latestRun={paintOnlyDisplayedTimeline ? null : activeActivityRun} @@ -3059,8 +3059,8 @@ export default function ChatView(props: ChatViewProps) { onIsAtEndChange={onIsAtEndChangeStable} onContentOverflowChange={setTimelineOverflows} onToolOutputCollapsedAtEnd={onToolOutputCollapsedAtEndStable} - onManualNavigation={cancelTimelineLiveFollowForUserNavigationStable} - cancelPositionRestoreRef={cancelPositionRestoreRef} + onViewportAttach={attachTimelineViewport} + onFooterGrow={onTimelineFooterGrowStable} hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading} emptyPlaceholderInset={composerReservedHeight} topFadeEnabled={!hasTimelineTopBanner} @@ -3072,6 +3072,7 @@ export default function ChatView(props: ChatViewProps) { {showScrollToBottom && !isThreadFindActive && ( { composerRef.current?.restoreAfterTimelineReachedEnd(); scrollToEnd(true); @@ -3081,7 +3082,10 @@ export default function ChatView(props: ChatViewProps) {
    { + setComposerOverlayElement(overlay); + attachFollowComposerOverlay(overlay); + }} inert={isRevertingCheckpoint} data-chat-composer-overlay="true" className={ @@ -3212,7 +3216,6 @@ export default function ChatView(props: ChatViewProps) { : projectCloneSendBlockReason } isPreparingWorktree={isPreparingWorktree && !sendQueuesBehindSetup} - queuedRunsControl={queuedRunsControl} bannerItems={composerBannerItems} resumeCompactionTokens={resumeCompactionTokens} keepFullHistory={keepFullHistory} @@ -3243,8 +3246,6 @@ export default function ChatView(props: ChatViewProps) { activeThreadModelSelection={activeThread?.modelSelection} activeProjectId={activeProject?.id ?? null} activeContextWindow={activeContextWindow} - activeTasksProgress={activeComposerTasksProgress} - activeTaskSteps={activeComposerTaskSteps} compactThreadUnavailable={compactThreadUnavailable} compactDisabled={compactDisabled} compactDisabledReason={compactDisabledReason} diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 4d20d5b5cb106..f0a23d2ab4336 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -108,11 +108,9 @@ import { cn, isMacPlatform } from "~/lib/utils"; import { basenameOfPath } from "~/pierre-icons"; import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon"; import { FileTagChipContent } from "./chat/FileTagChip"; -import { SkillChipIcon } from "./chat/SkillInlineText"; +import { SkillChipPopover, skillPopoverDescription } from "./chat/SkillInlineText"; import { AssistantCitationChip } from "./chat/AssistantCitationChip"; import { getTimelinePageScrollKey } from "./chat/pageScrollController"; -import { ContextChipPopover } from "./contextChipParts"; -import { Button } from "./ui/button"; import { ContextChip } from "./ContextChip"; import { ComposerContextActionsContext, @@ -348,31 +346,19 @@ function ComposerSkillNodeView({ node }: NodeViewProps) { const skill = skills.find( (candidate) => candidate.name === skillName && isProviderSkillUserInvocable(candidate), ); - const description = skill - ? skill.description?.trim() || skill.shortDescription?.trim() - : skillDescription; // The node outlives a provider switch, so its stored label can be another provider's. const skillLabel = skill ? formatProviderSkillDisplayName(skill) : (node.attrs.skillLabel as string) || skillName; return ( - } + -
    -

    {skillLabel}

    -

    {description || "No description is available for this skill."}

    - {skill?.path && actions.environmentId ? ( - - ) : null} -
    -
    + description={skill ? skillPopoverDescription(skill) : skillDescription} + onViewInstructions={ + skill?.path && actions.environmentId ? () => actions.openMention(skill.path) : undefined + } + />
    ); } diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 14e777edd6245..4d73067d84f67 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -1306,9 +1306,12 @@ export default function GitActionsControl({ const actionResult = result.value; syncThreadBranchAfterGitAction(actionResult); if (isPanel) { + const createdPullRequest = actionResult.pr.status === "created"; setInlineSuccess({ - title: actionResult.toast.title, - description: actionResult.toast.description ?? null, + title: createdPullRequest + ? `Created ${changeRequestTerminology.shortLabel}` + : actionResult.toast.title, + description: createdPullRequest ? null : (actionResult.toast.description ?? null), scopeKey: successScopeKey, }); return; diff --git a/apps/web/src/components/KeybindingsUpdateToast.test.ts b/apps/web/src/components/KeybindingsUpdateToast.test.ts new file mode 100644 index 0000000000000..13e063ff56941 --- /dev/null +++ b/apps/web/src/components/KeybindingsUpdateToast.test.ts @@ -0,0 +1,57 @@ +import type { ServerConfigStreamEvent } from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; + +const mocks = vi.hoisted(() => ({ + state: null as unknown as import("effect/reactivity").Atom.Writable<{ + readonly latestEvent: ServerConfigStreamEvent | null; + }>, + addToast: vi.fn<(toast: { readonly title?: unknown }) => void>(), +})); + +// The event atom is derived from server state, as in production; nothing else reads it. +vi.mock(import("../state/server"), async () => { + const { Atom } = await import("effect/reactivity"); + mocks.state = Atom.make<{ readonly latestEvent: ServerConfigStreamEvent | null }>({ + latestEvent: null, + }); + return { + primaryServerConfigEventAtom: Atom.make((get) => get(mocks.state).latestEvent), + } as never; +}); +// Coder: the toast shows the warning text itself; there is no KeybindingsConfigWarning. +vi.mock( + import("./ui/toast"), + () => + ({ + toastManager: { add: mocks.addToast }, + stackedThreadToast: (toast: unknown) => toast, + }) as never, +); + +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { startKeybindingsUpdateToasts } from "./KeybindingsUpdateToast"; + +function keybindingsUpdated(issues: ReadonlyArray): ServerConfigStreamEvent { + return { type: "keybindingsUpdated", payload: { keybindings: [], issues } } as never; +} + +describe("startKeybindingsUpdateToasts", () => { + it("toasts reloads the server reports after start", () => { + const stop = startKeybindingsUpdateToasts(); + try { + appAtomRegistry.set(mocks.state, { latestEvent: keybindingsUpdated([]) }); + appAtomRegistry.set(mocks.state, { + latestEvent: keybindingsUpdated([ + { kind: "keybindings.malformed-config", message: "Unexpected token" }, + ]), + }); + + expect(mocks.addToast.mock.calls.map(([toast]) => toast.title)).toEqual([ + "Keybindings updated", + "Invalid keybindings configuration", + ]); + } finally { + stop(); + } + }); +}); diff --git a/apps/web/src/components/KeybindingsUpdateToast.tsx b/apps/web/src/components/KeybindingsUpdateToast.tsx new file mode 100644 index 0000000000000..572693c64a9e6 --- /dev/null +++ b/apps/web/src/components/KeybindingsUpdateToast.tsx @@ -0,0 +1,31 @@ +import { subscribeAtomChanges } from "../rpc/atomRegistry"; +import { primaryServerConfigEventAtom } from "../state/server"; +import { createKeybindingsUpdateToastController } from "./KeybindingsUpdateToast.logic"; +import { stackedThreadToast, toastManager } from "./ui/toast"; + +/** Toasts each keybindings reload the primary server reports. */ +export function startKeybindingsUpdateToasts(): () => void { + const controller = createKeybindingsUpdateToastController({}); + return subscribeAtomChanges(primaryServerConfigEventAtom, (event) => { + const decision = controller.handle(event); + if (!decision) return; + + if (decision._tag === "Success") { + toastManager.add({ + type: "success", + title: "Keybindings updated", + description: "Keybindings configuration reloaded successfully.", + }); + return; + } + + // Coder: there are no local editors to open the config in, so the warning is its message. + toastManager.add( + stackedThreadToast({ + type: "warning", + title: "Invalid keybindings configuration", + description: decision.message, + }), + ); + }); +} diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index ba909e6842334..4d2c27270a7ec 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -33,7 +33,10 @@ vi.mock(import("../connection/catalog"), async (original) => { ...actual, environmentCatalog: { ...actual.environmentCatalog, - catalogValueAtom: Atom.make({ isReady: true, entries: new Map([["remote", {}]]) }) as never, + catalogValueAtom: Atom.make({ + isReady: true, + entries: new Map([["remote", { target: { _tag: "DirectConnectionTarget" } }]]), + }) as never, }, }; }); diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 37f25154c7c02..476d69a7ad8b6 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -656,10 +656,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { return () => document.removeEventListener("keydown", onNewSurfaceKeyDown, true); }, [props.open]); - const updateTabScrollState = () => { - const viewport = tabScrollViewport(tabListRef.current); - if (!viewport) return; - + const updateTabScrollState = (viewport: HTMLDivElement) => { const hasOverflow = viewport.scrollWidth - viewport.clientWidth > TAB_SCROLL_EDGE_TOLERANCE; const canScrollLeft = hasOverflow && viewport.scrollLeft > TAB_SCROLL_EDGE_TOLERANCE; const canScrollRight = @@ -807,34 +804,19 @@ export function RightPanelTabs(props: RightPanelTabsProps) { props.onCloseSurface(surface); }; + // A newly active tab, or tabs that start overflowing, can sit outside the scrolled strip. useEffect(() => { if (!props.activeSurfaceId || !tabScrollState.hasOverflow) return; const activeTab = tabListRef.current?.querySelector("[data-active-tab='true']"); activeTab?.scrollIntoView({ block: "nearest", inline: "nearest" }); }, [props.activeSurfaceId, tabScrollState.hasOverflow]); - useEffect(() => { - const viewport = tabScrollViewport(tabListRef.current); - if (!viewport) return; - - const content = viewport.firstElementChild; - const stopObserving = observeResize( - content ? [viewport, content] : viewport, - updateTabScrollState, - ); - viewport.addEventListener("scroll", updateTabScrollState, { passive: true }); - updateTabScrollState(); - - return () => { - stopObserving(); - viewport.removeEventListener("scroll", updateTabScrollState); - }; - }, [updateTabScrollState]); - - useEffect(() => { - const viewport = tabScrollViewport(tabListRef.current); + const attachTabList = (root: HTMLDivElement | null) => { + tabListRef.current = root; + const viewport = tabScrollViewport(root); if (!viewport) return; + const update = () => updateTabScrollState(viewport); const handleWheel = (event: WheelEvent) => { if (event.ctrlKey) return; let delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY; @@ -846,12 +828,22 @@ export function RightPanelTabs(props: RightPanelTabsProps) { viewport.scrollLeft += delta; if (viewport.scrollLeft === previousScrollLeft) return; event.preventDefault(); - updateTabScrollState(); + update(); }; + const content = viewport.firstElementChild; + const stopObserving = observeResize(content ? [viewport, content] : viewport, update); + viewport.addEventListener("scroll", update, { passive: true }); viewport.addEventListener("wheel", handleWheel, { passive: false }); - return () => viewport.removeEventListener("wheel", handleWheel); - }, [updateTabScrollState]); + update(); + + return () => { + tabListRef.current = null; + stopObserving(); + viewport.removeEventListener("scroll", update); + viewport.removeEventListener("wheel", handleWheel); + }; + }; return ( { await expect.element(screen.getByRole("status")).toHaveTextContent(String(lastWakeMs)); }); }); + +function JumpHints(props: { readonly held: boolean }) { + return {useThreadJumpHintsVisible(props.held) ? "shown" : "hidden"}; +} + +describe("useThreadJumpHintsVisible", () => { + it("waits for the delay again on a second hold", async () => { + // The first render reads the clock. + using _timers = fakeTimers({ now: 0 }); + await using screen = await render(, { + // A bare hook host; nothing here links or navigates. + router: false, + }); + await act(() => vi.advanceTimersByTime(1_000)); + await expect.element(screen.getByRole("status")).toHaveTextContent("shown"); + + await screen.rerender(); + await expect.element(screen.getByRole("status")).toHaveTextContent("hidden"); + await act(() => vi.advanceTimersByTime(1_000)); + + await screen.rerender(); + await expect.element(screen.getByRole("status")).toHaveTextContent("hidden"); + await act(() => vi.advanceTimersByTime(1_000)); + await expect.element(screen.getByRole("status")).toHaveTextContent("shown"); + }); +}); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 63f1dd5a570a0..f7403d2f85c48 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -670,10 +670,13 @@ type ThreadStatusInput = Pick< */ export function useThreadJumpHintsVisible(shouldShow: boolean): boolean { const [showAt, setShowAt] = React.useState(null); - let nextShowAt = shouldShow ? showAt : null; - if (shouldShow && showAt === null) nextShowAt = deadlineAfter(THREAD_JUMP_HINT_SHOW_DELAY_MS); - if (nextShowAt !== showAt) setShowAt(nextShowAt); - return useDeadlinePassed(nextShowAt); + // The clock is read inside the updater: the compiler caches a bare clock read + // in render once per instance, so a second hold would reuse the first deadline. + // React discards this render and re-runs with the update. + if (shouldShow !== (showAt !== null)) { + setShowAt(shouldShow ? () => deadlineAfter(THREAD_JUMP_HINT_SHOW_DELAY_MS) : null); + } + return useDeadlinePassed(showAt); } export function resolveThreadLastVisitedAt( diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 9ba16b6206565..1f1706b7e3ac8 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -3115,6 +3115,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve className="mt-auto" label="Working" count={workingThreads.length} + hostsUndoNotice toggle={{ expanded: workingShelfExpanded, onToggle: toggleWorkingShelf, @@ -3130,6 +3131,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve className={cn(workingThreads.length === 0 && "mt-auto")} label="Snoozed" count={snoozedThreads.length} + hostsUndoNotice={workingThreads.length === 0} toggle={{ expanded: snoozedShelfExpanded, onToggle: toggleSnoozedShelf, @@ -3147,6 +3149,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve )} label="Settled" count={settledCount} + hostsUndoNotice={ + workingThreads.length + snoozedThreads.length === 0 + } dragging={from !== null} isDropTarget={dragTargetSection === "settled"} toggle={{ @@ -3238,7 +3243,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) : null} - + ); } diff --git a/apps/web/src/components/SlowRpcRequestToastCoordinator.tsx b/apps/web/src/components/SlowRpcRequestToastCoordinator.tsx index 2300ad7aaf5ea..4536987ab3b7d 100644 --- a/apps/web/src/components/SlowRpcRequestToastCoordinator.tsx +++ b/apps/web/src/components/SlowRpcRequestToastCoordinator.tsx @@ -1,6 +1,4 @@ -import { useEffect, useRef } from "react"; - -import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState"; +import { type SlowRpcAckRequest, subscribeSlowRpcAckRequests } from "../rpc/requestLatencyState"; import { toastManager } from "./ui/toast"; function describeSlowRequests(requests: ReadonlyArray): string { @@ -30,15 +28,15 @@ function SlowRequestDetails({ requests }: { requests: ReadonlyArray | null>(null); +/** One warning toast that tracks the set of slow requests while any are outstanding. */ +export function startSlowRpcRequestToasts(): () => void { + let toastId: ReturnType | null = null; - useEffect(() => { + const unsubscribe = subscribeSlowRpcAckRequests((slowRequests) => { if (slowRequests.length === 0) { - if (toastIdRef.current !== null) { - toastManager.close(toastIdRef.current); - toastIdRef.current = null; + if (toastId !== null) { + toastManager.close(toastId); + toastId = null; } return; } @@ -55,21 +53,15 @@ export function SlowRpcRequestToastCoordinator() { type: "warning" as const, }; - if (toastIdRef.current === null) { - toastIdRef.current = toastManager.add(nextToast); + if (toastId === null) { + toastId = toastManager.add(nextToast); } else { - toastManager.update(toastIdRef.current, nextToast); + toastManager.update(toastId, nextToast); } - }, [slowRequests]); - - useEffect( - () => () => { - if (toastIdRef.current !== null) { - toastManager.close(toastIdRef.current); - } - }, - [], - ); + }); - return null; + return () => { + unsubscribe(); + if (toastId !== null) toastManager.close(toastId); + }; } diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index 6efba489ebb7a..cf3c0427c57c3 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -1,22 +1,14 @@ import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; -import type { ScopedThreadRef } from "@t3tools/contracts"; -import { useNavigate } from "@tanstack/react-router"; +import { Navigate, useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; import ChatView from "./ChatView"; import { BackgroundThreadContext } from "./chat/backgroundThread"; -import { resolveDraftPromotionNavigationTarget, threadHasStarted } from "./ChatView.logic"; -import { waitForDraftHeroTransition } from "./chat/draftHeroTransition"; import { SidebarInset } from "./ui/sidebar"; -import { - finalizePromotedDraftThreadByRef, - markPromotedDraftThreadByRef, - useBackgroundDraftSubmissionPending, - useComposerDraftStore, -} from "../composerDraftStore"; +import { useComposerDraftStore } from "../composerDraftStore"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; -import { useEnvironmentThreadRefs, useThreadRefs, useQuietThreadShell } from "../state/entities"; +import { useEnvironmentThreadRefs, useQuietThreadShell } from "../state/entities"; import { useEnvironmentShellStatus } from "../state/shell"; import { useEnvironmentThread } from "../state/threads"; import { @@ -27,7 +19,9 @@ import { } from "../threadRoutes"; /** - * Render in the shared layout to retain ChatView across route swaps; plain server threads remain unkeyed. + * Unkeyed so navigating between server threads reuses one ChatView. Rendered by the `_chat` + * layout, since an element only survives a route swap when the same parent renders it. Draft + * promotion runs in the draft store; this only follows the redirect it leaves behind. * `background` keeps the thread mounted, inert and in place under Settings or Usage. */ export function ThreadRouteView({ @@ -42,53 +36,36 @@ export function ThreadRouteView({ const draftSession = useComposerDraftStore((store) => draftId === null ? null : store.getDraftSession(draftId), ); - const threadRefs = useThreadRefs(); - // Promotion can begin before the server creates the reserved thread. - const inferredThreadRef = draftSession - ? (threadRefs.find( - (ref) => - ref.environmentId === draftSession.environmentId && - ref.threadId === draftSession.threadId, - ) ?? null) - : null; - const serverThreadRef: ScopedThreadRef | null = - target.kind === "server" ? target.threadRef : inferredThreadRef; - const serverThread = useQuietThreadShell(serverThreadRef); - const backgroundSubmissionPending = useBackgroundDraftSubmissionPending( - target.kind === "draft" ? serverThreadRef : null, + const draftRedirect = useComposerDraftStore((store) => + draftId === null ? null : store.getPromotedDraftRedirect(draftId), ); - const canonicalThreadRef = - target.kind === "draft" - ? resolveDraftPromotionNavigationTarget({ - serverThreadRef, - serverThread, - backgroundSubmissionPending, - }) - : null; - + const serverThreadRef = target.kind === "server" ? target.threadRef : null; + const serverThreadShell = useQuietThreadShell(serverThreadRef); const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null); - const serverThreadShell = serverThread; const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null); const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus); const draftThread = useComposerDraftStore((store) => serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null, ); - const promotedDraftId = useComposerDraftStore((store) => - target.kind === "server" ? store.getDraftIdByRef(target.threadRef) : null, + // Reached from the sidebar before finalize, the thread still has its draft. + const serverThreadDraftId = useComposerDraftStore((store) => + serverThreadRef ? store.getDraftIdByRef(serverThreadRef) : null, ); - // Latch the key through promotion because the draft record disappears after the route swap. - const [chatViewKey, setChatViewKey] = useState<{ threadKey: string; key: string } | null>(null); - const serverThreadKey = target.kind === "server" ? scopedThreadKey(target.threadRef) : null; - const nextChatViewKey = - serverThreadKey === null - ? null - : chatViewKey?.threadKey === serverThreadKey - ? chatViewKey - : promotedDraftId - ? { threadKey: serverThreadKey, key: promotedDraftId } + // The ChatView that carried a draft keeps its key through the redirect to its thread, and only + // until the route leaves that thread, so later visits reuse the shared unkeyed ChatView. + const [handoffKey, setHandoffKey] = useState<{ threadKey: string; key: string } | null>(null); + const nextHandoffKey = + draftId !== null && draftSession === null && draftRedirect + ? handoffKey?.key === draftId + ? handoffKey + : { threadKey: scopedThreadKey(draftRedirect), key: draftId } + : serverThreadRef && handoffKey?.threadKey === scopedThreadKey(serverThreadRef) + ? handoffKey + : serverThreadRef && serverThreadDraftId + ? { threadKey: scopedThreadKey(serverThreadRef), key: serverThreadDraftId } : null; - if (nextChatViewKey !== chatViewKey) { - setChatViewKey(nextChatViewKey); + if (nextHandoffKey !== handoffKey) { + setHandoffKey(nextHandoffKey); } const environmentHasDraftThreads = useComposerDraftStore((store) => serverThreadRef ? store.hasDraftThreadsInEnvironment(serverThreadRef.environmentId) : false, @@ -111,43 +88,8 @@ export function ThreadRouteView({ unlistedThreadDetail, draftThreadExists: draftThread !== null, }); - const serverThreadStarted = threadHasStarted(serverThreadShell); const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads; - useEffect(() => { - if (!inferredThreadRef || draftSession?.promotedTo) { - return; - } - markPromotedDraftThreadByRef(inferredThreadRef); - }, [draftSession?.promotedTo, inferredThreadRef]); - - useEffect(() => { - if (!canonicalThreadRef || background) { - return; - } - let cancelled = false; - void waitForDraftHeroTransition().then(() => { - if (cancelled) { - return; - } - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(canonicalThreadRef), - replace: true, - }); - }); - return () => { - cancelled = true; - }; - }, [background, canonicalThreadRef, navigate]); - - useEffect(() => { - if (background || target.kind !== "draft" || draftSession || canonicalThreadRef) { - return; - } - void navigate({ to: "/", replace: true }); - }, [background, canonicalThreadRef, draftSession, navigate, target.kind]); - useEffect(() => { if (target.kind !== "server" || !bootstrapComplete) { return; @@ -161,14 +103,8 @@ export function ThreadRouteView({ } }, [background, bootstrapComplete, environmentHasAnyThreads, navigate, renderState, target]); - useEffect(() => { - if (target.kind !== "server" || !serverThreadStarted || !draftThread) { - return; - } - finalizePromotedDraftThreadByRef(target.threadRef); - }, [draftThread, serverThreadStarted, target]); - let view: React.ReactNode = null; + let redirect: React.ReactNode = null; if (target.kind === "draft") { if (draftSession) { view = ( @@ -181,11 +117,30 @@ export function ThreadRouteView({ forceExpandedMobileComposer /> ); + } else if (draftRedirect) { + // Same slot and key as the server route renders, so the swap keeps this instance. + view = ( + + ); + redirect = ( + + ); + } else { + redirect = ; } } else if (renderState === "ready" || (renderState === "loading" && serverThreadShell !== null)) { view = ( {view} + {background ? null : redirect} ); } diff --git a/apps/web/src/components/ThreadTerminalDrawer.test.ts b/apps/web/src/components/ThreadTerminalDrawer.test.ts index 82b58e859f67c..9979d3563ff88 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.test.ts +++ b/apps/web/src/components/ThreadTerminalDrawer.test.ts @@ -11,6 +11,7 @@ import { shouldClearTerminalSelectionAction, shouldHandleTerminalExit, synchronizeTerminalOutput, + synchronizeTerminalSession, } from "./ThreadTerminalDrawer"; describe("terminal selection actions", () => { @@ -87,3 +88,16 @@ it("retains visible output and selection until a replacement subscription receiv synchronizeTerminalOutput(terminal, cleared, observedCursor); expect(terminal.resetAndWrite).toHaveBeenLastCalledWith(""); }); + +it("reports an attach failure that leaves the output unchanged", () => { + const terminal = { resetAndWrite: vi.fn(), write: vi.fn(), clearSelection: vi.fn() }; + const previous = { ...EMPTY_TERMINAL_BUFFER_STATE, error: null }; + const failed = { ...previous, error: "Terminal attach failed" }; + + expect( + synchronizeTerminalSession(terminal, previous, failed, INITIAL_TERMINAL_OUTPUT_CURSOR), + ).toBe(INITIAL_TERMINAL_OUTPUT_CURSOR); + expect(terminal.write).toHaveBeenCalledWith("\r\n[terminal] Terminal attach failed\r\n"); + expect(terminal.resetAndWrite).not.toHaveBeenCalled(); + expect(terminal.clearSelection).not.toHaveBeenCalled(); +}); diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index 07c8c9fcff73a..5e87cd70b784a 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -1,3 +1,4 @@ +import { useAtomMount } from "@effect/atom-react"; import { isAtomCommandInterrupted, squashAtomCommandFailure, @@ -30,7 +31,6 @@ import * as Schema from "effect/Schema"; import { type PointerEvent as ReactPointerEvent, type ReactNode, - type SetStateAction, useEffect, useEffectEvent, useLayoutEffect, @@ -73,7 +73,8 @@ import { readLocalApi } from "~/localApi"; import { confirmTerminalClose } from "~/lib/terminalCloseConfirm"; import { useClientSettings } from "../hooks/useSettings"; import { useLocalStorage } from "../hooks/useLocalStorage"; -import { useAttachedTerminalSession } from "../state/terminalSessions"; +import { attachedTerminalSessionAtom } from "../state/terminalSessions"; +import { appAtomRegistry } from "../rpc/atomRegistry"; import { terminalEnvironment } from "../state/terminal"; import { useAtomCommand } from "../state/use-atom-command"; import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut"; @@ -117,6 +118,8 @@ function resolveTerminalDrawerMaxHeight(input: DrawerLayout): number { ); } +const DRAG_HEIGHT_PROPERTY = "--terminal-drawer-drag-height"; + function clampDrawerHeight(height: number, maxHeight: number): number { const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT; return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight); @@ -136,7 +139,10 @@ function readDrawerLayout(column: HTMLElement | null): Omit, + message: string, +): void { terminal.write(`\r\n[terminal] ${message}\r\n`); } @@ -163,6 +169,24 @@ export function synchronizeTerminalOutput( return update.cursor; } +/** Writes what changed between two session notifications: new output, then a new error. */ +export function synchronizeTerminalSession( + terminal: Pick, + previous: Pick, + session: Pick, + cursor: TerminalOutputCursor, +): TerminalOutputCursor { + const nextCursor = + session.version === previous.version && session.output === previous.output + ? cursor + : synchronizeTerminalOutput(terminal, session, cursor); + // An attach failure can change only the error, keeping the last buffer. + if (session.error !== null && session.error !== previous.error) { + writeSystemMessage(terminal, session.error); + } + return nextCursor; +} + function parseTerminalColor(value: string, fallback: GhosttyColor): GhosttyColor { if (typeof document === "undefined") return fallback; @@ -392,6 +416,19 @@ export function shouldClearTerminalSelectionAction(options: { return options.actionPending || options.openMenuRequestId === options.currentRequestId; } +/** + * A writable session's output generation. A new one is a fresh PTY (or a + * reconnect) that has not seen the surface's grid yet. + */ +function writableSessionGeneration( + session: TerminalSessionState, + canOperate: boolean, +): number | null { + return canOperate && session.version > 0 && session.status === "running" + ? session.output.generation + : null; +} + export function shouldHandleTerminalExit( current: TerminalSessionState["status"], synchronized: TerminalSessionState["status"], @@ -421,8 +458,6 @@ interface TerminalViewportProps { /** Focuses the viewport when it mounts; otherwise focus arrives through `focusTerminal`. */ autoFocus?: boolean; visible: boolean; - resizeEpoch: number; - drawerHeight: number; keybindings: ResolvedKeybindingsConfig; } @@ -458,8 +493,6 @@ function TerminalSessionViewport({ onAddTerminalContext, autoFocus = false, visible, - resizeEpoch, - drawerHeight, keybindings, }: TerminalViewportProps) { const containerRef = useRef(null); @@ -508,20 +541,23 @@ function TerminalSessionViewport({ }), ); const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize }); - const terminalSession = useAttachedTerminalSession({ - environmentId, - terminal: { - threadId, - terminalId, - cwd, - ...(worktreePath !== undefined ? { worktreePath } : {}), - ...(runtimeEnv ? { env: runtimeEnv } : {}), - ...(providerInstanceId ? { providerInstanceId } : {}), - }, + // Keyed by the launch (see TerminalViewport), so the atom is fixed for this surface. + const terminalSessionAtom = attachedTerminalSessionAtom(environmentId, { + threadId, + terminalId, + cwd, + ...(worktreePath !== undefined ? { worktreePath } : {}), + ...(runtimeEnv ? { env: runtimeEnv } : {}), + ...(providerInstanceId ? { providerInstanceId } : {}), }); - const canResizeTerminal = - canOperateTerminal && terminalSession.version > 0 && terminalSession.status === "running"; - const resizeSessionGeneration = canResizeTerminal ? terminalSession.output.generation : null; + // Attaching starts with the viewport, while the WASM surface is still loading; + // the surface reads the session itself, so output chunks never re-render here. + useAtomMount(terminalSessionAtom); + const readTerminalSession = useEffectEvent(() => appAtomRegistry.get(terminalSessionAtom)); + const subscribeTerminalSession = useEffectEvent( + (listener: (session: TerminalSessionState) => void) => + appAtomRegistry.subscribe(terminalSessionAtom, listener), + ); const writeTerminal = useEffectEvent((data: string) => runTerminalWrite({ environmentId, @@ -529,15 +565,14 @@ function TerminalSessionViewport({ }), ); const resizeTerminal = useEffectEvent((cols: number, rows: number) => { - if (!canResizeTerminal || !hasTerminalWriteAccess()) return; + if (writableSessionGeneration(readTerminalSession(), hasTerminalWriteAccess()) === null) { + return; + } return runTerminalResize({ environmentId, input: { threadId, terminalId, cols, rows }, }); }); - const terminalOutput = terminalSession.output; - const terminalError = terminalSession.error; - const terminalStatus = terminalSession.status; const outputCursorRef = useRef(INITIAL_TERMINAL_OUTPUT_CURSOR); const synchronizedStatusRef = useRef("closed"); const synchronizeTerminalStatus = useEffectEvent( @@ -559,19 +594,6 @@ function TerminalSessionViewport({ if (version > 0) synchronizedStatusRef.current = status; }, ); - const terminalVersion = terminalSession.version; - const previousSessionRef = useRef({ - output: terminalOutput, - error: terminalError, - status: terminalStatus, - version: terminalVersion, - }); - const readLatestSession = useEffectEvent(() => ({ - output: terminalOutput, - error: terminalError, - status: terminalStatus, - version: terminalVersion, - })); useLayoutEffect(() => { if (terminalRef.current) terminalRef.current.input.readOnly = !canOperateTerminal; @@ -579,13 +601,6 @@ function TerminalSessionViewport({ consumePendingTerminalFocus(threadRef, terminalId); }, [canOperateTerminal, terminalId, threadRef]); - useEffect(() => { - if (resizeSessionGeneration === null) return; - // The first fit can precede authorization/attach; replay the grid for each writable session, including - // reconnects. - terminalRef.current?.resendSize(); - }, [resizeSessionGeneration]); - useLayoutEffect(() => { visibleRef.current = visible; terminalRef.current?.setVisible(visible); @@ -643,8 +658,7 @@ function TerminalSessionViewport({ if (currentFont.family !== setupFont.family || currentFont.size !== setupFont.size) { void terminal.setFont(terminalFontOptions(currentFont.family, currentFont.size)); } - const latestSession = readLatestSession(); - previousSessionRef.current = latestSession; + const latestSession = readTerminalSession(); const initialOutput = readTerminalOutputUpdate( latestSession.output, INITIAL_TERMINAL_OUTPUT_CURSOR, @@ -656,6 +670,29 @@ function TerminalSessionViewport({ if (latestSession.error !== null) writeSystemMessage(terminal, latestSession.error); synchronizedStatusRef.current = "closed"; synchronizeTerminalStatus(terminal, latestSession.status, latestSession.version); + // Read and subscribe in one synchronous step so no output lands between them. + let previousSession = latestSession; + let resizeGeneration = writableSessionGeneration(latestSession, hasTerminalWriteAccess()); + setupCleanups.push( + subscribeTerminalSession((session) => { + const nextResizeGeneration = writableSessionGeneration(session, hasTerminalWriteAccess()); + if (nextResizeGeneration !== resizeGeneration) { + resizeGeneration = nextResizeGeneration; + // The first fit can precede authorization/attach; replay the grid for each writable session, including + // reconnects. + if (nextResizeGeneration !== null) terminal.resendSize(); + } + const previous = previousSession; + previousSession = session; + synchronizeTerminalStatus(terminal, session.status, session.version); + outputCursorRef.current = synchronizeTerminalSession( + terminal, + previous, + session, + outputCursorRef.current, + ); + }), + ); if ( hasTerminalWriteAccess() && visibleRef.current && @@ -1006,53 +1043,6 @@ function TerminalSessionViewport({ }; }, [cwd, environmentId, terminalId]); - useEffect(() => { - const terminal = terminalRef.current; - const current = { - output: terminalOutput, - error: terminalError, - status: terminalStatus, - version: terminalVersion, - }; - if (!terminal) { - previousSessionRef.current = current; - return; - } - - const previous = previousSessionRef.current; - synchronizeTerminalStatus(terminal, current.status, current.version); - if (current.version === previous.version && current.output === previous.output) { - return; - } - - outputCursorRef.current = synchronizeTerminalOutput(terminal, current, outputCursorRef.current); - - if (current.error !== null && current.error !== previous.error) { - writeSystemMessage(terminal, current.error); - } - - previousSessionRef.current = current; - }, [terminalOutput, terminalError, terminalStatus, terminalVersion]); - - // A hidden surface skips fitting, and showing it again fits through setVisible. - const layoutRevision = visible ? `${drawerHeight}:${resizeEpoch}` : null; - useEffect(() => { - const terminal = terminalRef.current; - if (!terminal || layoutRevision === null) return; - const wasAtBottom = terminal.isAtBottom(); - // onResize alone sends PTY resize RPCs; fitting here only refreshes layout. - const frame = window.requestAnimationFrame(() => { - if (!visibleRef.current) return; - terminal.fit(); - if (wasAtBottom) { - terminal.scrollToBottom(); - } - }); - return () => { - window.cancelAnimationFrame(frame); - }; - }, [layoutRevision]); - const attachContainer = (mount: HTMLDivElement) => { containerRef.current = mount; const focus = () => @@ -1176,8 +1166,6 @@ function TerminalSplitPanes({ threadId, onAddTerminalContext, visible, - resizeEpoch, - drawerHeight, keybindings, }: { terminalIds: readonly string[]; @@ -1192,8 +1180,6 @@ function TerminalSplitPanes({ threadId: ThreadId; onAddTerminalContext: (selection: TerminalContextSelection) => void; visible: boolean; - resizeEpoch: number; - drawerHeight: number; keybindings: ResolvedKeybindingsConfig; }) { return ( @@ -1242,8 +1228,6 @@ function TerminalSplitPanes({ onSessionExited={() => onCloseTerminal(terminalId)} onAddTerminalContext={onAddTerminalContext} visible={visible} - resizeEpoch={resizeEpoch} - drawerHeight={drawerHeight} keybindings={keybindings} />
    @@ -1387,36 +1371,19 @@ export default function ThreadTerminalDrawer({ false, Schema.Boolean, ); - const controlledDrawerHeight = height; const drawerRef = useRef(null); const [drawerLayout, setDrawerLayout] = useState(() => readDrawerLayout(null)); const maxDrawerHeight = resolveTerminalDrawerMaxHeight({ ...drawerLayout, composerHeight }); - const [drawerHeightState, setDrawerHeightState] = useState(() => ({ - threadId, - height: controlledDrawerHeight, - })); - const preferredDrawerHeight = - drawerHeightState.threadId === threadId ? drawerHeightState.height : controlledDrawerHeight; - const drawerHeight = clampDrawerHeight(preferredDrawerHeight, maxDrawerHeight); - const setDrawerHeight = (update: SetStateAction) => { - setDrawerHeightState((current) => { - const currentHeight = current.threadId === threadId ? current.height : controlledDrawerHeight; - const nextHeight = typeof update === "function" ? update(currentHeight) : update; - return nextHeight === currentHeight && current.threadId === threadId - ? current - : { threadId, height: nextHeight }; - }); - }; - const [resizeEpoch, setResizeEpoch] = useState(0); - const drawerHeightRef = useRef(drawerHeight); - const lastSyncedHeightRef = useRef({ threadId, height: controlledDrawerHeight }); + const drawerHeight = clampDrawerHeight(height, maxDrawerHeight); + // A drag only writes the drawer's style; the store hears the height once, at + // pointerup. The custom property outranks the rendered height while it is set. const resizeStateRef = useRef<{ pointerId: number; startY: number; startHeight: number; + height: number; drawer: HTMLElement | null; } | null>(null); - const didResizeDuringDragRef = useRef(false); const normalizedTerminalIds = (() => { const normalizedIds: string[] = []; @@ -1586,35 +1553,15 @@ export default function ThreadTerminalDrawer({ }); }; - useLayoutEffect(() => { - const resizeState = resizeStateRef.current; - if (resizeState) { - resizeState.drawer?.style.setProperty("height", `${drawerHeightRef.current}px`); - return; - } - drawerHeightRef.current = drawerHeight; - }, [drawerHeight]); - - const syncHeight = (nextHeight: number) => { - const lastSynced = lastSyncedHeightRef.current; - if (lastSynced.threadId === threadId && lastSynced.height === nextHeight) return; - lastSyncedHeightRef.current = { threadId, height: nextHeight }; - onHeightChange(nextHeight); - }; - - useEffect(() => { - lastSyncedHeightRef.current = { threadId, height: controlledDrawerHeight }; - }, [controlledDrawerHeight, threadId]); - const handleResizePointerDown = (event: ReactPointerEvent) => { if (event.button !== 0) return; event.preventDefault(); event.currentTarget.setPointerCapture(event.pointerId); - didResizeDuringDragRef.current = false; resizeStateRef.current = { pointerId: event.pointerId, startY: event.clientY, - startHeight: drawerHeightRef.current, + startHeight: drawerHeight, + height: drawerHeight, drawer: event.currentTarget.parentElement, }; }; @@ -1627,12 +1574,11 @@ export default function ThreadTerminalDrawer({ resizeState.startHeight + (resizeState.startY - event.clientY), maxDrawerHeight, ); - if (clampedHeight === drawerHeightRef.current) { + if (clampedHeight === resizeState.height) { return; } - didResizeDuringDragRef.current = true; - drawerHeightRef.current = clampedHeight; - resizeState.drawer?.style.setProperty("height", `${clampedHeight}px`); + resizeState.height = clampedHeight; + resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${clampedHeight}px`); }; const handleResizePointerEnd = (event: ReactPointerEvent) => { @@ -1642,19 +1588,11 @@ export default function ThreadTerminalDrawer({ if (event.currentTarget.hasPointerCapture(event.pointerId)) { event.currentTarget.releasePointerCapture(event.pointerId); } + resizeState.drawer?.style.removeProperty(DRAG_HEIGHT_PROPERTY); // A drag that ends where it started keeps the stored preference, which may // be taller than the capped height the drag started from. - if (!didResizeDuringDragRef.current || drawerHeightRef.current === resizeState.startHeight) { - // React skips the write when the rendered height did not change, so put - // back the preference as the current layout caps it. - const renderedHeight = clampDrawerHeight(preferredDrawerHeight, maxDrawerHeight); - drawerHeightRef.current = renderedHeight; - resizeState.drawer?.style.setProperty("height", `${renderedHeight}px`); - return; - } - setDrawerHeight(drawerHeightRef.current); - syncHeight(drawerHeightRef.current); - setResizeEpoch((value) => value + 1); + if (resizeState.height === resizeState.startHeight || resizeState.height === height) return; + onHeightChange(resizeState.height); }; const drawerLayoutRef = useRef(drawerLayout); @@ -1671,16 +1609,17 @@ export default function ThreadTerminalDrawer({ if (!heightBudgetChanged && source === "column") return; drawerLayoutRef.current = layout; const resizeState = resizeStateRef.current; - const liveHeight = clampDrawerHeight( - drawerHeightRef.current, - resolveTerminalDrawerMaxHeight({ ...layout, composerHeight }), - ); - if (resizeState && liveHeight !== drawerHeightRef.current) { - drawerHeightRef.current = liveHeight; - resizeState.drawer?.style.setProperty("height", `${liveHeight}px`); + if (resizeState) { + const liveHeight = clampDrawerHeight( + resizeState.height, + resolveTerminalDrawerMaxHeight({ ...layout, composerHeight }), + ); + if (liveHeight !== resizeState.height) { + resizeState.height = liveHeight; + resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${liveHeight}px`); + } } if (heightBudgetChanged) setDrawerLayout(layout); - setResizeEpoch((value) => value + 1); }, ); useLayoutEffect(() => { @@ -1705,9 +1644,6 @@ export default function ThreadTerminalDrawer({ }; }, [isPanel, visible]); - const syncPreferredHeight = useEffectEvent(() => syncHeight(preferredDrawerHeight)); - useEffect(() => () => syncPreferredHeight(), []); - if (normalizedTerminalIds.length === 0) { return (