From f9b19a7f855b7e10f057cab6b4bc17ea43188623 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 20:14:30 -0800 Subject: [PATCH 001/162] fix(server): folder discovery skips the walk when t3.json ignores the whole project (#40664) --- .../src/workspace/WorkspaceFolders.test.ts | 37 +++++++++++++++++++ apps/server/src/workspace/WorkspaceFolders.ts | 12 +++--- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 61dac26a8c044..4c5b33bbf7776 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -193,6 +193,43 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { }), ); + it.effect("does not walk a project's folders when t3.json ignores the whole project", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceRoot = yield* makeTempDir; + for (const folder of ["api/.git", "src/web/.git", "notes"]) { + yield* fileSystem.makeDirectory(path.join(workspaceRoot, folder), { recursive: true }); + } + yield* fileSystem.writeFileString( + path.join(workspaceRoot, "t3.json"), + JSON.stringify({ ignoreRepositories: ["."] }), + ); + const probed: Array = []; + const counting = FileSystem.FileSystem.of({ + ...fileSystem, + readDirectory: (target, options) => { + probed.push(target); + return fileSystem.readDirectory(target, options); + }, + stat: (target) => { + probed.push(target); + return fileSystem.stat(target); + }, + }); + + const found = yield* WorkspaceFolders.discoverFolders(workspaceRoot).pipe( + Effect.provideService(FileSystem.FileSystem, counting), + ); + + assert.deepEqual(found, []); + assert.deepEqual( + probed.filter((target) => target !== workspaceRoot), + [], + ); + }), + ); + it.effect("keeps the folders someone added when a project holds more than fit", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index 776f90ea6e5b0..9b21fd3fbcc62 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -276,11 +276,7 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function* const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const { realPath, ownsHistory } = yield* folderProbes; - // Uncapped: the folders outside the project are dropped below, and must not use up the room. - const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option); - if (Option.isNone(scan)) return []; - const root = scan.value.workspaceRoot; - const realRoot = yield* realPath(root); + const root = path.resolve(expandHomePath(workspaceRoot.trim(), yield* HostProcess.HomeDirectory)); const ignored = ( parseT3ProjectFile( yield* fileSystem @@ -288,6 +284,12 @@ export const discoverFolders = Effect.fn("WorkspaceFolders.discover")(function* .pipe(Effect.orElseSucceed(() => "")), )?.ignoreRepositories ?? [] ).map((entry) => path.resolve(root, entry)); + // Everything the scan could find would be dropped, so skip the walk. + if (ignored.some((entry) => isWithinRoot(path, root, entry))) return []; + // Uncapped: the folders outside the project are dropped below, and must not use up the room. + const scan = yield* scanFolders({ workspaceRoot }, Number.POSITIVE_INFINITY).pipe(Effect.option); + if (Option.isNone(scan)) return []; + const realRoot = yield* realPath(root); const inside = yield* Effect.filter( scan.value.folders.filter( (folder) => From 28a420060b321ce3317f8529a5db5138af97c189 Mon Sep 17 00:00:00 2001 From: Sudharsan <126713117+Sidreyas@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:06:26 +0530 Subject: [PATCH 002/162] fix(server): checkpoint repository scopes walk the project folder once per turn (#40671) Co-authored-by: Julius Marminge --- .../src/orchestration-v2/CheckpointService.ts | 9 ++++---- .../src/workspace/WorkspaceFolders.test.ts | 22 +++++++++++-------- apps/server/src/workspace/WorkspaceFolders.ts | 5 +++-- 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index 079ac88211870..ec3e872d61c2b 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -924,10 +924,11 @@ export const layer: Layer.Layer< const repositoryScopesIfReadable: CheckpointServiceV2Shape["repositoryScopesIfReadable"] = Effect.fn("CheckpointService.repositoryScopes")( function* (input) { - const [workspace, submodules] = yield* Effect.all([ - workspaceFolders.forThread(input), - workspaceFolders.submodules(input), - ]); + const workspace = yield* workspaceFolders.forThread(input); + const submodules = yield* workspaceFolders.submodules({ + ...input, + folders: workspace.folders, + }); return yield* Effect.forEach( [...workspace.folders.filter((folder) => folder.isGitRepository), ...submodules], (folder) => diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 4c5b33bbf7776..3a02d202be891 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -330,17 +330,21 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { folders: [], extraRoots: [], }); - assert.deepEqual(yield* workspaceFolders.submodules({ projectId, worktreePath: null }), [ - { name: "lib", path: path.join(workspaceRoot, "vendor", "lib"), isGitRepository: true }, - { - name: "deep", - path: path.join(workspaceRoot, "vendor", "lib", "deep"), - isGitRepository: true, - }, - ]); + const { folders } = yield* workspaceFolders.forThread({ projectId, worktreePath: null }); + assert.deepEqual( + yield* workspaceFolders.submodules({ projectId, worktreePath: null, folders }), + [ + { name: "lib", path: path.join(workspaceRoot, "vendor", "lib"), isGitRepository: true }, + { + name: "deep", + path: path.join(workspaceRoot, "vendor", "lib", "deep"), + isGitRepository: true, + }, + ], + ); // A worktree reaches its own submodules, named by where the project folder has them. assert.deepEqual( - yield* workspaceFolders.submodules({ projectId, worktreePath: worktree }), + yield* workspaceFolders.submodules({ projectId, worktreePath: worktree, folders: [] }), [ { name: "lib", diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index 9b21fd3fbcc62..0824c647ce360 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -64,6 +64,8 @@ export class WorkspaceFolders extends Context.Service< readonly submodules: (input: { readonly projectId: ProjectId; readonly worktreePath: string | null; + /** The thread's `forThread` folders; passed in so the project is walked once. */ + readonly folders: ReadonlyArray; }) => Effect.Effect, WorkspaceFoldersError>; readonly list: ( input: WorkspaceListFoldersInput, @@ -508,7 +510,6 @@ const make = Effect.gen(function* () { const submodules: WorkspaceFolders["Service"]["submodules"] = Effect.fn( "WorkspaceFolders.submodules", )(function* (input) { - const { folders } = yield* forThread(input); // A worktree can outlive its project record; its submodules are then named by where they are. const projectRoot = yield* readProject(input.projectId).pipe( Effect.map((project) => path.resolve(project.workspaceRoot)), @@ -520,7 +521,7 @@ const make = Effect.gen(function* () { const identity = Option.getOrElse(projectRoot, () => root); return yield* submodulesOf([ { path: root, identity }, - ...folders.flatMap((folder) => + ...input.folders.flatMap((folder) => folder.isGitRepository ? [{ path: folder.path, identity: folder.repositoryPath ?? folder.path }] : [], From c5fa33b27e45ca48fea7b4e12337b8560845f3db Mon Sep 17 00:00:00 2001 From: MIT-Consulting Date: Sun, 22 Nov 2026 00:42:40 -0500 Subject: [PATCH 003/162] fix(server,cursor): preserve inline handoff when a failed Cursor turn drops its prompt (#40670) Co-authored-by: Julius Marminge --- .../ContextHandoffDelivery.ts | 10 +- .../src/orchestration-v2/Orchestrator.ts | 5 +- .../ProviderTurnStartService.ts | 103 +++++++--- .../orchestration-v2/RestartBackgroundNote.ts | 35 ++-- .../RunExecutionService.test.ts | 48 +++++ .../orchestration-v2/RunExecutionService.ts | 192 ++++++++++++------ .../ProviderSwitch.integration.test.ts | 169 +++++++++++++++ packages/contracts/src/orchestrationV2.ts | 8 + .../src/server/ProviderAdapter.ts | 4 + .../src/server/adapter.test.ts | 143 +++++++++++++ .../provider-cursor/src/server/adapter.ts | 14 ++ .../orchestrationV2ManualContinuation.test.ts | 12 ++ .../src/orchestrationV2ManualContinuation.ts | 10 +- 13 files changed, 634 insertions(+), 119 deletions(-) diff --git a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts index 5211da2faf169..72471eb8cf944 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffDelivery.ts @@ -37,7 +37,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH handoff.delivery.status === "pending", ); if (pending.length === 0 || (input.deferInline && input.inject === undefined)) - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; const budget = typeof input.budget === "number" ? input.budget : yield* input.budget; let coverage = pending .map( @@ -76,7 +76,8 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH budget, }); if (historyCost(selected.messages, selected.context) > budget) { - if (input.deferInline) return { context: "", delivered: Effect.void, unsent: Effect.void }; + if (input.deferInline) + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; return yield* new ContextHandoffBudgetError(); } const omittedItemIds = new Set(selected.omittedItemIds); @@ -127,7 +128,7 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH }); if (injected) { yield* persist("injected"); - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; } } else { yield* persist("pending"); @@ -135,12 +136,13 @@ export const deliverContextHandoffs = Effect.fn("orchestrationV2.deliverContextH if (input.deferInline) { // Compaction cannot carry inline transcripts; retain for the next turn if native injection is unsupported. yield* Effect.forEach(pending, input.persist, { discard: true }); - return { context: "", delivered: Effect.void, unsent: Effect.void }; + return { context: "", delivered: Effect.void, unsent: Effect.void, inlineHandoffs: [] }; } return { context: renderHistory(selected.messages, selected.context), delivered: persist("inline"), unsent: Effect.forEach(pending, input.persist, { discard: true }), + inlineHandoffs: pending, }; }, ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 4f1d2d671060e..995ff63b25747 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -28,6 +28,7 @@ import { CommandId, type GuestMessageId, isCompactionCommandMessage, + isDeliveredProviderTurn, isOrchestrationV2WorkActive, isProviderNativeSubagentThread, MessageId, @@ -1599,7 +1600,9 @@ function lastDeliveredRunForProviderThread( isHandoffSourceRun(run) && run.providerThreadId === providerThreadId && (run.status === "completed" || - projection.providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId)), + projection.providerTurns.some( + (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn), + )), ); } diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index e47e88eda09a0..8e35271ce5aa9 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -16,6 +16,7 @@ import { type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, isCompactionCommandMessage, + isDeliveredProviderTurn, parseGoalCommand, RunId, RunAttemptId, @@ -32,6 +33,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; import { @@ -173,7 +175,9 @@ const nativeSessionMissesKeptTurns = ( ): boolean => { const nativeId = providerThread.nativeThreadRef?.nativeId; if (nativeId === undefined) return false; - const acceptedAttemptIds = new Set(projection.providerTurns.map((turn) => turn.runAttemptId)); + const acceptedAttemptIds = new Set( + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); const accepted = projection.attempts.filter((attempt) => acceptedAttemptIds.has(attempt.id)); const runsById = new Map(projection.runs.map((source) => [source.id, source])); const ordinalOf = (attempt: OrchestrationV2RunAttempt) => @@ -1087,7 +1091,12 @@ export const layer: Layer.Layer< ...settledHandoffs.flatMap((handoff) => handoff.delivery?.omittedItemIds ?? []), ]); const deliveredAttemptIds = new Set( - projection.providerTurns.map((turn) => turn.runAttemptId), + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); + const droppedAttemptIds = new Set( + projection.providerTurns + .filter((turn) => !isDeliveredProviderTurn(turn)) + .map((turn) => turn.runAttemptId), ); const acceptedAttempts = projection.attempts.filter( (source) => @@ -1159,7 +1168,9 @@ export const layer: Layer.Layer< (source) => source.ordinal < run.ordinal && source.providerThreadId === providerThread.id && - (source.status === "failed" || source.status === "interrupted") && + (source.status === "failed" || + source.status === "interrupted" || + (source.status === "cancelled" && droppedAttemptIds.has(source.activeAttemptId))) && !deliveredAttemptIds.has(source.activeAttemptId), ); const missedRunIds = new Set(missedRuns.map((source) => source.id)); @@ -1536,7 +1547,9 @@ export const layer: Layer.Layer< const rejectedHistory = yield* Effect.gen(function* () { if (session.driver !== "codex") return false; const acceptedAttemptIds = new Set( - projection.providerTurns.map((turn) => turn.runAttemptId), + projection.providerTurns + .filter(isDeliveredProviderTurn) + .map((turn) => turn.runAttemptId), ); const previous = projection.runs.findLast( (source) => @@ -1605,7 +1618,9 @@ export const layer: Layer.Layer< // Dispatch prepares no import handoff for a session import: its history is in the native session. const importedNativeSession = projection.thread.historyOrigin === "v1_import" && - !projection.providerTurns.some((turn) => turn.providerThreadId === providerThread.id) && + !projection.providerTurns.some( + (turn) => turn.providerThreadId === providerThread.id && isDeliveredProviderTurn(turn), + ) && !projection.contextHandoffs.some( (handoff) => handoff.toProviderThreadId === providerThread.id && @@ -2025,6 +2040,10 @@ export const layer: Layer.Layer< ], }); }); + let inlineDeliveredHandoffs: ReadonlyArray = []; + let promptDroppedOnTerminal = false; + const inlineDeliveryLock = yield* Semaphore.make(1); + const retryHandoffIds = new Set(retryHandoff.handoffs.map((handoff) => handoff.id)); const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")( function* (turnInput: Parameters[0], compact = false) { const delivery = yield* deliverContextHandoffs({ @@ -2051,6 +2070,15 @@ export const layer: Layer.Layer< sideChatHandoff === undefined || compact || goalCommand ? "" : sideChatHandoff.summaryText; + // Record inline handoffs before startTurn so an immediate dropped terminal can restore them. + inlineDeliveredHandoffs = [ + ...delivery.inlineHandoffs.map((handoff) => + retryHandoffIds.has(handoff.id) + ? { ...handoff, status: "superseded" as const } + : handoff, + ), + ...(sideChatContext === "" || sideChatHandoff === undefined ? [] : [sideChatHandoff]), + ]; const context = [delivery.context, sideChatContext, restartNote] .filter((part) => part !== "") .join("\n\n"); @@ -2101,31 +2129,39 @@ export const layer: Layer.Layer< : Effect.void, ), ); - // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. - const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId; - yield* Effect.forEach( - [ - delivery.delivered, - ...(sideChatContext === "" || sideChatHandoff === undefined || nativeThreadId == null - ? [] - : [ - persistHandoff({ - ...sideChatHandoff, - toProviderThreadId: runningProviderThread.id, - delivery: { nativeThreadId, status: "inline" as const, itemIds: [] }, - }), - ]), - ], - (record) => - record.pipe( - Effect.catchCause(() => - Effect.logWarning("Failed to record accepted context handoff delivery", { - runId: run.id, - deliveryStatus: "pending", - }), - ), - ), - { discard: true }, + // Serialize acceptance writes against dropped-terminal restoration so neither overwrites the other. + yield* inlineDeliveryLock.withPermits(1)( + Effect.gen(function* () { + if (promptDroppedOnTerminal) return; + // After provider acceptance, failed delivery bookkeeping must not stop live ingestion. + const nativeThreadId = runningProviderThread.nativeThreadRef?.nativeId; + yield* Effect.forEach( + [ + delivery.delivered, + ...(sideChatContext === "" || + sideChatHandoff === undefined || + nativeThreadId == null + ? [] + : [ + persistHandoff({ + ...sideChatHandoff, + toProviderThreadId: runningProviderThread.id, + delivery: { nativeThreadId, status: "inline" as const, itemIds: [] }, + }), + ]), + ], + (record) => + record.pipe( + Effect.catchCause(() => + Effect.logWarning("Failed to record accepted context handoff delivery", { + runId: run.id, + deliveryStatus: "pending", + }), + ), + ), + { discard: true }, + ); + }), ); }, Effect.mapError((cause) => @@ -2186,6 +2222,13 @@ export const layer: Layer.Layer< hasUnpairedRunInterruptRequest: runControls.hasUnpairedRunInterruptRequest, loadRunInterruptReason: runControls.loadRunInterruptReason, hasWorkspaceMoved: runControls.hasWorkspaceMoved, + loadDroppedInlineHandoffs: () => + inlineDeliveryLock.withPermits(1)( + Effect.sync(() => { + promptDroppedOnTerminal = true; + return inlineDeliveredHandoffs; + }), + ), loadUnsettledWork: runControls.loadUnsettledWork, message: { messageId: message.id, diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index ceaf2fd5de54b..58918bdef612d 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -1,14 +1,15 @@ -import type { - NodeId, - OrchestrationV2ConversationMessage, - OrchestrationV2PendingBackgroundTask, - OrchestrationV2ProviderThread, - OrchestrationV2ProviderTurn, - OrchestrationV2RestartCancelledBackgroundWork, - OrchestrationV2Run, - OrchestrationV2RunAttempt, - OrchestrationV2Subagent, - OrchestrationV2TurnItem, +import { + isDeliveredProviderTurn, + type NodeId, + type OrchestrationV2ConversationMessage, + type OrchestrationV2PendingBackgroundTask, + type OrchestrationV2ProviderThread, + type OrchestrationV2ProviderTurn, + type OrchestrationV2RestartCancelledBackgroundWork, + type OrchestrationV2Run, + type OrchestrationV2RunAttempt, + type OrchestrationV2Subagent, + type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; @@ -151,7 +152,7 @@ export function restartCancelledBackgroundWorkNote( type ProviderTurnState = Pick< OrchestrationV2ProviderTurn, - "runAttemptId" | "providerThreadId" | "status" + "runAttemptId" | "providerThreadId" | "status" | "promptDropped" >; export function isRestartNoteSource( @@ -307,12 +308,14 @@ export function delegatedTaskResultRun( /** The provider never accepted this continuation's prompt, so starting it again repeats nothing. */ export function continuationFailedBeforePrompt( run: Pick, - providerTurns: ReadonlyArray>, + providerTurns: ReadonlyArray>, ): boolean { return ( run.status === "failed" && run.restartContinuationOfRunId !== undefined && - !providerTurns.some((turn) => turn.runAttemptId === run.activeAttemptId) + !providerTurns.some( + (turn) => turn.runAttemptId === run.activeAttemptId && isDeliveredProviderTurn(turn), + ) ); } @@ -323,7 +326,9 @@ export function continuationStartRetryDelayMs( run: OrchestrationV2Run, projection: { readonly runs: ReadonlyArray; - readonly providerTurns: ReadonlyArray>; + readonly providerTurns: ReadonlyArray< + Pick + >; readonly turnItems: Parameters[1]; }, ): number | undefined { diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index a23a3fdf87bff..1d13620b75623 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -8,6 +8,7 @@ import { NodeId, type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, + type OrchestrationV2ContextHandoff, type OrchestrationV2DomainEvent, type OrchestrationV2ExecutionNode, type OrchestrationV2PendingBackgroundTask, @@ -3702,6 +3703,49 @@ it.effect.each([ }), ); +it.effect("restores dropped inline handoffs when ingestion fails before the terminal", () => + Effect.gen(function* () { + const key = "dropped-turn-ingest-error"; + const ids = backgroundScenarioIds(key); + const handoff = { id: `handoff:${key}` } as unknown as OrchestrationV2ContextHandoff; + const { finalEvents } = yield* captureRootRunTermination({ + key, + shouldFinalizeRun: () => Effect.succeed(true), + loadDroppedInlineHandoffs: () => Effect.succeed([handoff]), + events: () => + Stream.make({ + type: "provider_turn.updated" as const, + driver, + threadId: ids.threadId, + providerTurn: { + id: ids.rootProviderTurnId, + providerThreadId: ids.providerThreadId, + runAttemptId: ids.attemptId, + ordinal: 1, + status: "failed", + promptDropped: true, + } as OrchestrationV2ProviderTurn, + }), + ingestNormalized: ({ event }) => + event.type === "provider_turn.updated" + ? Effect.fail( + new ProviderEventIngestor.ProviderEventPublishError({ + providerSessionId: ProviderSessionId.make(`session:${key}`), + eventCount: 1, + cause: new Error("SQLITE_FULL: database or disk is full"), + }), + ) + : Effect.succeed([]), + }); + assert.deepEqual( + finalEvents.flatMap((event) => + event.type === "context-handoff.updated" ? [event.payload.id] : [], + ), + [handoff.id], + ); + }), +); + it.effect("does not interrupt a provider when ingestion fails before the root turn is known", () => Effect.gen(function* () { const interrupts = yield* Ref.make(0); @@ -3989,6 +4033,7 @@ function captureRootRunTermination(input: { readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly hasWorkspaceMoved?: () => Effect.Effect; readonly loadRunInterruptReason?: () => Effect.Effect; + readonly loadDroppedInlineHandoffs?: RunExecutionService.RunExecutionServiceV2StartRootRunInput["loadDroppedInlineHandoffs"]; readonly hasPendingBackgroundWorkForThread?: ProviderAdapter.ProviderAdapterV2SessionRuntime["hasPendingBackgroundWorkForThread"]; readonly seedOpenSubagent?: boolean; readonly events?: ( @@ -4235,6 +4280,9 @@ function captureRootRunTermination(input: { ...(input.hasWorkspaceMoved === undefined ? {} : { hasWorkspaceMoved: input.hasWorkspaceMoved }), + ...(input.loadDroppedInlineHandoffs === undefined + ? {} + : { loadDroppedInlineHandoffs: input.loadDroppedInlineHandoffs }), message: { messageId: MessageId.make(`message:${input.key}`), text: input.messageText ?? "interrupt projection", diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 1bc83f639d5ae..34cc31f98fa09 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -9,6 +9,7 @@ import { type NodeId, type OrchestrationV2AppThread, type OrchestrationV2CheckpointScope, + type OrchestrationV2ContextHandoff, type OrchestrationV2DomainEvent, type OrchestrationV2ExecutionNode, type OrchestrationV2ProviderFailure, @@ -658,6 +659,11 @@ export interface RunExecutionServiceV2StartRootRunInput { readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect; readonly loadRunInterruptReason?: () => Effect.Effect; readonly hasWorkspaceMoved?: () => Effect.Effect; + /** Restores inline context handoffs if the provider drops this turn's prompt before persisting it. */ + readonly loadDroppedInlineHandoffs?: () => Effect.Effect< + ReadonlyArray, + never + >; /** * Stored rows of a thread's unsettled work. Work a dead runtime left is ended from these, since * Stop may have settled it after the snapshots this run holds. @@ -736,6 +742,7 @@ export const layer: Layer.Layer< readonly abandonedProviderTurn?: OrchestrationV2ProviderTurn; // Stored root tool calls still open when the provider runtime was lost; nothing else ends them. readonly lostToolCalls?: ReadonlyArray; + readonly restoredHandoffs?: ReadonlyArray; readonly terminal: ProviderTerminalEvent; readonly completedAt?: DateTime.Utc; readonly failureItemPersisted: boolean; @@ -752,24 +759,35 @@ export const layer: Layer.Layer< status: input.terminal.status, completedAt, }; + const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId }); + const buildRestoredHandoffEvents = () => + input.terminal.promptDropped === true && + input.restoredHandoffs !== undefined && + input.restoredHandoffs.length > 0 + ? Effect.forEach(input.restoredHandoffs, (handoff) => + Effect.map(allocateEventId(), (id) => ({ + id, + type: "context-handoff.updated" as const, + threadId: input.run.threadId, + runId: input.run.id, + providerInstanceId: input.run.providerInstanceId, + occurredAt: completedAt, + payload: { ...handoff, updatedAt: completedAt }, + })), + ) + : Effect.succeed([]); const shouldFinalizeRun = input.shouldFinalizeRun === undefined ? true : yield* input.shouldFinalizeRun(); if (!shouldFinalizeRun) { - if (input.terminal.status === "interrupted") { - const hasUnpairedRequest = - input.hasUnpairedRunInterruptRequest === undefined - ? false - : yield* input.hasUnpairedRunInterruptRequest(); - if (hasUnpairedRequest) { - const reason = - input.loadRunInterruptReason === undefined - ? undefined - : yield* input.loadRunInterruptReason(); - yield* eventSink.writeWithEffects({ - effects: [], - events: [ + const restoredHandoffEvents = yield* buildRestoredHandoffEvents(); + const unpairedInterruptEvents = + input.terminal.status === "interrupted" && + (input.hasUnpairedRunInterruptRequest === undefined + ? false + : yield* input.hasUnpairedRunInterruptRequest()) + ? [ { - id: yield* idAllocator.allocate.event({ threadId: input.run.threadId }), + id: yield* allocateEventId(), type: "turn-item.updated" as const, threadId: input.run.threadId, runId: input.run.id, @@ -781,18 +799,25 @@ export const layer: Layer.Layer< run: input.run, rootNode: input.rootNode, providerThread: input.providerThread, - reason, + reason: + input.loadRunInterruptReason === undefined + ? undefined + : yield* input.loadRunInterruptReason(), completedAt, }), }, - ], - }); - yield* input.refreshAfterTurn; - } + ] + : []; + const earlyEvents = [...unpairedInterruptEvents, ...restoredHandoffEvents]; + if (earlyEvents.length > 0) { + yield* eventSink.writeWithEffects({ + effects: [], + events: earlyEvents, + }); + yield* input.refreshAfterTurn; } return false; } - const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId }); const reason = input.terminal.status === "interrupted" ? ((input.loadRunInterruptReason === undefined @@ -839,6 +864,7 @@ export const layer: Layer.Layer< status: finalProviderThreadStatus(input.terminal.threadDisposition), updatedAt: completedAt, }; + const restoredHandoffEvents = yield* buildRestoredHandoffEvents(); const runEventId = yield* allocateEventId(); const nodeEventId = yield* allocateEventId(); const providerThreadEventId = yield* allocateEventId(); @@ -1005,6 +1031,7 @@ export const layer: Layer.Layer< occurredAt: completedAt, payload: finalizedProviderThread, }, + ...restoredHandoffEvents, ], } satisfies Parameters[0]; if (input.writeIfRunCurrent !== undefined) { @@ -1031,6 +1058,13 @@ export const layer: Layer.Layer< effects: finalization.effects, }); if (!result.committed) { + if (restoredHandoffEvents.length > 0) { + yield* eventSink.writeWithEffects({ + effects: [], + events: restoredHandoffEvents, + }); + yield* input.refreshAfterTurn; + } return false; } } else { @@ -1275,44 +1309,55 @@ export const layer: Layer.Layer< } const providerThread = yield* Ref.get(latestProviderThread); const openSubagents = yield* Ref.get(openRunOwnedSubagents); - const writeTerminal = (settledTerminal: ProviderTerminalEvent) => - writeFinalRunEvents({ - run: input.run, - rootNode: input.rootNode, - checkpointScope: input.checkpointScope, - providerThread, - attempt: input.attempt, - ...(input.shouldFinalizeRun === undefined - ? {} - : { - shouldFinalizeRun: input.shouldFinalizeRun, - // Stop may commit between the ownership read and this - // terminal write. Gate the events and checkpoint together. - writeIfRunCurrent: { - activeAttemptId: input.attempt.id, - expectedStatus: "running" as const, - unlessInterruptRequested: settledTerminal !== terminal, - }, - }), - ...(input.hasUnpairedRunInterruptRequest === undefined - ? {} - : { - hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest, - }), - ...(input.loadRunInterruptReason === undefined - ? {} - : { loadRunInterruptReason: input.loadRunInterruptReason }), - openRunOwnedSubagents: openSubagents, - openRunOwnedSubagentsTerminal: terminal, - ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }), - terminal: settledTerminal, - failureItemPersisted: settledTerminal.status === "failed", - refreshAfterTurn, - }).pipe( - Effect.mapError( - (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), + const writeTerminal = Effect.fnUntraced( + function* (settledTerminal: ProviderTerminalEvent) { + const restoredHandoffs = + settledTerminal.promptDropped === true && + input.loadDroppedInlineHandoffs !== undefined + ? yield* input.loadDroppedInlineHandoffs() + : undefined; + return yield* writeFinalRunEvents({ + run: input.run, + rootNode: input.rootNode, + checkpointScope: input.checkpointScope, + providerThread, + attempt: input.attempt, + ...(input.shouldFinalizeRun === undefined + ? {} + : { + shouldFinalizeRun: input.shouldFinalizeRun, + // Stop may commit between the ownership read and this + // terminal write. Gate the events and checkpoint together. + writeIfRunCurrent: { + activeAttemptId: input.attempt.id, + expectedStatus: "running" as const, + unlessInterruptRequested: settledTerminal !== terminal, + }, + }), + ...(input.hasUnpairedRunInterruptRequest === undefined + ? {} + : { + hasUnpairedRunInterruptRequest: input.hasUnpairedRunInterruptRequest, + }), + ...(input.loadRunInterruptReason === undefined + ? {} + : { loadRunInterruptReason: input.loadRunInterruptReason }), + openRunOwnedSubagents: openSubagents, + openRunOwnedSubagentsTerminal: terminal, + ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }), + ...(restoredHandoffs === undefined ? {} : { restoredHandoffs }), + terminal: settledTerminal, + failureItemPersisted: settledTerminal.status === "failed", + refreshAfterTurn, + }); + }, + (effect) => + effect.pipe( + Effect.mapError( + (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }), + ), ), - ); + ); // A workspace handoff detaches the session and stops the turn that asked // for it: the run completes, while its native subagents still settle // as interrupted. The completed write refuses in the same transaction @@ -2116,6 +2161,13 @@ export const layer: Layer.Layer< : null; const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal); const openSubagents = yield* Ref.get(openRunOwnedSubagents); + const droppedPrompt = + (yield* Ref.get(terminalEvent))?.promptDropped === true || + rootProviderTurn?.promptDropped === true; + const recoveredHandoffs = + droppedPrompt && input.loadDroppedInlineHandoffs !== undefined + ? yield* input.loadDroppedInlineHandoffs() + : undefined; const lostToolCalls = runtimeLost ? yield* loadLostRootToolCalls.pipe( Effect.catchCauseIf( @@ -2141,18 +2193,24 @@ export const layer: Layer.Layer< }, openRunOwnedSubagents: openSubagents, ...(abandonedProviderTurn === null ? {} : { abandonedProviderTurn }), + ...(recoveredHandoffs === undefined + ? {} + : { restoredHandoffs: recoveredHandoffs }), lostToolCalls, completedAt, - terminal: makeFailedTerminalEvent( - makeProviderFailure({ - cause: squashed, - message: - knownProviderFailureMessage(squashed) ?? - userFacingDatabaseErrorMessage(squashed), - class: "unknown", - }), - latestItemOrdinal + 1, - ), + terminal: { + ...makeFailedTerminalEvent( + makeProviderFailure({ + cause: squashed, + message: + knownProviderFailureMessage(squashed) ?? + userFacingDatabaseErrorMessage(squashed), + class: "unknown", + }), + latestItemOrdinal + 1, + ), + ...(droppedPrompt ? { promptDropped: true as const } : {}), + }, failureItemPersisted: false, refreshAfterTurn, }).pipe( diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index ee048c2100592..ddf9259622599 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -118,6 +118,7 @@ function makeTestAdapter(input: { readonly failure?: ReturnType; readonly rejectedNativeThreads?: Ref.Ref>; readonly failedRunOrdinals?: ReadonlySet; + readonly promptDroppedRunOrdinals?: ReadonlySet; readonly brokenRunOrdinals?: ReadonlySet; readonly interruptedRunOrdinals?: ReadonlySet; readonly cancelledRunOrdinals?: ReadonlySet; @@ -410,6 +411,9 @@ function makeTestAdapter(input: { status: terminalStatus, startedAt: eventTime, completedAt: eventTime, + ...(input.promptDroppedRunOrdinals?.has(turnInput.runOrdinal) + ? { promptDropped: true as const } + : {}), }, }, { @@ -462,6 +466,9 @@ function makeTestAdapter(input: { threadDisposition: input.brokenRunOrdinals?.has(turnInput.runOrdinal) ? "broken" : "reusable", + ...(input.promptDroppedRunOrdinals?.has(turnInput.runOrdinal) + ? { promptDropped: true as const } + : {}), }, ]; const reportedUsage = input.tokenUsageByRunOrdinal?.[turnInput.runOrdinal]; @@ -6400,4 +6407,166 @@ describe("orchestration v2 provider switching", () => { ); }), ); + + it.effect.each([ + "same-provider-retry", + "cancelled-dropped", + "switch-away-and-return", + "persisted-failure", + ] as const)("handles an inline context handoff after a failed returning turn (%s)", (variant) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(`dropped-handoff-${variant}`); + const capturedTurns = yield* Ref.make>([]); + const dropped = variant !== "persisted-failure"; + const cancelled = variant === "cancelled-dropped"; + const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ + makeTestAdapter({ + instanceId: CODEX_MODEL_SELECTION.instanceId, + driver: CODEX_DRIVER, + capabilities: CodexProviderCapabilitiesV2, + modelSelection: CODEX_MODEL_SELECTION, + responseByRunOrdinal: { + 1: "Morning Codex summary.", + 3: "", + 4: "Recovered Codex answer.", + 5: "Recovered Codex after round-trip.", + }, + capturedTurns, + ...(cancelled + ? { cancelledRunOrdinals: new Set([3]) } + : { failedRunOrdinals: new Set([3]) }), + ...(dropped ? { promptDroppedRunOrdinals: new Set([3]) } : {}), + }), + makeTestAdapter({ + instanceId: CLAUDE_MODEL_SELECTION.instanceId, + driver: CLAUDE_DRIVER, + capabilities: ClaudeProviderCapabilitiesV2, + modelSelection: CLAUDE_MODEL_SELECTION, + responseByRunOrdinal: { + 2: "Afternoon Claude shipped b63 live draft.", + 4: "Extra Claude turn after dropped handoff.", + }, + capturedTurns, + }), + ]); + + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const testThreadId = ThreadId.make(`thread:dropped-handoff:${variant}`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:dropped-handoff:${variant}:create`), + threadId: testThreadId, + projectId, + title: `Dropped handoff ${variant}`, + modelSelection: CODEX_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + let step = 0; + const send = (text: string, modelSelection: ModelSelection) => + Effect.gen(function* () { + step += 1; + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`command:dropped-handoff:${variant}:msg-${step}`), + threadId: testThreadId, + messageId: MessageId.make(`message:dropped-handoff:${variant}:${step}`), + text, + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* worker.drain(); + yield* waitForIdle(testThreadId); + yield* worker.drain(); + return yield* orchestrator.getThreadProjection(testThreadId); + }); + + // Run 1: establish native session on Codex. + yield* send("Morning task", CODEX_MODEL_SELECTION); + // Run 2: switch to Claude and do real work. + yield* send("Build live draft b63", CLAUDE_MODEL_SELECTION); + // Run 3: switch back to Codex (delta handoff covering run 2); fails. + const afterRun3 = yield* send("Resume after failure", CODEX_MODEL_SELECTION); + const run3 = afterRun3.runs.find((run) => run.ordinal === 3)!; + assert.equal(run3.status, cancelled ? "cancelled" : "failed"); + const run3Handoff = afterRun3.contextHandoffs.find( + (handoff) => handoff.targetRunId === run3.id, + ); + assert.isDefined(run3Handoff); + assert.deepEqual(run3Handoff?.coveredRunOrdinals, { from: 2, to: 2 }); + + if (dropped) { + assert.isUndefined( + run3Handoff?.delivery, + "dropping the failed prompt must clear inline handoff delivery", + ); + const run3Turn = afterRun3.providerTurns.find( + (turn) => turn.runAttemptId === run3.activeAttemptId, + ); + assert.equal(run3Turn?.promptDropped, true); + } else { + assert.equal(run3Handoff?.delivery?.status, "inline"); + } + + if (variant === "same-provider-retry" || variant === "cancelled-dropped") { + // Run 4: stay on Codex; must re-deliver run 2's handoff. + const afterRun4 = yield* send("Resume", CODEX_MODEL_SELECTION); + const turns = yield* Ref.get(capturedTurns); + const run4Turn = turns.at(-1)!; + assert.include(run4Turn.text, "Afternoon Claude shipped b63 live draft."); + assert.include(run4Turn.text, "Resume after failure"); + assert.include(run4Turn.text, "User message:\nResume"); + const updatedHandoff = afterRun4.contextHandoffs.find( + (handoff) => handoff.id === run3Handoff!.id, + ); + assert.equal(updatedHandoff?.delivery?.status, "inline"); + } else if (variant === "switch-away-and-return") { + // Run 4: bounce back to Claude, then Run 5: return to Codex. + yield* send("Continue on Claude", CLAUDE_MODEL_SELECTION); + const afterRun5 = yield* send("Back to Codex", CODEX_MODEL_SELECTION); + const run5 = afterRun5.runs.find((run) => run.ordinal === 5)!; + const run5Handoff = afterRun5.contextHandoffs.find( + (handoff) => handoff.targetRunId === run5.id, + ); + assert.isDefined(run5Handoff); + assert.deepEqual(run5Handoff?.coveredRunOrdinals, { from: 2, to: 4 }); + const run5Turn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.include(run5Turn.text, "Afternoon Claude shipped b63 live draft."); + assert.include(run5Turn.text, "Extra Claude turn after dropped handoff."); + } else { + // Control: run 3 persisted its prompt before failing, so run 4 must not re-send run 2. + yield* send("Resume", CODEX_MODEL_SELECTION); + const run4Turn = (yield* Ref.get(capturedTurns)).at(-1)!; + assert.notInclude(run4Turn.text, "Afternoon Claude shipped b63 live draft."); + } + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { + name: `dropped-handoff-${variant}`, + runtimePolicyOverride: { + cwd, + approvalPolicy: "never", + sandboxPolicy: { + type: "readOnly", + access: { type: "fullAccess" }, + networkAccess: false, + }, + }, + }, + layerRegistry, + ), + ), + ); + }), + ); }); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 2d5bc546d1800..8b05c12e17871 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1334,9 +1334,17 @@ export const OrchestrationV2ProviderTurn = Schema.Struct({ turnTokenUsage: Schema.optional(TurnTokenUsage), /** The model the provider reported running this turn's root agent, which can differ from the requested one. */ model: Schema.optional(TrimmedNonEmptyString), + /** True when the provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), }); export type OrchestrationV2ProviderTurn = typeof OrchestrationV2ProviderTurn.Type; +export function isDeliveredProviderTurn( + turn: Pick, +): boolean { + return turn.promptDropped !== true; +} + /** Codex goals can span multiple native turns within one attempt. */ export function latestProviderTurnForAttempt< Turn extends Pick, diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 18ebf74baa1c7..c0bf5156acb97 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -202,6 +202,8 @@ export const ProviderAdapterV2Event = Schema.Union([ failure: Schema.Null, reason: Schema.optional(Schema.String), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), }), Schema.Struct({ @@ -216,6 +218,8 @@ export const ProviderAdapterV2Event = Schema.Union([ retry: Schema.optional(OrchestrationV2ProviderRetry), retryStartedAt: Schema.optional(Schema.DateTimeUtc), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), /** Child turns outlive root failure and report their own terminals; otherwise open children settle. */ childTurnsContinue: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 5c0a1940d671c..dfa1ac4865269 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -756,6 +756,149 @@ describe("CursorAdapterV2", () => { ), ); + it.effect("marks failed turns as promptDropped only when Cursor did not checkpoint the run", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const workspace = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "cursor-v2-dropped-", + }); + const checkpointedRuns = new Set(); + let sendCalls = 0; + const instanceId = ProviderInstanceId.make("cursor"); + const threadId = ThreadId.make("cursor-dropped-thread"); + const modelSelection = { instanceId, model: "gemini-4-neon" }; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const adapter = yield* makeCursorAdapterV2({ + instanceId, + environment: { HOME: workspace }, + }).pipe( + Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { + assertComplete: Effect.void, + open: () => + Effect.succeed({ + agentId: "native-cursor-dropped", + listMessages: Effect.succeed([]), + close: Effect.void, + runCheckpointed: (runId) => + Effect.succeed(runId !== undefined && checkpointedRuns.has(runId)), + send: () => + Effect.sync(() => { + sendCalls += 1; + const runId = `native-cursor-run-${sendCalls}`; + return { + agentId: "native-cursor-dropped", + runId, + cancel: Effect.void, + wait: Effect.succeed({ + id: runId, + status: "error" as const, + error: { + message: + 'AI Model Not Found Invalid parameters for registry model: "gemini-4-neon"', + }, + }), + }; + }), + }), + textGenerate: () => Effect.die("unused"), + }), + Effect.provide(TestProviderHost.layer({ cwd: workspace })), + ); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("cursor-dropped-session"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const appThread = { + id: threadId, + projectId: ProjectId.make("cursor-dropped-project"), + createdBy: "user" as const, + creationSource: "web" as const, + title: "Cursor dropped prompt", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + branch: null, + worktreePath: null, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; + const runFailed = (ordinal: number) => + Effect.gen(function* () { + yield* runtime.startTurn({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + runId: RunId.make(`cursor-dropped-run-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`cursor-dropped-attempt-${ordinal}`), + rootNodeId: NodeId.make(`cursor-dropped-root-${ordinal}`), + appThread, + message: { + messageId: MessageId.make(`cursor-dropped-message-${ordinal}`), + createdBy: "user", + creationSource: "web", + text: "Resume", + attachments: [], + }, + }); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + const terminal = events.find((event) => event.type === "turn.terminal"); + const turn = events.findLast( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, + ); + return { + terminal: terminal?.type === "turn.terminal" ? terminal : undefined, + turn: turn?.type === "provider_turn.updated" ? turn.providerTurn : undefined, + }; + }); + + // Uncheckpointed failure: Cursor never persisted the prompt. + const uncheckpointed = yield* runFailed(1); + assert.equal(uncheckpointed.terminal?.status, "failed"); + assert.equal(uncheckpointed.terminal?.promptDropped, true); + assert.equal(uncheckpointed.turn?.promptDropped, true); + + // Checkpointed failure: Cursor kept the run's prompt in its store. + checkpointedRuns.add("native-cursor-run-2"); + const checkpointed = yield* runFailed(2); + assert.equal(checkpointed.terminal?.status, "failed"); + assert.isUndefined(checkpointed.terminal?.promptDropped); + assert.isUndefined(checkpointed.turn?.promptDropped); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), + ), + ), + ); + it.effect("sends T3 instructions to each Cursor conversation that lacks them", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 7aadadaf9ddd4..b4dd1033c2a9f 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -2510,6 +2510,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( readonly status: OrchestrationV2ProviderTurn["status"]; readonly completedAt: DateTime.Utc | null; readonly tokenUsage?: OrchestrationV2ProviderTurn["tokenUsage"]; + readonly promptDropped?: true; }): OrchestrationV2ProviderTurn => ({ id: input.context.providerTurnId, providerThreadId: input.context.input.providerThread.id, @@ -2525,6 +2526,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( startedAt: input.context.startedAt, completedAt: input.completedAt, ...(input.tokenUsage === undefined ? {} : { tokenUsage: input.tokenUsage }), + ...(input.promptDropped === true ? { promptDropped: true as const } : {}), ...(input.completedAt === null || input.context.usage === undefined ? {} : { @@ -2590,6 +2592,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }).pipe(Effect.as(undefined)), ), ); + // Cursor only keeps a run in conversation history once it saves its first checkpoint. + const promptDropped = + (input.status === "failed" || input.status === "cancelled") && + !input.context.compacted && + input.context.prompt !== undefined && + !(yield* ( + input.context.session.runCheckpointed?.(input.context.run.runId) ?? + Effect.succeed(false) + ).pipe(Effect.orElseSucceed(() => false))); yield* emitProviderEvent({ type: "provider_turn.updated", driver: CursorAgentSdk.CURSOR_PROVIDER, @@ -2597,6 +2608,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( context: input.context, status: input.status, completedAt, + ...(promptDropped ? { promptDropped: true as const } : {}), ...(contextUsage === undefined ? {} : { @@ -2633,6 +2645,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: input.failure ?? makeProviderFailure({ class: "provider_error" }), threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), } : { type: "turn.terminal", @@ -2643,6 +2656,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: null, threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), }, ); if (input.context.runtimeInstructions !== undefined) { diff --git a/packages/shared/src/orchestrationV2ManualContinuation.test.ts b/packages/shared/src/orchestrationV2ManualContinuation.test.ts index 137bf6cd8f205..e7670749f6c5a 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.test.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.test.ts @@ -108,4 +108,16 @@ describe("unsentManualContinuationSource", () => { unsentManualContinuationSource(run("c", "a" as RunId), projection([a, b], [], [])), ).toBeUndefined(); }); + + it("treats a turn with promptDropped as unsent", () => { + const source = run("src"); + const a1 = attempt("a1", "src", 1); + const dropped = { ...turn("a1"), promptDropped: true as const }; + expect( + unsentManualContinuationSource( + run("r2", "src" as RunId), + projection([source], [a1], [dropped]), + ), + ).toBe(source); + }); }); diff --git a/packages/shared/src/orchestrationV2ManualContinuation.ts b/packages/shared/src/orchestrationV2ManualContinuation.ts index 3fb6c8d5a1866..ad64b63483e14 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.ts @@ -1,4 +1,8 @@ -import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { + isDeliveredProviderTurn, + type OrchestrationV2Run, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; export function unsentManualContinuationSource( run: Pick | undefined, @@ -7,7 +11,9 @@ export function unsentManualContinuationSource( let sourceId = run?.manualContinuationOfRunId; if (sourceId === undefined) return undefined; const runs = new Map(projection.runs.map((source) => [source.id, source])); - const acceptedAttempts = new Set(projection.providerTurns.map((turn) => turn.runAttemptId)); + const acceptedAttempts = new Set( + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); const latestAttempt = ( runId: OrchestrationV2Run["id"], matches: (attempt: (typeof projection.attempts)[number]) => boolean, From 0fb6ac6e65cced6201247705b304170010e37a78 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 21:47:07 -0800 Subject: [PATCH 004/162] perf(web): Markdown renders with Words as static islands under one shared tooltip; remark leaves the web app (#27866) Co-authored-by: Claude Opus 5.5 Co-authored-by: Yash Singh Co-authored-by: Cursor Co-authored-by: Gemini 4 Neon Co-authored-by: Noah Sigel --- .pnpmfile.cjs | 26 +- .../pull-requests/PullRequestDescription.tsx | 4 +- .../pull-requests/PullRequestMarkdown.tsx | 8 +- .../pullRequestAutolinks.test.ts | 2 +- .../pullRequestDescriptionContent.test.ts | 4 +- .../usePullRequestDescription.ts | 2 +- apps/mobile/src/lib/composerContext.test.ts | 13 +- apps/mobile/src/lib/composerContext.ts | 10 +- .../src/native/T3ComposerEditor.ios.tsx | 4 +- .../src/native/T3ComposerEditor.native.tsx | 4 +- apps/web/deps/README.md | 15 + .../deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz | Bin 0 -> 219310 bytes apps/web/package.json | 13 +- .../components/ChatMarkdown.browser.test.tsx | 99 +- apps/web/src/components/ChatMarkdown.tsx | 495 ++++--- .../chat/ChatMarkdownMedia.browser.test.tsx | 13 +- .../chat/MarkdownCodeBlock.logic.ts | 10 +- .../src/components/chat/MarkdownCodeBlock.tsx | 122 +- .../src/components/chat/MarkdownDetails.tsx | 39 + .../src/components/chat/MarkdownFileLink.tsx | 135 +- .../chat/MarkdownMath.browser.test.tsx | 36 - apps/web/src/components/chat/MarkdownMath.tsx | 81 -- .../components/chat/MathTypeset.logic.test.ts | 30 - .../src/components/chat/MathTypeset.logic.ts | 39 - apps/web/src/components/chat/MathTypeset.tsx | 49 - .../chat/MessagesTimeline.browser.test.tsx | 64 +- .../components/chat/MessagesTimeline.logic.ts | 2 +- .../components/chat/TimelineAssistantRows.tsx | 2 +- .../chat/TimelineUserMessageRow.tsx | 12 +- .../chat/TimelineWorkEntryRow.logic.ts | 74 +- .../components/chat/TimelineWorkEntryRow.tsx | 8 +- .../components/chat/TimelineWorkGroupRows.tsx | 10 +- .../components/chat/markdownIslands.test.ts | 50 + .../src/components/chat/markdownIslands.ts | 214 +++ .../components/chat/markdownRenderer.test.tsx | 85 +- .../src/components/chat/markdownRenderer.ts | 76 +- ....test.tsx => markdownStreamBlocks.test.ts} | 33 +- .../components/chat/markdownSyntaxGates.ts | 204 --- .../components/chat/markdownTextDirection.ts | 33 +- .../components/chat/threadFindHighlights.ts | 2 +- .../components/chat/timelineMinimapItems.ts | 64 +- .../src/components/files/FilePreviewPanel.tsx | 2 +- .../src/components/files/NotebookPreview.tsx | 23 +- .../pullRequest/PullRequestDetailPanel.tsx | 4 +- .../PullRequestMarkdown.browser.test.tsx | 2 +- .../pullRequest/PullRequestMarkdown.tsx | 6 +- .../pullRequest/PullRequestSummaryTab.tsx | 2 +- .../pullRequestDetail.logic.test.ts | 9 + .../pullRequest/pullRequestDetail.logic.ts | 31 +- .../pullRequestMarkdown.logic.test.ts | 86 +- .../pullRequest/pullRequestMarkdown.logic.ts | 154 +- .../src/components/settings/settingsSearch.ts | 1 + apps/web/src/components/ui/shared-tooltip.tsx | 262 ++++ .../components/ui/tooltip.browser.test.tsx | 131 +- apps/web/src/components/ui/tooltip.tsx | 28 +- apps/web/src/composer-editor-mentions.ts | 5 +- apps/web/src/composer-rich-text-doc.ts | 3 +- apps/web/src/i18n/translations/de.json | 5 - apps/web/src/i18n/translations/en.json | 5 - apps/web/src/i18n/translations/es.json | 5 - apps/web/src/i18n/translations/fr.json | 5 - apps/web/src/i18n/translations/ja.json | 5 - apps/web/src/i18n/translations/ko.json | 5 - apps/web/src/i18n/translations/pt-BR.json | 5 - apps/web/src/i18n/translations/ru.json | 5 - apps/web/src/i18n/translations/sv.json | 5 - apps/web/src/i18n/translations/zh.json | 5 - apps/web/src/index.css | 13 +- apps/web/src/markdown-clipboard.test.ts | 128 +- apps/web/src/markdown-clipboard.ts | 4 +- apps/web/src/markdown-incremental.test.tsx | 135 -- apps/web/src/markdown-incremental.ts | 98 -- apps/web/src/markdown-links.ts | 39 + apps/web/src/markdown/markdownText.ts | 68 + apps/web/src/markdown/wordsHast.test.ts | 403 +++++ apps/web/src/markdown/wordsHast.ts | 1296 +++++++++++++++++ packages/client-runtime/package.json | 12 +- .../src/pullRequestMarkdown.test.ts | 80 +- .../client-runtime/src/pullRequestMarkdown.ts | 71 +- .../src/pullRequestReferences.ts | 30 + packages/shared/package.json | 19 + packages/shared/src/assistantInsights.ts | 3 + packages/shared/src/codexArtifactTemplates.ts | 26 + .../shared/src/codexMarkdownDirectives.ts | 26 - .../shared/src/composerInlineTokens.test.ts | 18 +- packages/shared/src/composerInlineTokens.ts | 15 +- .../shared/src/markdownGithubAlerts.test.ts | 19 +- packages/shared/src/markdownHast.ts | 211 +++ packages/shared/src/markdownLinks.ts | 3 + .../src/markdownListIndentation.test.ts | 23 +- packages/shared/src/markdownPipeline.ts | 212 +-- packages/shared/src/markdownTaskEdits.ts | 28 + packages/shared/src/markdownTaskList.test.ts | 3 +- packages/shared/src/markdownTaskList.ts | 31 +- packages/shared/src/markdownWindowsPaths.ts | 4 +- packages/shared/src/textDirection.ts | 4 +- packages/shared/src/threadFindBlockTags.ts | 38 + packages/shared/src/threadFindText.ts | 47 +- pnpm-lock.yaml | 109 +- scripts/check-changed.ts | 3 +- scripts/release-smoke.ts | 11 +- 101 files changed, 3959 insertions(+), 2256 deletions(-) create mode 100644 apps/web/deps/README.md create mode 100644 apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz delete mode 100644 apps/web/src/components/chat/MarkdownMath.browser.test.tsx delete mode 100644 apps/web/src/components/chat/MarkdownMath.tsx delete mode 100644 apps/web/src/components/chat/MathTypeset.logic.test.ts delete mode 100644 apps/web/src/components/chat/MathTypeset.logic.ts delete mode 100644 apps/web/src/components/chat/MathTypeset.tsx create mode 100644 apps/web/src/components/chat/markdownIslands.test.ts create mode 100644 apps/web/src/components/chat/markdownIslands.ts rename apps/web/src/components/chat/{markdownStreamBlocks.test.tsx => markdownStreamBlocks.test.ts} (81%) delete mode 100644 apps/web/src/components/chat/markdownSyntaxGates.ts create mode 100644 apps/web/src/components/ui/shared-tooltip.tsx delete mode 100644 apps/web/src/markdown-incremental.test.tsx delete mode 100644 apps/web/src/markdown-incremental.ts create mode 100644 apps/web/src/markdown/markdownText.ts create mode 100644 apps/web/src/markdown/wordsHast.test.ts create mode 100644 apps/web/src/markdown/wordsHast.ts create mode 100644 packages/client-runtime/src/pullRequestReferences.ts create mode 100644 packages/shared/src/assistantInsights.ts rename apps/web/src/markdownGithubAlerts.test.tsx => packages/shared/src/markdownGithubAlerts.test.ts (70%) create mode 100644 packages/shared/src/markdownHast.ts rename apps/web/src/markdownListIndentation.test.tsx => packages/shared/src/markdownListIndentation.test.ts (72%) create mode 100644 packages/shared/src/markdownTaskEdits.ts create mode 100644 packages/shared/src/threadFindBlockTags.ts diff --git a/.pnpmfile.cjs b/.pnpmfile.cjs index 87a153f7b030d..8e79fceda4142 100644 --- a/.pnpmfile.cjs +++ b/.pnpmfile.cjs @@ -1,16 +1,22 @@ const fs = require("node:fs"); const path = require("node:path"); -// Our forks ship as tarballs in apps/mobile/deps. A pnpm patch on one is a second source of -// truth that the next tarball silently drops, so changes go to the fork (apps/mobile/deps/README.md). +// Our forks ship as tarballs in apps/mobile/deps and apps/web/deps. A pnpm patch on one is a +// second source of truth that the next tarball silently drops, so changes go to the fork (see +// the README beside each tarball). +const FORK_APPS = ["apps/mobile", "apps/web"]; + function forkTarballPatches(patchedDependencies) { - const manifestPath = path.join(__dirname, "apps/mobile/package.json"); - // Release staging installs a partial workspace without the mobile app. - if (!patchedDependencies || !fs.existsSync(manifestPath)) return []; - const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); - const forks = Object.keys(dependencies).filter((name) => - String(dependencies[name]).startsWith("file:deps/"), - ); + if (!patchedDependencies) return []; + const forks = FORK_APPS.flatMap((app) => { + const manifestPath = path.join(__dirname, app, "package.json"); + // Release staging installs a partial workspace without every app. + if (!fs.existsSync(manifestPath)) return []; + const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + return Object.keys(dependencies).filter((name) => + String(dependencies[name]).startsWith("file:deps/"), + ); + }); return Object.keys(patchedDependencies).filter((key) => forks.some((name) => key === name || key.startsWith(`${name}@`)), ); @@ -23,7 +29,7 @@ module.exports = { if (forkPatches.length > 0) { throw new Error( `pnpm-workspace.yaml patches ${forkPatches.join(", ")}, which ships as a fork tarball in ` + - "apps/mobile/deps. Change the fork and replace the tarball instead (apps/mobile/deps/README.md).", + "an app's deps directory. Change the fork and replace the tarball instead (deps/README.md).", ); } // Windows installs need Linux x64 glibc binaries because WSL shares node_modules. diff --git a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx index 3251cb8773f03..f0604d6b4ceb6 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestDescription.tsx @@ -10,7 +10,7 @@ import { useContext, useMemo, useState, type ComponentProps, type ReactNode } fr import { Platform, Pressable, ScrollView, StyleSheet, View } from "react-native"; import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"; import { pullRequestImageSource } from "./pullRequestMediaSource"; -import { parseMarkdownDocument } from "../../lib/markdownDocument"; +import { markdownReferenceDefinitions, parseMarkdownDocument } from "../../lib/markdownDocument"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; @@ -44,7 +44,7 @@ export function PullRequestDescription(props: { const document = parseMarkdownDocument(props.markdown); const content = pullRequestDescriptionContent( document, - splitPullRequestBody(props.markdown), + splitPullRequestBody(props.markdown, markdownReferenceDefinitions), messages, ); return { diff --git a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx index 3654cfd87bb42..c1852a6ee2601 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMarkdown.tsx @@ -17,7 +17,7 @@ import { createContext, useContext, useMemo, useState } from "react"; import { changeRequestReferenceAutolinker, resolveChangeRequestMediaUrl, -} from "@t3tools/client-runtime/pull-request-markdown"; +} from "@t3tools/client-runtime/pull-request-references"; import { sourceControlClients, type ReferenceAutolink, @@ -28,6 +28,7 @@ import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { SelectableMarkdownText } from "../../native/SelectableMarkdownText"; import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; import { markdownImageSources } from "../../lib/markdownImageSources"; +import { markdownReferenceDefinitions } from "../../lib/markdownDocument"; import { FilePreviewGallery, useFilePreviewGallery } from "../../components/ui/FilePreviewGallery"; import { pullRequestImageSource } from "./pullRequestMediaSource"; import { @@ -124,7 +125,10 @@ export function PullRequestMarkdown(props: { }) { const mediaContext = useContext(PullRequestMediaContext); const changeRequestUrl = useContext(ChangeRequestUrlContext); - const segments = useMemo(() => splitPullRequestBody(props.markdown), [props.markdown]); + const segments = useMemo( + () => splitPullRequestBody(props.markdown, markdownReferenceDefinitions), + [props.markdown], + ); const [undoneTicks, setUndoneTicks] = useState(0); const gallery: FilePreviewItem[] = markdownImageSources( props.imageGroupMarkdown ?? props.markdown, diff --git a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts index 6500a79885a8d..7acb1640694f7 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestAutolinks.test.ts @@ -1,4 +1,4 @@ -import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown"; +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-references"; import { describe, expect, it } from "vite-plus/test"; import { nativePullRequestMarkdown } from "./pullRequestAutolinks"; diff --git a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts index 6d6a1bfe4b624..74e21d39018ee 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestDescriptionContent.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; -import type { MarkdownNode } from "../../lib/markdownDocument"; +import { markdownReferenceDefinitions, type MarkdownNode } from "../../lib/markdownDocument"; import { splitPullRequestBody } from "@t3tools/client-runtime/pull-request-markdown"; import { pullRequestDescriptionContent } from "./pullRequestDescriptionContent"; @@ -15,6 +15,7 @@ describe("PR attachments", () => { } as MarkdownNode; const media = splitPullRequestBody( `${uri}\n\nhttps://drop.example.com/demo.mp4\n\nhttps://github.com/user-attachments/assets/123-abc`, + markdownReferenceDefinitions, ); expect(pullRequestDescriptionContent(document, media).attachments).toEqual([ { uri, caption: "Screenshot", kind: "image" }, @@ -30,6 +31,7 @@ describe("PR attachments", () => { it("collects videos from a before/after table", () => { const media = splitPullRequestBody( "\n\n\n
BeforeAfter
\n\nhttps://drop.example.com/before.mp4\n\n\n\nhttps://drop.example.com/after.mp4\n\n
", + markdownReferenceDefinitions, ); expect( pullRequestDescriptionContent({ type: "root" } as MarkdownNode, media).attachments, diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts b/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts index 105f4a1095009..5758e6b2ee84a 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestDescription.ts @@ -8,7 +8,7 @@ import { } from "@t3tools/client-runtime/pull-request-editing"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { PullRequestDetail } from "@t3tools/contracts"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { AsyncResult } from "effect/reactivity"; import { useGT } from "gt-react-native"; import { useRef, useState } from "react"; diff --git a/apps/mobile/src/lib/composerContext.test.ts b/apps/mobile/src/lib/composerContext.test.ts index e2a5a015c61af..255666ebcf0b2 100644 --- a/apps/mobile/src/lib/composerContext.test.ts +++ b/apps/mobile/src/lib/composerContext.test.ts @@ -8,6 +8,7 @@ import { type ServerProviderSkill, } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, @@ -167,7 +168,7 @@ describe("mobile composer context", () => { const modelTokens = (text: string) => composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), new Set(), collectComposerModelTokens(text, known), ) @@ -256,7 +257,7 @@ describe("mobile composer context", () => { const skills = [babysit, disabled, agentOnly]; const tokens = composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(skills), ); expect(tokens.map((token) => token.source)).toEqual([ @@ -271,14 +272,14 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels([]), ).map((token) => token.type), ).toEqual(["mention", "context", "context", "citation", "citation"]); expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels([{ ...babysit, name: "HOME" }]), ) .filter((token) => token.type === "skill") @@ -292,7 +293,7 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(promoted), ) .filter((token) => token.type === "skill") @@ -301,7 +302,7 @@ describe("mobile composer context", () => { expect( composerContextEditorTokens( text, - collectComposerInlineTokens(text), + collectComposerInlineTokens(text, { findMath: markdownMathRanges }), composerSkillLabels(skills), ) .filter((token) => token.type === "skill") diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.ts index 754774c4f1306..219a61108fd51 100644 --- a/apps/mobile/src/lib/composerContext.ts +++ b/apps/mobile/src/lib/composerContext.ts @@ -40,6 +40,7 @@ import { composerMathRanges, type ComposerInlineToken, } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; const isMessageContext = Schema.is(OrchestrationMessageContext); const decodeMessageContext = Schema.decodeUnknownOption(OrchestrationMessageContext); @@ -73,7 +74,7 @@ export function composerMentionPath(source: string, context?: OrchestrationMessa const record = context?.records.find((entry) => entry.contextId === reference.contextId); return record?.kind === "mention" && "path" in record ? record.path : null; } - const token = collectComposerInlineTokens(`${source} `)[0]; + const token = collectComposerInlineTokens(`${source} `, { findMath: markdownMathRanges })[0]; return token?.type === "mention" && token.source === source ? token.value : null; } @@ -222,7 +223,12 @@ export function composerContextEditorTokens( !references.some((ref) => token.start < ref.end && token.end > ref.start) && !citations.some((ref) => token.start < ref.end && token.end > ref.start), ); - const taken = [...inlineTokens, ...references, ...citations, ...composerMathRanges(text)]; + const taken = [ + ...inlineTokens, + ...references, + ...citations, + ...composerMathRanges(text, markdownMathRanges), + ]; const models = modelTokens.filter( (mention) => !taken.some((range) => mention.start < range.end && mention.end > range.start), ); diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx index ef57536abe95f..7e8eba1d01b28 100644 --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx @@ -1,6 +1,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste"; import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext"; import { useComposerModelTokens } from "./useComposerModelTokens"; import { requireNativeView } from "expo"; @@ -169,11 +170,12 @@ export function ComposerEditor({ // an abandoned render from leaking a trailing token into the next one. const [confirmedTokens, setConfirmedTokens] = useState(() => ({ value: props.value, - tokens: collectComposerInlineTokens(props.value), + tokens: collectComposerInlineTokens(props.value, { findMath: markdownMathRanges }), })); let tokens = confirmedTokens.tokens; if (confirmedTokens.value !== props.value) { tokens = collectComposerInlineTokens(props.value, { + findMath: markdownMathRanges, preserveTrailingFrom: confirmedTokens.tokens, }); setConfirmedTokens({ value: props.value, tokens }); diff --git a/apps/mobile/src/native/T3ComposerEditor.native.tsx b/apps/mobile/src/native/T3ComposerEditor.native.tsx index 28f47c3b758ab..4a0f57e411020 100644 --- a/apps/mobile/src/native/T3ComposerEditor.native.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.native.tsx @@ -1,6 +1,7 @@ import { PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES } from "@t3tools/client-runtime/text-paste"; import { PROVIDER_SEND_TURN_MAX_INPUT_CHARS } from "@t3tools/contracts"; import { collectComposerInlineTokens } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "@t3tools/shared/markdownMath"; import { composerContextEditorTokens, composerSkillLabels } from "../lib/composerContext"; import { DEFAULT_COMPOSER_ENTER_BEHAVIOR } from "../lib/composerEnterBehavior"; import { useComposerModelTokens } from "./useComposerModelTokens"; @@ -156,11 +157,12 @@ export function ComposerEditor({ // an abandoned render from leaking a trailing token into the next one. const [confirmedTokens, setConfirmedTokens] = useState(() => ({ value: props.value, - tokens: collectComposerInlineTokens(props.value), + tokens: collectComposerInlineTokens(props.value, { findMath: markdownMathRanges }), })); let tokens = confirmedTokens.tokens; if (confirmedTokens.value !== props.value) { tokens = collectComposerInlineTokens(props.value, { + findMath: markdownMathRanges, preserveTrailingFrom: confirmedTokens.tokens, }); setConfirmedTokens({ value: props.value, tokens }); diff --git a/apps/web/deps/README.md b/apps/web/deps/README.md new file mode 100644 index 0000000000000..26750d308c195 --- /dev/null +++ b/apps/web/deps/README.md @@ -0,0 +1,15 @@ +The Words tarball comes from the [`fork/t3-words` branch](https://github.com/pingdotgg/pierre/tree/fork/t3-words) of our fork of [pierrecomputer/pierre](https://github.com/pierrecomputer/pierre). Its `t3-fork.json` records the source commit and the upstream base. The fork adds opt-in options, all off by default so default output stays byte-identical to upstream: + +- `singleTilde: false`: only `~~` strikes. +- `windowsPaths`: backslashes in Windows drive paths stay. +- `codeMeta`: code fence info after the language becomes `data-meta`. +- `sourcePositions`: `data-sourcepos` byte ranges on list items, links, images, code blocks, math and directives. +- `directives`: the named remark-directive text and leaf directives. +- `escapeHtml`: raw HTML renders as escaped text. +- `leadingWhitespace`: spaces typed at the start of paragraph lines show, in `data-leading-whitespace` spans. +- `texDelimiters`: with `math`, `\(…\)` and `\[…\]` are math, as T3's llm-math reads them. +- `autolinkBoundaries`: end ASCII bare URLs before CJK/Arabic punctuation and keep trailing `_`/`~` when not closing emphasis. + +To replace it, commit the change on `fork/t3-words`, bump `packages/words/package.json` to the next `0.2.2-t3.N` and update `t3-fork.json`'s `source`, then run `moon run words:build` (or `node scripts/build.ts && tsdown`) and `npm pack` in `packages/words`. Name the archive with the first eight characters of the source commit, such as `pierre-words-0.2.2-t3.4-7c04b7f1.tgz`, update the path in `apps/web/package.json`, and run `vp i`. + +Change it through the fork, never with a pnpm patch: the next tarball would drop the patch without a trace. diff --git a/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz b/apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz new file mode 100644 index 0000000000000000000000000000000000000000..b6716f0395062eef7d2d14d830eafacc8c0d894f GIT binary patch literal 219310 zcmV(N<}{*YTC!9w$Y) zU6i*|U35l8@x`zCuiNb&?Cq(#@7->%+uh$+U+nH5bbGyngYKUCqTAcqIq0b`x?lVT z{}x3V=U;TYzrrND-LA6#{U7r0bR3s)dlu){?QPRh-`5OmwaXo6F4=T^*_ZWs(Z!O*mRVQ zbsOt_b=L9*gm174JNtUJ24Wa;(u>q&CsLE$NKN)4HQA5U!pYm|?)-x)vS~8jREi;L&yo+#BvnOzbrGr2 zBF}YNK7$gq)BTr7m3f>N^BBIi)~p|4NCv1;-okP`u7eVf90NE`iup9Y?bDf*bfvH2 zMVSrUBu3eE8qW*eSLUyQk6GQ$lRJ-OIf+y`Zi&U|tDaepJJ+JOzj`fTd^nuFdKk)y zJPO{yuT}=?BdcG=vt)YPSF&n}hX}=@F^f<#W%w zkjLX>Q9${sLoZ3^uer_@01ozZMmUQylVm*B=}M?3Iv(phM7_(Y{s7(lvM9>r^0qz7 z(o&~oU*S@>FLZgMp;K>l4szIQ1^~9AuX;Q45B?T0$mWvzj0M=KEWlk;x>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!XZIGnJh&>Lar^5NCcT|QDI?W z5dkvnMnh&yDl9A{MMEfHC5RyOBaC40x^ZR@p2E&EZlmfaYwW#5n1vfa^Ic8*-jeio@^ zYvfwCTCQd1MX}vlmXvE*lU&OnHu$DL^oI#@xLecpdO4o8(D$_&g9yptZX@H&?^e>9 zK2R^0Y}mMLOL$|y5niP@sgijm%}Tn<(v;leO2yGK;Z;ULwK85BdP2;zRZHuZ!u%3;OQl=(Ua_N$li5MkIc!j{Ua@ZL#)q0sned#iG$YD!W z5=I7lBRA9~w7zgcag_P!X@}OxdO2<+)cI&3RV}%p&Nh`yLmj4tZ5U3*a8z4%bB;bY1nUg_*wThBHv~UZc77KRCDnaQ6}jZ&r_R?B zJL=^ykEKyBCo~>Kb8#0QGF*~YtfZD%T&AYOO4c!!VBnQ*-RNKJor6k$CZ(<`>o`Wn zgQxr8b%%pY;iImXaTvOxB#xe=7B4l7c|X%9ErWY>OZvQ%5%YQYg~fGt*8B``v*u@k zgMewMQ;yB6$l;WwcGt^=U$pOW!yGue-_3?O;Pshj*D`SfBdt1Wz3f<7wa!6AJGNz> zC^rP_97Lqgyv0O(i^z5CO9aGxH%y=HbtR=G5^Bb6Pj0A7x-?~L=c@H`S!rph+>nEA z-9mS44RxmCq&#}e7#R+6%ji*$rA{|>en0wF*B^^qmfGDgisWAinHz$iOHmx{yh1q= z%C)FCj-_>F9o4Rv>l_Z1FVfwLQn{f{%a~aw%*orO_kThA4Rv;3GQ1$G(8Go3)@Xj}1m`Tw+YEjtKio1-m~3Kk>bbG}!>Bf>y%nx_)nqe*K^xzfz( xwYqImg?t*iHj+@gPJ`e`A_vv&Xh literal 0 HcmV?d00001 diff --git a/apps/web/package.json b/apps/web/package.json index 21ac8caba0b1e..a60eb801260cf 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -34,6 +34,7 @@ "@noble/hashes": "catalog:", "@pierre/diffs": "catalog:", "@pierre/trees": "1.0.0-beta.6", + "@pierre/words": "file:deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz", "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/provider-core": "workspace:*", @@ -74,24 +75,16 @@ "jszip": "3.10.1", "katex": "^0.18.2", "lucide-react": "^0.564.0", - "mdast-util-from-markdown": "^2.0.3", - "micromark-util-combine-extensions": "^2.0.1", "pdfjs-dist": "6.4.299", "pele": "catalog:", + "property-information": "^7.2.0", "react": "catalog:", "react-dom": "catalog:", - "react-markdown": "^10.1.0", - "remark-gfm": "catalog:", - "remark-math": "6.0.0", - "remark-parse": "catalog:", - "remark-rehype": "catalog:", "saxes": "6.0.0", "sql.js": "1.15.0", "tailwind-merge": "^3.4.0", "tiff": "7.1.3", - "unified": "catalog:", "use-sync-external-store": "^1.6.0", - "vfile": "^6.0.3", "zustand": "^5.0.11" }, "devDependencies": { @@ -103,7 +96,6 @@ "@types/compression": "^1.8.1", "@types/culori": "^4.0.1", "@types/hast": "^3.0.4", - "@types/mdast": "^4.0.4", "@types/react": "catalog:", "@types/react-dom": "catalog:", "@types/sql.js": "1.4.11", @@ -113,7 +105,6 @@ "@vitest/browser-playwright": "5.0.5", "compression": "^1.8.2", "gt": "2.27.0", - "micromark-util-types": "catalog:", "oxc-transform-react": "~0.152.0", "playwright": "1.64.1", "tailwindcss": "^4.0.0", diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index 0586a724b0c56..faca71b4a101f 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -2,7 +2,6 @@ import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/asset import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { type ReactElement } from "react"; -import remarkGfm from "remark-gfm"; import { describe, expect, it, vi } from "vite-plus/test"; import { commands, page, userEvent } from "vite-plus/test/browser"; @@ -15,11 +14,8 @@ import { selectActiveRightPanelSurface, useRightPanelStore, } from "../rightPanelStore"; -import { - CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -} from "@t3tools/shared/markdownPipeline"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import type { MarkdownExtensions } from "../markdown/wordsHast"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { HostImageUrlContext } from "./chat/hostImageUrl"; import { getSyntaxHighlighterPromise } from "~/lib/syntaxHighlighting"; @@ -28,14 +24,14 @@ const { workspaceSearch, filesystemMetadata } = vi.hoisted(() => ({ filesystemMetadata: vi.fn(), })); const parsedSources = vi.hoisted(() => [] as string[]); -vi.mock(import("mdast-util-from-markdown"), async (original) => { +vi.mock(import("../markdown/wordsHast"), async (original) => { const actual = await original(); return { ...actual, - fromMarkdown: ((source: string, ...rest: never[]) => { - parsedSources.push(String(source)); - return (actual.fromMarkdown as (...args: unknown[]) => unknown)(source, ...rest); - }) as typeof actual.fromMarkdown, + wordsHast: (source, options) => { + parsedSources.push(source); + return actual.wordsHast(source, options); + }, }; }); @@ -188,7 +184,7 @@ function buttonsLabelled(container: HTMLElement, label: string) { ); } -const SOURCE_NUMBER_PLUGINS = [remarkEnableOrderedListNumbers]; +const USER_MESSAGE = { userMessage: true }; it("keeps decimal markers in nested user lists while documents keep their counter styles", async () => { setup(); @@ -201,7 +197,7 @@ it("keeps decimal markers in nested user lists while documents keep their counte cwd={undefined} text={text} className="user-message-markdown" - extraRemarkPlugins={SOURCE_NUMBER_PLUGINS} + extensions={USER_MESSAGE} />

@@ -312,36 +308,24 @@ it("reuses the parse of a streaming reply's finished blocks when it remounts", a expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1); }); -it("reuses the parse of a remounted message that has stable extra plugins", async () => { +it("reuses the parse of a remounted message that has stable extensions", async () => { setup(); - const parsed = vi.fn(); - const countingPlugins = [() => () => void parsed()]; - const message = ( - - ); + const extensions = { userMessage: true }; + const message = ; { await using first = await render( - , + , ); await first.rerender(message); } await using screen = await render(message); await expect.element(screen.getByText("Cached text")).toBeVisible(); - expect(parsed).toHaveBeenCalledTimes(1); - const changed = vi.fn(); + const parses = () => parsedSources.filter((source) => source === "Cached text").length; + expect(parses()).toBe(1); await screen.rerender( - () => void changed()]} - />, + , ); - expect(changed).toHaveBeenCalledTimes(1); + expect(parses()).toBe(2); }); it("highlights a code block's own source when an earlier block of the same length was cached", async () => { @@ -399,6 +383,45 @@ describe("ChatMarkdown external link labels", () => { }); }); +describe("ChatMarkdown link tooltips", () => { + it("shows each link's address on one shared tooltip as the pointer moves between links", async () => { + setup(); + await using screen = await render( + , + ); + await userEvent.hover(screen.getByRole("link", { name: /First/ })); + await expect.element(page.getByText("https://example.com/a")).toBeVisible(); + await userEvent.hover(screen.getByRole("link", { name: /Second/ })); + await expect.element(page.getByText("https://example.org/b")).toBeVisible(); + expect(document.querySelectorAll('[data-slot="tooltip-popup"]')).toHaveLength(1); + }); +}); + +describe("ChatMarkdown details", () => { + it("opens collapsed details by click, and by keyboard without losing focus", async () => { + setup(); + await using screen = await render( + First\n\nHidden one\n\n\n\n
Second\n\nHidden two\n\n
" + } + />, + ); + await userEvent.click(screen.getByRole("button", { name: "First" })); + await expect.element(screen.getByText("Hidden one")).toBeVisible(); + await userEvent.tab(); + const second = screen.getByRole("button", { name: "Second" }); + await expect.element(second).toHaveFocus(); + await userEvent.keyboard("{Enter}"); + await expect.element(screen.getByText("Hidden two")).toBeVisible(); + await expect.element(screen.getByRole("button", { name: "Second" })).toHaveFocus(); + }); +}); + describe("ChatMarkdown streaming", () => { it("runs only a complete single-line shell block after a click", async () => { setup(); @@ -802,12 +825,12 @@ describe("ChatMarkdown copy", () => { "copies and selects user lines the same whether their typed indentation shows: $text", async (copy) => { setup(); - const copied = async (extraRemarkPlugins: typeof CHAT_USER_MARKDOWN_REMARK_PLUGINS) => { + const copied = async (extensions: MarkdownExtensions) => { await using screen = await renderText(copy.text, { className: "user-message-markdown", lineBreaks: true, parseRawHtml: false, - extraRemarkPlugins, + extensions, }); const range = document.createRange(); range.selectNodeContents(screen.container); @@ -824,9 +847,9 @@ describe("ChatMarkdown copy", () => { // A drag or anything else that reads the selection gets its text, not the copy payload. return { payload: chatMarkdownClipboardPayload(selection), selected: selection.toString() }; }; - const shown = await copied(CHAT_USER_MARKDOWN_REMARK_PLUGINS); + const shown = await copied({ userMessage: true, leadingWhitespace: true }); // The user pipeline as it was before typed indentation was shown. - expect(shown).toEqual(await copied([[remarkGfm, { singleTilde: false }]])); + expect(shown).toEqual(await copied({ userMessage: true })); }, ); @@ -885,7 +908,7 @@ describe("ChatMarkdown copy", () => { setup(); await using screen = await renderText( source, - userMessage ? { extraRemarkPlugins: SOURCE_NUMBER_PLUGINS } : {}, + userMessage ? { extensions: USER_MESSAGE } : {}, ); const itemText = (shown: string) => [...screen.container.querySelectorAll("li")] diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 8c0d14520871d..979d1858cafc1 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -13,7 +13,7 @@ import { extractMarkdownLinkHrefs, inlineCodeFilePathCandidate, } from "@t3tools/shared/markdownLinks"; -import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskList"; +import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskEdits"; import { isHostPath, resolveWorkspaceFilePath } from "@t3tools/shared/path"; import { usePullRequestLinking } from "~/hooks/usePullRequestLinking"; import { @@ -21,14 +21,7 @@ import { AuthOrchestrationOperateScope, SOURCE_CONTROL_MEDIA_ASSET, } from "@t3tools/contracts"; -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - CHAT_MARKDOWN_REHYPE_PLUGINS, - chatMarkdownImageSource, - decodeMarkdownLinkEscapes, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; +import { chatMarkdownImageSource } from "@t3tools/shared/markdownHast"; import { useAtomValue } from "@effect/atom-react"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, @@ -94,27 +87,17 @@ import React, { useState, type ReactNode, } from "react"; -import type { - Components, - ExtraProps as ReactMarkdownExtraProps, - Options as ReactMarkdownOptions, -} from "react-markdown"; -import { createIncrementalMarkdownPlugin } from "../markdown-incremental"; -import type { Pluggable, PluggableList } from "unified"; -import { defaultUrlTransform } from "react-markdown"; import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations"; import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences"; import { parseThreadLinkHref } from "@t3tools/shared/threadLinks"; import { AssistantCitationEmbed } from "./chat/AssistantCitationChip"; import { MarkdownThreadLink } from "./chat/MarkdownThreadLink"; -import { mathKind } from "@t3tools/shared/markdownMath"; -import remarkMath from "remark-math"; +import { artifactTemplateFromHastProperties } from "@t3tools/shared/codexArtifactTemplates"; import { - artifactTemplateFromHastProperties, + decodeMarkdownLinkEscapes, renderCodexInlineDirectivesAsMarkdown, -} from "@t3tools/shared/codexMarkdownDirectives"; +} from "../markdown/markdownText"; import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText"; -import { MarkdownMath } from "./chat/MarkdownMath"; import { resolveMarkdownMediaPreview, type ExpandedImagePreview, @@ -131,7 +114,7 @@ import { resolveExternalWebLinkHost, showExternalLinkContextMenu, } from "./chat/externalLinkContextMenu"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +import { SharedTooltipProvider, SharedTooltipTrigger } from "./ui/shared-tooltip"; import { Button } from "./ui/button"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { recordVisitForThread } from "../browserHistoryStore"; @@ -214,6 +197,15 @@ import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview"; import { IssueLinkPreview, IssueLinkPreviewFallback } from "./issue/IssueLinkPreview"; import { MarkdownCodeBlock, SuspenseShikiCodeBlock } from "./chat/MarkdownCodeBlock"; import { createMarkdownRenderer } from "./chat/markdownRenderer"; +import type { MarkdownExtensions, WordsHastOptions } from "../markdown/wordsHast"; +import { + type MarkdownIslandOptions, + renderHastWithIslands, + withProperties, +} from "./chat/markdownIslands"; +import type { Element as HastElement } from "hast"; +import { matchInlineSkills } from "@t3tools/shared/inlineSkills"; +import { collectComposerModelMentions } from "@t3tools/client-runtime/composer-model-mentions"; import { splitMarkdownBlocks } from "./chat/markdownStreamBlocks"; import { MarkdownMermaidCodeBlock } from "./chat/MarkdownMermaidCodeBlock"; import { MarkdownTable } from "./chat/MarkdownTable"; @@ -230,9 +222,7 @@ import { import { MarkdownExternalLinkContent } from "./chat/MarkdownExternalLink"; import { MarkdownFileLink } from "./chat/MarkdownFileLink"; import { canUseMarkdownFileShellActions } from "./chat/MarkdownFileLink.logic"; -import { rehypeChipPunctuation } from "./chat/markdownChipPunctuation"; -import { handleMarkdownFragmentClick, rehypeHeadingIds } from "./chat/markdownFragments"; -import { rehypeTextDirection } from "./chat/markdownTextDirection"; +import { handleMarkdownFragmentClick } from "./chat/markdownFragments"; import { hastHasText, hastPlainTextDeep, plainHastText } from "./chat/markdownHast.logic"; import { extractCodeBlock, @@ -268,8 +258,8 @@ interface ChatMarkdownProps { imageBaseDir?: string | undefined; workspaceMutationId?: string | null | undefined; onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined; - /** Keep one list per configuration (a module constant): it keys the shared parse cache. */ - extraRemarkPlugins?: NonNullable; + /** Keep one object per configuration (a module constant): it keys the shared parse cache. */ + extensions?: MarkdownExtensions | undefined; renderContextReference?: ((reference: ChatMarkdownContextReference) => ReactNode) | undefined; /** Loads media a source control host keeps behind a credential through the server, which holds `cwd`'s; without it a private repository's uploads load unauthenticated and 404. */ @@ -289,7 +279,7 @@ export interface ChatMarkdownContextReference { } const EMPTY_MARKDOWN_SKILLS: ReadonlyArray = []; -const EMPTY_REMARK_PLUGINS: NonNullable = []; +const NO_EXTENSIONS: MarkdownExtensions = {}; const ARTIFACT_TEMPLATE_ICON_BY_KIND = { document: FileTextIcon, @@ -423,19 +413,29 @@ function normalizeMarkdownLinkHrefKey(href: string): string { : rewrittenHref; } -// Heading ids are added after sanitizing, which would prefix them a second time. -const CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS = [ - ...CHAT_MARKDOWN_REHYPE_PLUGINS, - rehypeHeadingIds, - rehypeTextDirection, - rehypeChipPunctuation, -] satisfies NonNullable; +/** A component per element, with the hast node it renders, as react-markdown typed them. */ +type MarkdownComponents = { + [Tag in keyof React.JSX.IntrinsicElements]?: React.ComponentType< + React.JSX.IntrinsicElements[Tag] & { node?: HastElement | undefined } + >; +}; -const CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS = [ - rehypeHeadingIds, - rehypeTextDirection, - rehypeChipPunctuation, -] satisfies NonNullable; +// react-markdown's defaultUrlTransform: relative URLs, and absolute ones with a safe protocol. +const SAFE_PROTOCOL = /^(?:https?|ircs?|mailto|xmpp)$/i; +function safeUrl(value: string): string { + const colon = value.indexOf(":"); + const before = (character: string) => { + const at = value.indexOf(character); + return at !== -1 && colon > at; + }; + return colon === -1 || + before("/") || + before("?") || + before("#") || + SAFE_PROTOCOL.test(value.slice(0, colon)) + ? value + : ""; +} function markdownUrlTransform(href: string) { if (parseAssistantCitationHref(href)) return href; @@ -443,7 +443,7 @@ function markdownUrlTransform(href: string) { if (parseThreadLinkHref(href)) return href; if (isWindowsDrivePathHref(href)) return href; if (isLocalEditorFileHref(href)) return href; - return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href); + return rewriteMarkdownFileUriHref(href) ?? safeUrl(href); } const NO_MARKDOWN_EDITORS: ReadonlyArray = []; @@ -486,11 +486,16 @@ const markdownServerConfigFieldsAtom = Atom.family((environmentId: EnvironmentId }).pipe(Atom.withLabel("markdown-server-config-fields")), ); -function fileLinkSourcesKey( +interface BlockFileLinkSources { + readonly hrefs: ReadonlyArray; + readonly spans: ReadonlyArray; +} + +function blockFileLinkSources( text: string, cwd: string | undefined, imageBaseDir: string | undefined, -): string { +): BlockFileLinkSources { const hrefs = extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(text)) .filter((href) => !parseComposerContextHref(href)) .map(decodeMarkdownLinkEscapes) @@ -499,7 +504,47 @@ function fileLinkSourcesKey( const spans = extractInlineCodeSpans(text).filter((span) => resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd), ); - return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + return { hrefs, spans }; +} + +// Links and code spans never cross blocks: a streamed reply rescans only its open last block. +const MAX_CACHED_BLOCK_CHARS = 2_000_000; +const finishedBlockFileLinkSources = new Map(); +let cachedBlockChars = 0; + +function fileLinkSourcesKey( + text: string, + cwd: string | undefined, + imageBaseDir: string | undefined, + streamingBlocks: ReadonlyArray | null, +): string { + if (!streamingBlocks) { + const { hrefs, spans } = blockFileLinkSources(text, cwd, imageBaseDir); + return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + } + const config = `${cwd ?? ""}\u0000${imageBaseDir ?? ""}\u0000`; + const hrefs = new Set(); + const spans = new Set(); + const last = streamingBlocks.length - 1; + for (const [index, block] of streamingBlocks.entries()) { + // The last block still grows; caching each of its prefixes would only fill the cache. + const key = config + block; + let sources = index === last ? undefined : finishedBlockFileLinkSources.get(key); + if (!sources) { + sources = blockFileLinkSources(block, cwd, imageBaseDir); + if (index !== last) { + if (cachedBlockChars + key.length > MAX_CACHED_BLOCK_CHARS) { + finishedBlockFileLinkSources.clear(); + cachedBlockChars = 0; + } + finishedBlockFileLinkSources.set(key, sources); + cachedBlockChars += key.length; + } + } + for (const href of sources.hrefs) hrefs.add(href); + for (const span of sources.spans) spans.add(span); + } + return JSON.stringify([[...hrefs], [...spans]]); } function resolveFileLinkSources( @@ -525,27 +570,30 @@ function resolveFileLinkSources( return { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath }; } -function useChatMarkdownState({ - text, - inline = false, - cwd, - agentDirectories, - threadRef, - pullRequestPanelRef, - environmentId: explicitEnvironmentId, - onTaskListChange, - isStreaming = false, - skills = EMPTY_MARKDOWN_SKILLS, - onUseArtifactTemplate, - onRunShellCommand, - imageBaseDir, - workspaceMutationId, - onImageExpand, - renderContextReference, - headingLevelOffset = 0, - sourceControlMedia = false, - sourceControlMediaRepository, -}: ChatMarkdownProps) { +function useChatMarkdownState( + { + text, + inline = false, + cwd, + agentDirectories, + threadRef, + pullRequestPanelRef, + environmentId: explicitEnvironmentId, + onTaskListChange, + isStreaming = false, + skills = EMPTY_MARKDOWN_SKILLS, + onUseArtifactTemplate, + onRunShellCommand, + imageBaseDir, + workspaceMutationId, + onImageExpand, + renderContextReference, + headingLevelOffset = 0, + sourceControlMedia = false, + sourceControlMediaRepository, + }: ChatMarkdownProps, + streamingBlocks: ReadonlyArray | null, +) { const gt = useGT(); const messages = useMessages(); const resolvedTheme = useRenderedAppearance(); @@ -743,7 +791,7 @@ function useChatMarkdownState({ // Keyed by the file links found, not the text, so streamed text that adds none keeps the // renderer context, and every block reading it, unchanged. // A template literal marks the key as a string, so the compiler memoizes the maps on its value. - const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir)}`; + const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); const resolveThreadPullRequest = ( @@ -1087,7 +1135,7 @@ function markdownHeadingRenderer(level: 1 | 2 | 3 | 4 | 5 | 6) { return function MarkdownHeading({ node: _node, ...props - }: ComponentProps & ReactMarkdownExtraProps) { + }: ComponentProps & { node?: HastElement | undefined }) { const { headingLevelOffset } = use(ChatMarkdownRendererContext); return ( ; } - return ( - - - {href} - - ); + return ; } const label = nodeToPlainText(children); @@ -1533,18 +1576,9 @@ const CHAT_MARKDOWN_COMPONENTS = { ); }, code: function MarkdownCode({ node, children, className, ...props }) { - const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip, mathEnabled, inline } = - use(ChatMarkdownRendererContext); - const math = mathEnabled ? mathKind(className) : null; - if (math) { - return ( - - ); - } + const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip } = use( + ChatMarkdownRendererContext, + ); if (node?.properties?.dataInlineCode != null) { const codeText = nodeToPlainText(children); const fileLinkMeta = @@ -1769,15 +1803,9 @@ const CHAT_MARKDOWN_COMPONENTS = { }, pre: function MarkdownPre({ node, children, ...props }) { const gt = useGT(); - const { - resolvedTheme, - diffThemeName, - expandMedia, - isStreaming, - onRunShellCommand, - inline, - mathEnabled, - } = use(ChatMarkdownRendererContext); + const { resolvedTheme, diffThemeName, expandMedia, isStreaming, onRunShellCommand } = use( + ChatMarkdownRendererContext, + ); const text = use(ChatMarkdownTextContext); const codeBlock = extractCodeBlock(children); if (!codeBlock) { @@ -1785,15 +1813,6 @@ const CHAT_MARKDOWN_COMPONENTS = { } const language = extractFenceLanguage(codeBlock.className); - if ( - mathEnabled && - language === "math" && - (!isStreaming || - mathKind(codeBlock.className) === "display" || - isClosedCodeFence(node, text, codeBlock.code)) - ) { - return ; - } const fenceTitle = extractFenceTitle(extractPreCodeMeta(node)); const highlightedCode = ( ); }, -} satisfies Components; - -const REMARK_MATH: Pluggable = [remarkMath, { singleDollarTextMath: true }]; -// Shared lists, so every message with the same options shares a processor and its cache. -const CHAT_MARKDOWN_REMARK_PLUGIN_SETS = { - plain: CHAT_MARKDOWN_REMARK_PLUGINS, - breaks: CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - math: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS], - mathBreaks: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS], -} satisfies Record; - -const combinedPlugins = new WeakMap>(); +} satisfies MarkdownComponents; -// One combined list per pair, so a stable extra list shares a renderer and its parse cache. -const INSIGHT_REMARK_PLUGINS: PluggableList = [remarkAssistantInsights]; +const markdownOptions = new WeakMap>(); -function withExtraPlugins(shared: PluggableList, extra: PluggableList): PluggableList { - if (extra.length === 0) return shared; - let byShared = combinedPlugins.get(extra); - if (!byShared) combinedPlugins.set(extra, (byShared = new WeakMap())); - let combined = byShared.get(shared); - if (!combined) byShared.set(shared, (combined = [...shared, ...extra])); - return combined; +/** One options object per configuration, so equal messages share a renderer and its cache. */ +function wordsOptions( + extensions: MarkdownExtensions, + flags: Omit, +): WordsHastOptions { + let byFlags = markdownOptions.get(extensions); + if (!byFlags) markdownOptions.set(extensions, (byFlags = new Map())); + const key = `${+flags.math}${+flags.breaks}${+flags.escapeHtml}${+flags.insights}`; + let options = byFlags.get(key); + if (!options) byFlags.set(key, (options = { ...flags, extensions })); + return options; } const markdownRenderers = new WeakMap< - PluggableList, - WeakMap> + WordsHastOptions, + ReturnType >(); -function markdownRenderer(remarkPlugins: PluggableList, rehypePlugins: PluggableList) { - let byRehype = markdownRenderers.get(remarkPlugins); - if (!byRehype) markdownRenderers.set(remarkPlugins, (byRehype = new WeakMap())); - let renderer = byRehype.get(rehypePlugins); +function markdownRenderer(markdown: WordsHastOptions) { + let renderer = markdownRenderers.get(markdown); if (!renderer) { renderer = createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, + markdown, components: CHAT_MARKDOWN_COMPONENTS, urlTransform: markdownUrlTransform, }); - byRehype.set(rehypePlugins, renderer); + markdownRenderers.set(markdown, renderer); } return renderer; } +type ChatMarkdownComponentState = ReturnType["componentState"]; + +function hastClassName(node: HastElement): string | undefined { + const { className } = node.properties; + return Array.isArray(className) ? className.join(" ") : (className as string | undefined); +} + +// Paragraphs and list items turn skill and model mentions in their text into chips, except in +// code and links, as SkillInlineText does. +function hastTextHasChip(node: HastElement, skills: ReadonlyArray): boolean { + return node.children.some((child) => + child.type === "text" + ? (skills.length > 0 && !matchInlineSkills(child.value, skills).next().done) || + collectComposerModelMentions(child.value).length > 0 + : child.type === "element" && + child.tagName !== "code" && + child.tagName !== "a" && + hastTextHasChip(child, skills), + ); +} + +const HEADING_LEVELS: Record = { h1: 1, h2: 2, h3: 3, h4: 4, h5: 5, h6: 6 }; + +const markdownIslandOptionsByState = new WeakMap< + ChatMarkdownComponentState, + MarkdownIslandOptions +>(); + +/** Which elements need CHAT_MARKDOWN_COMPONENTS, and what the others' components add. */ +function markdownIslandOptions(state: ChatMarkdownComponentState): MarkdownIslandOptions { + const cached = markdownIslandOptionsByState.get(state); + if (cached) return cached; + const { + cwd, + headingLevelOffset, + imageBaseDir, + inlineCodeFileLinkMetaByText, + onTaskListChange, + skills, + } = state; + const options: MarkdownIslandOptions = { + components: CHAT_MARKDOWN_COMPONENTS, + variant: String(headingLevelOffset), + isIsland: (node) => { + switch (node.tagName) { + case "a": + case "img": + case "pre": + case "details": + case "table": + return true; + case "blockquote": + return GITHUB_ALERT_PRESENTATIONS[String(node.properties.dataAlert ?? "")] !== undefined; + case "div": + return artifactTemplateFromHastProperties(node.properties) !== null; + case "input": + return node.properties.type === "checkbox" && onTaskListChange !== undefined; + case "code": { + if (node.properties.dataInlineCode == null) return false; + const codeText = hastPlainTextDeep(node); + return ( + (inlineCodeFileLinkMetaByText.get(codeText.trim()) ?? + resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd)) != null + ); + } + case "p": + case "li": + return hastTextHasChip(node, skills); + default: + return false; + } + }, + staticElement: (node) => { + const level = HEADING_LEVELS[node.tagName]; + if (level !== undefined) { + return headingLevelOffset > 0 + ? withProperties(node, { ariaLevel: Math.min(level + headingLevelOffset, 6) }) + : node; + } + switch (node.tagName) { + case "ol": { + const itemValues = node.children.flatMap((child) => + child.type === "element" && child.tagName === "li" ? [child.properties.value] : [], + ); + const gutter = orderedListGutterStyle(itemValues, node.properties.start); + if (!gutter) return node; + const authored = typeof node.properties.style === "string" ? node.properties.style : ""; + return withProperties(node, { + style: `${authored}${authored ? ";" : ""}--list-gutter:${gutter["--list-gutter"]}`, + }); + } + case "li": + return hastClassName(node)?.includes("task-list-item") + ? withProperties(node, { dataListItemOffset: node.position?.start.offset }) + : node; + case "input": + return node.properties.type === "checkbox" + ? withProperties(node, { readOnly: true }) + : node; + default: + return node; + } + }, + }; + markdownIslandOptionsByState.set(state, options); + return options; +} + const MarkdownSource = memo(function MarkdownSource({ text, - remarkPlugins, - rehypePlugins, - shared, + markdown, cache, }: { text: string; - remarkPlugins: PluggableList; - rehypePlugins: PluggableList; - /** The plugins are one of the shared sets. */ - shared: boolean; + markdown: WordsHastOptions; /** The text will not change again; streamed text would only fill the cache with prefixes. */ cache: boolean; }) { - // Per-instance plugins, such as the incremental parser, set up their state on every render. - const render = shared - ? markdownRenderer(remarkPlugins, rehypePlugins) - : createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, - components: CHAT_MARKDOWN_COMPONENTS, - urlTransform: markdownUrlTransform, - }); - const element = render(text); + const render = markdownRenderer(markdown); + const entry = render.parse(text); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Caching during render would make React Compiler rebuild the element when `cache` flips. useEffect(() => { - if (shared && cache) render.remember(text, element); - }, [render, text, element, shared, cache]); - return {element}; + if (cache) render.remember(text, entry); + }, [render, text, entry, cache]); + const islandState = use(ChatMarkdownRendererContext); + return ( + + {islandState + ? renderHastWithIslands(entry.tree, markdownIslandOptions(islandState)) + : render.element(entry)} + + ); }); function ChatMarkdown({ @@ -1935,51 +2045,28 @@ function ChatMarkdown({ inline = false, lineBreaks = false, parseRawHtml = true, - extraRemarkPlugins = EMPTY_REMARK_PLUGINS, + extensions = NO_EXTENSIONS, renderInsights = false, ...props }: ChatMarkdownProps) { - const { componentState, handleCopy, markdownRef, localMediaPreview, closeLocalMediaPreview } = - useChatMarkdownState({ text, inline, ...props }); - const hasInsights = renderInsights && text.includes("★ Insight"); - // Streaming re-renders only the last block; offsets for task edits need the whole text. + // Streaming re-renders only the last block; offsets for task edits, and extensions that read + // the whole message, need the whole text. const streamingBlocks = - props.isStreaming === true && - !inline && - extraRemarkPlugins.length === 0 && - !props.onTaskListChange - ? splitMarkdownBlocks(text) + props.isStreaming === true && !inline && extensions === NO_EXTENSIONS && !props.onTaskListChange + ? (splitMarkdownBlocks(text) ?? [text]) : null; - const incrementalParsing = - props.isStreaming === true && - !hasInsights && - streamingBlocks === null && - extraRemarkPlugins.length === 0 && - /(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text); + const { componentState, handleCopy, markdownRef, localMediaPreview, closeLocalMediaPreview } = + useChatMarkdownState({ text, inline, ...props }, streamingBlocks); const Root = inline ? "span" : "div"; const bindMarkdownRef = (node: HTMLElement | null) => { markdownRef.current = node; }; - const sharedRemarkPlugins = - CHAT_MARKDOWN_REMARK_PLUGIN_SETS[ - componentState.mathEnabled - ? lineBreaks - ? "mathBreaks" - : "math" - : lineBreaks - ? "breaks" - : "plain" - ]; - // The incremental parser keeps per-instance state, so its output is not shared. - const uncachedPlugins = incrementalParsing; - const remarkPlugins = incrementalParsing - ? [...sharedRemarkPlugins, ...extraRemarkPlugins, createIncrementalMarkdownPlugin()] - : withExtraPlugins( - hasInsights - ? withExtraPlugins(INSIGHT_REMARK_PLUGINS, sharedRemarkPlugins) - : sharedRemarkPlugins, - extraRemarkPlugins, - ); + const markdown = wordsOptions(extensions, { + math: componentState.mathEnabled, + breaks: lineBreaks, + escapeHtml: !parseRawHtml, + insights: renderInsights && text.includes("★ Insight"), + }); const blocks = streamingBlocks ?? [text]; return ( @@ -1995,22 +2082,18 @@ function ChatMarkdown({ onCopy={handleCopy} > - {blocks.map((source, index) => ( - - ))} + + {blocks.map((source, index) => ( + + ))} + {localMediaPreview ? ( diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx index db46999708043..04a4d9fd76f84 100644 --- a/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx +++ b/apps/web/src/components/chat/ChatMarkdownMedia.browser.test.tsx @@ -1,7 +1,6 @@ import type { PreparedConnection } from "@t3tools/client-runtime/connection"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import { markdownTree } from "~/markdown/wordsHast"; import { describe, expect, it, vi } from "vite-plus/test"; import { render } from "../../../test/render"; @@ -91,9 +90,13 @@ describe("markdownImageCopy", () => { it("copies an image whose path has a space as Markdown that is still that image", () => { // Raw HTML and sources reach the copy with the space unencoded. const copied = markdownImageCopy("Shot", "/work/my shot.png", undefined); - const [block] = unified().use(remarkParse).parse(copied).children; + const [block] = markdownTree(copied).children; const images = - block?.type === "paragraph" ? block.children.filter((node) => node.type === "image") : []; - expect(images.map((image) => decodeURI(image.url))).toEqual(["/work/my shot.png"]); + block?.type === "element" && block.tagName === "p" + ? block.children.filter((node) => node.type === "element" && node.tagName === "img") + : []; + expect( + images.map((image) => image.type === "element" && decodeURI(String(image.properties.src))), + ).toEqual(["/work/my shot.png"]); }); }); diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts index fcee475c2886a..0a45cd6ac5659 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts +++ b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts @@ -1,5 +1,5 @@ import { Children, isValidElement, type ReactNode } from "react"; -import type { ExtraProps as ReactMarkdownExtraProps } from "react-markdown"; +import type { Element } from "hast"; import type { DiffThemeName } from "../../lib/diffRendering"; @@ -44,11 +44,7 @@ export function extractPreCodeMeta(node: unknown): string | undefined { return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined; } -export function isClosedCodeFence( - node: ReactMarkdownExtraProps["node"], - text: string, - code: string, -): boolean { +export function isClosedCodeFence(node: Element | undefined, text: string, code: string): boolean { const start = node?.position?.start.offset; const end = node?.position?.end.offset; if (start === undefined || end === undefined) return false; @@ -98,7 +94,7 @@ export function extractCodeBlock( return null; } // With a custom `code` component the child's type is that component, not - // the "code" tag — the hast node react-markdown attaches still names it. + // the "code" tag — the hast node the renderer passes still names it. if (onlyChild.type !== "code" && onlyChild.props.node?.tagName !== "code") { return null; } diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.tsx b/apps/web/src/components/chat/MarkdownCodeBlock.tsx index d6c8a7aaba2eb..726c34cbf029e 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.tsx +++ b/apps/web/src/components/chat/MarkdownCodeBlock.tsx @@ -1,4 +1,4 @@ -import { T, useGT } from "gt-react"; +import { useGT } from "gt-react"; import { PlayIcon, WrapTextIcon, CheckIcon, CopyIcon } from "lucide-react"; import { toHtml } from "hast-util-to-html"; import React, { use, useEffect, useState, type ReactNode } from "react"; @@ -18,7 +18,7 @@ import { syntheticFileNameForLanguageId, } from "../../pierre-icons"; import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { HighlightedCodeLines } from "./HighlightedCodeLines"; import { createHighlightCacheKey, @@ -115,19 +115,17 @@ function MarkdownCodeBlockTitleContent({ return {language}; } return ( - - - } - > - - - {language} - + + } + > + + ); } @@ -187,22 +185,20 @@ export function MarkdownCodeBlock({ const handleCopy = () => copyToClipboard(code.endsWith("\n") ? code.slice(0, -1) : code); const copyButton = ( - - - } - > - {copied ? : } - - {copyLabel} - + + } + > + {copied ? : } + ); if (diagram) { @@ -231,43 +227,37 @@ export function MarkdownCodeBlock({ aria-label={gt("Code block actions")} > {canWrap ? ( - - setWrapOverride(!wrapped)} - aria-label={wrapLabel} - /> - } - > - - - {wrapLabel} - + setWrapOverride(!wrapped)} + aria-label={wrapLabel} + /> + } + > + + ) : null} {canRun ? ( - - onRunShellCommand(command)} - aria-label={gt("Run in terminal")} - /> - } - > - - - - Run in terminal - - + onRunShellCommand(command)} + aria-label={gt("Run in terminal")} + /> + } + > + + ) : null} {viewToggle} {copyButton} diff --git a/apps/web/src/components/chat/MarkdownDetails.tsx b/apps/web/src/components/chat/MarkdownDetails.tsx index 5ec510c3a4306..b6fa2b1d8d1f1 100644 --- a/apps/web/src/components/chat/MarkdownDetails.tsx +++ b/apps/web/src/components/chat/MarkdownDetails.tsx @@ -1,5 +1,6 @@ import { useGT } from "gt-react"; import { ChevronRightIcon } from "lucide-react"; +import { flushSync } from "react-dom"; import { Children, isValidElement, @@ -12,6 +13,11 @@ import { import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { findRevealRef, MarkdownFindContext } from "./markdownFindContext"; +const focusOnMount = (element: HTMLElement | null) => { + if (element && element.ownerDocument.activeElement === element.ownerDocument.body) + element.focus(); +}; + export function MarkdownDetails({ children, open = false, @@ -19,6 +25,7 @@ export function MarkdownDetails({ }: Pick, "children" | "open" | "dir">) { const gt = useGT(); const [isOpen, setIsOpen] = useState(open); + const [armed, setArmed] = useState<"hover" | "focus" | null>(null); const searching = use(MarkdownFindContext); const expanded = isOpen; const revealForFind = () => setIsOpen(true); @@ -36,6 +43,36 @@ export function MarkdownDetails({ : gt("Details", { $context: "fallback title of a collapsible section" }); const content = childNodes.filter((_, index) => index !== summaryIndex); + // Most details stay closed: mount Base UI on hover or focus, before the first click. + if (!armed && !expanded && !searching) { + return ( +
+
+ +
+
+ ); + } + return (
- } - className={MARKDOWN_FILE_LINK_CLASS_NAME} - data-markdown-copy={copyMarkdown} - onClick={(event) => { - event.preventDefault(); - event.stopPropagation(); - if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { - handleOpenInEditor(); - return; - } - if (useBrowserPrimaryAction) { - handleOpenInBrowser(); - return; - } - handleOpenInFilePreview(); - }} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) : ( - } - aria-label={gt("File options for {label}", { label })} - aria-haspopup="menu" - className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} - data-markdown-copy={copyMarkdown} - onClick={handleContextMenu} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - theme={theme} - /> - - ) + const tooltipContent = ( + + ); + const sharedTooltip = useSharedTooltip({ + render: () => tooltipContent, + contentKey: `${iconPath}\u0000${targetPath}`, + variant: "code", + }); + const chip = hasPrimaryAction ? ( + } + className={MARKDOWN_FILE_LINK_CLASS_NAME} + data-markdown-copy={copyMarkdown} + onClick={(event) => { + event.preventDefault(); + event.stopPropagation(); + if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { + handleOpenInEditor(); + return; + } + if (useBrowserPrimaryAction) { + handleOpenInBrowser(); + return; } + handleOpenInFilePreview(); + }} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} + /> + + ) : ( + } + aria-label={gt("File options for {label}", { label })} + aria-haspopup="menu" + className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} + data-markdown-copy={copyMarkdown} + onClick={handleContextMenu} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + theme={theme} /> + + ); + if (sharedTooltip) return withSharedTooltip(chip, sharedTooltip); + return ( + + - + {tooltipContent} ); diff --git a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx b/apps/web/src/components/chat/MarkdownMath.browser.test.tsx deleted file mode 100644 index ec5b38541ddc4..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, it } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; - -import { render } from "../../../test/render"; -import "../../index.css"; - -import { MarkdownMath } from "./MarkdownMath"; - -it("keeps keyboard scrolling available as a streamed equation outgrows its viewport", async () => { - const equation = (tex: string, width = 180) => ( -
- - - -
- ); - await using screen = await render(equation("x")); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8")); - const scroller = screen.getByLabelText("Scroll display equation"); - await expect.element(scroller).toHaveAttribute("tabindex", "0"); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(scroller).toHaveFocus(); - await userEvent.keyboard("{ArrowRight}"); - await expect.element(scroller).not.toHaveProperty("scrollLeft", 0); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8", 1000)); - await expect.element(screen.getByLabelText("Scroll display equation")).not.toBeInTheDocument(); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); -}); diff --git a/apps/web/src/components/chat/MarkdownMath.tsx b/apps/web/src/components/chat/MarkdownMath.tsx deleted file mode 100644 index 8070d64ac3c18..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import { useGT } from "gt-react"; -import { lazy, memo, Suspense, useLayoutEffect, useRef, useState } from "react"; - -import { observeResize } from "../../lib/observeResize"; - -import { RenderErrorBoundary } from "../RenderErrorBoundary"; - -const MathTypeset = lazy(() => import("./MathTypeset")); - -/** - * One formula from `remark-math`. Shows its TeX until KaTeX loads, and - * keeps showing it when KaTeX cannot parse it, such as mid-stream. Copying - * any part of a formula copies its whole TeX source. - */ -export const MarkdownMath = memo(function MarkdownMath(props: { - tex: string; - display: boolean; - focusable?: boolean; -}) { - const gt = useGT(); - const viewportRef = useRef(null); - const contentRef = useRef(null); - const [overflows, setOverflows] = useState(false); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes formula DOM width to make overflowing equations keyboard scrollable - useLayoutEffect(() => { - const viewport = viewportRef.current; - const content = contentRef.current; - if (!viewport || !content || props.focusable === false) return; - const measure = () => setOverflows(viewport.scrollWidth > viewport.clientWidth); - measure(); - // Typesetting and streamed TeX can change content width without resizing the viewport. - return observeResize([viewport, content], measure); - }, [props.focusable]); - const scrollable = props.focusable !== false && overflows; - const tex = props.tex.trim(); - const source = props.display ? `\\[\n${tex}\n\\]` : `\\(${tex}\\)`; - const fallback = {source}; - return ( - - - - - - - - - - - - ); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.test.ts b/apps/web/src/components/chat/MathTypeset.logic.test.ts deleted file mode 100644 index 634f5146475ac..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import katex from "katex"; -import { describe, expect, it } from "vite-plus/test"; - -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -describe("escapeLiteralPercents", () => { - it.each([ - ["\\text{3.18% yield}", "\\text{3.18\\% yield}"], - ["\\text{100%% yield}", "\\text{100\\%\\% yield}"], - ["6\\% + 2\\%", "6\\% + 2\\%"], - ["x\\\\%", "x\\\\\\%"], - ["x % note\n+ 1", "x % note\n+ 1"], - ["% note\n\\text{2%}", "% note\n\\text{2\\%}"], - ["x &= 1 % +9%\n\\text{2%}", "x &= 1 % +9%\n\\text{2\\%}"], - ["\\verb|50%|+\\text{2%}", "\\verb|50%|+\\text{2\\%}"], - ["\\verb*%a%b%+c%", "\\verb*%a%b\\%+c\\%"], - ["\\verb|50%+\\text{2%}", "\\verb|50%+\\text{2%}"], - ])("repairs %j", (tex, expected) => { - expect(escapeLiteralPercents(tex)).toBe(expected); - }); - - it("lets the reported multiline equation typeset", () => { - const tex = - "R_e=\\underbrace{\\frac{1.0176}{32}}_{\\text{3.18% dividend yield}}\n+\\underbrace{6\\%}_{\\text{growth}}\n=\\boxed{9.18\\%}"; - expect(() => katex.renderToString(tex, { throwOnError: true })).toThrow(); - expect(() => - katex.renderToString(escapeLiteralPercents(tex), { throwOnError: true }), - ).not.toThrow(); - }); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.ts b/apps/web/src/components/chat/MathTypeset.logic.ts deleted file mode 100644 index 04111ab4a70b4..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Escapes each `%` written right after other text, as in `\text{3.18% yield}`. - * A `%` at a line start or after whitespace stays a comment. Skips escapes and - * `\verb` like KaTeX's lexer, in one linear pass. - */ -export function escapeLiteralPercents(tex: string): string { - let repaired = ""; - let copied = 0; - let index = 0; - while (index < tex.length) { - const char = tex[index]; - if (char === "\\") { - if (tex.startsWith("\\verb", index)) { - const starred = tex[index + 5] === "*"; - const delimiter = tex[index + (starred ? 6 : 5)]; - if (delimiter !== undefined && (starred || !/[*a-zA-Z]/.test(delimiter))) { - const bodyStart = index + (starred ? 7 : 6); - let close = bodyStart; - while (close < tex.length && ![delimiter, "\n", "\r"].includes(tex[close]!)) close++; - // KaTeX rejects a \verb that does not close on its own line. - if (tex[close] !== delimiter) return tex; - index = close + 1; - continue; - } - } - // A control symbol such as `\%` or `\\` is two characters. - index += 2; - } else if (char === "%" && index > 0 && !/\s/.test(tex[index - 1]!)) { - repaired += `${tex.slice(copied, index)}\\%`; - copied = ++index; - } else if (char === "%") { - const newline = tex.indexOf("\n", index); - index = newline === -1 ? tex.length : newline + 1; - } else { - index++; - } - } - return copied === 0 ? tex : repaired + tex.slice(copied); -} diff --git a/apps/web/src/components/chat/MathTypeset.tsx b/apps/web/src/components/chat/MathTypeset.tsx deleted file mode 100644 index 16d3dba409ee6..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import katex from "katex"; -import "katex/dist/katex.min.css"; -import type { ReactNode } from "react"; - -import { LRUCache } from "../../lib/lruCache"; -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -// Virtualized threads remount messages while scrolling; cached markup keeps -// that from typesetting the same formulas again. "" records a parse error. -const typesetCache = new LRUCache(1000, 4 * 1024 * 1024); - -function typeset(tex: string, display: boolean): string { - const key = `${display ? "display" : "inline"}:${tex}`; - const cached = typesetCache.get(key); - if (cached !== null) return cached; - const options = { - displayMode: display, - output: "htmlAndMathml" as const, - throwOnError: true, - // No \href, \url, \htmlClass, or other commands that emit active HTML. - trust: false, - strict: "ignore" as const, - maxSize: 20, - maxExpand: 1000, - }; - let html = ""; - try { - html = katex.renderToString(tex, options); - } catch { - const repaired = escapeLiteralPercents(tex); - if (repaired !== tex) { - try { - html = katex.renderToString(repaired, options); - } catch { - // Unfinished or unsupported TeX stays readable as its source. - } - } - } - typesetCache.set(key, html, (key.length + html.length) * 2); - return html; -} - -/** KaTeX lives in this lazily loaded chunk, so it is only fetched once a formula renders. */ -export default function MathTypeset(props: { tex: string; display: boolean; fallback: ReactNode }) { - const html = typeset(props.tex, props.display); - if (!html) return props.fallback; - // KaTeX escapes the TeX it renders, and `trust: false` keeps it from emitting links or attributes. - return ; -} diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 2e7721dddea18..d15a26ca43db0 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -44,11 +44,10 @@ import { type PendingApproval, deriveTimelineEntriesFromVisibleTurnItems, } from "../../session-logic"; -import type { Root } from "mdast"; import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; -import { remarkThoughtPreview, THOUGHT_PREVIEW_MAX_LENGTH } from "./TimelineWorkEntryRow.logic"; +import { THOUGHT_PREVIEW_MAX_LENGTH, thoughtPreviewMarkdown } from "./TimelineWorkEntryRow.logic"; +import { wordsHast } from "~/markdown/wordsHast"; import { TimelineRowCtx } from "./timelineRowContext"; -import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; @@ -2128,49 +2127,22 @@ describe("compact reasoning math", () => { ["hard \nbreak\\\nagain", [["text", "hard break again"]]], ["
only html
", [["text", "Reasoning"]]], ])("keeps formulas while flattening compact reasoning previews: %j", (source, expected) => { - const tree = parseMarkdownWithMath(source); - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children.map((node) => [node.type, "value" in node ? node.value : null])).toEqual( - expected, - ); - }); - - it("stops reading the tree once the preview is full", () => { - const beyondCap = (): string => { - throw new Error("read beyond cap"); - }; - const head = "x".repeat(THOUGHT_PREVIEW_MAX_LENGTH - 2); - const tree: Root = { - type: "root", - children: [ - { - type: "paragraph", - children: [ - { type: "text", value: head }, - { type: "strong", children: [{ type: "text", value: "yz beyond" }] }, - { - type: "inlineMath", - get value() { - return beyondCap(); - }, - }, - ], - }, - { - type: "paragraph", - children: [ - { - type: "text", - get value() { - return beyondCap(); - }, - }, - ], - }, - ], - }; - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children).toEqual([{ type: "text", value: `${head}yz` }]); + const tree = wordsHast(source, { + math: true, + breaks: false, + escapeHtml: false, + insights: false, + extensions: thoughtPreviewMarkdown("Reasoning"), + }); + expect( + tree.children.map((node) => + node.type === "text" + ? ["text", node.value] + : node.type === "element" && node.children[0]?.type === "element" + ? ["inlineMath", String(node.children[0].properties.ariaLabel).trim()] + : [node.type, null], + ), + ).toEqual(expected); }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 124062303e0cf..b00a48185b9db 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -14,7 +14,7 @@ import { IDLE_COMPACTION_TITLES, } from "@t3tools/client-runtime/user-message"; import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff"; -import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives"; +import { renderCodexDirectivesForCopy } from "~/markdown/markdownText"; import { commandDisplayText, commandProgramName, diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 7ab6e361494ee..72fcf79013e87 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -1,4 +1,4 @@ -import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline"; +import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/assistantInsights"; import { MessageId, type RunId, type TurnItemId } from "@t3tools/contracts"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; import { agentWorkingDirectories } from "@t3tools/client-runtime/workspace-basename-lookup"; diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 88cdd61b58cc5..cd99aad44d080 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,10 +1,7 @@ import { copySnapshot as copySnapshotToClipboard } from "./copySnapshot"; import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; -import { - CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -} from "@t3tools/shared/markdownPipeline"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { T, useGT, useMessages, Var } from "gt-react"; import { findRevealRef } from "./markdownFindContext"; import { @@ -1284,10 +1281,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop ); }); -const USER_MESSAGE_REMARK_PLUGINS = [ - ...CHAT_USER_MARKDOWN_REMARK_PLUGINS, - remarkEnableOrderedListNumbers, -]; +const USER_MESSAGE_MARKDOWN: MarkdownExtensions = { userMessage: true, leadingWhitespace: true }; const UserMessageBody = memo(function UserMessageBody(props: { text: string; @@ -1308,7 +1302,7 @@ const UserMessageBody = memo(function UserMessageBody(props: { className="text-message-foreground user-message-markdown" lineBreaks parseRawHtml={false} - extraRemarkPlugins={USER_MESSAGE_REMARK_PLUGINS} + extensions={USER_MESSAGE_MARKDOWN} renderContextReference={props.renderContextReference} headingLevelOffset={MESSAGE_HEADING_LEVEL} /> diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts index dc279ea8cb164..894f58f45edb4 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts @@ -1,6 +1,5 @@ import { msg } from "gt-react"; -import type { PluggableList } from "unified"; -import type { Root, RootContent } from "mdast"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { resolveWorkEntryToolPresentation, toolGroupAction, @@ -209,67 +208,14 @@ export function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconNa export const THOUGHT_PREVIEW_SOURCE_MAX_LENGTH = 8_192; export const THOUGHT_PREVIEW_MAX_LENGTH = 2_048; -/** Compact reasoning keeps formulas while flattening other Markdown into label text. */ -export function remarkThoughtPreview(fallback: string) { - return (tree: Root) => { - const children: RootContent[] = []; - let remaining = THOUGHT_PREVIEW_MAX_LENGTH; - let fragments: string[] = []; - const flush = () => { - if (fragments.length === 0) return; - children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") }); - fragments = []; - }; - const take = (value: string) => { - const text = value.slice(0, remaining); - remaining = text.length < value.length ? 0 : remaining - text.length; - // A cut here or at the source limit must not leave half a surrogate pair. - return text.replace(/[\uD800-\uDBFF]$/, ""); - }; - const append = (value: string) => { - fragments.push(take(value)); - }; - const visit = (node: Root | RootContent) => { - if (remaining === 0 || node.type === "html" || node.type === "definition") return; - if (node.type === "math" || node.type === "inlineMath") { - flush(); - const value = take(node.value); - children.push({ - type: "inlineMath", - value, - position: node.position, - data: { - hName: "code", - hProperties: { className: ["language-math", "math-inline"] }, - hChildren: [{ type: "text", value }], - }, - }); - } else if ("alt" in node) append(node.alt ?? ""); - else if ("value" in node) append(node.value); - else if ("children" in node) { - for (const [index, child] of node.children.entries()) { - if (remaining === 0) break; - if ( - index && - ["root", "blockquote", "list", "listItem", "table", "tableRow"].includes(node.type) - ) - append(" "); - visit(child); - } - } else if (node.type === "break") append(" "); - }; - visit(tree); - flush(); - const first = children[0]; - const last = children.at(-1); - if (first?.type === "text") first.value = first.value.trimStart(); - if (last?.type === "text") last.value = last.value.trimEnd(); - tree.children = children.some((child) => child.type !== "text" || child.value) - ? children - : [{ type: "text", value: fallback }]; - }; -} +const thoughtPreviews = new Map(); -export function thoughtPreviewPlugins(fallback: string): PluggableList { - return [[remarkThoughtPreview, fallback]]; +/** Compact reasoning keeps formulas while flattening other Markdown into label text. */ +export function thoughtPreviewMarkdown(fallback: string): MarkdownExtensions { + let extensions = thoughtPreviews.get(fallback); + if (!extensions) { + extensions = { preview: { fallback, maxLength: THOUGHT_PREVIEW_MAX_LENGTH } }; + thoughtPreviews.set(fallback, extensions); + } + return extensions; } diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 8e7f03618e59d..4cd6fc0e8dee6 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -73,7 +73,7 @@ import { workEntryRawCommand, buildToolCallExpandedBody, workEntryIconName, - thoughtPreviewPlugins, + thoughtPreviewMarkdown, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, } from "./TimelineWorkEntryRow.logic"; @@ -590,10 +590,10 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { )} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={ + extensions={ workEntry.toolLifecycleStatus === "inProgress" - ? thoughtPreviewPlugins(gt("Thinking")) - : thoughtPreviewPlugins(gt("Thought")) + ? thoughtPreviewMarkdown(gt("Thinking")) + : thoughtPreviewMarkdown(gt("Thought")) } /> ) : threadLabel ? ( diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx index 745a7aff68fdf..c67c76bf4cca3 100644 --- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx +++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx @@ -56,7 +56,7 @@ import { SimpleWorkEntryRow, } from "./TimelineWorkEntryRow"; import { - thoughtPreviewPlugins, + thoughtPreviewMarkdown, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH, toolGroupSummaryIconName, workEntryIconName, @@ -640,7 +640,7 @@ export function LiveWorkEntryTimelineRow({ text={thoughtLine} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={thoughtPreviewPlugins(gt("Thought"))} + extensions={thoughtPreviewMarkdown(gt("Thought"))} />
} @@ -661,10 +661,10 @@ export function LiveWorkEntryTimelineRow({ text={(row.entry.detail ?? label).slice(0, THOUGHT_PREVIEW_SOURCE_MAX_LENGTH)} cwd={ctx.markdownCwd} parseRawHtml={false} - extraRemarkPlugins={ + extensions={ row.active - ? thoughtPreviewPlugins(gt("Thinking")) - : thoughtPreviewPlugins(gt("Thought")) + ? thoughtPreviewMarkdown(gt("Thinking")) + : thoughtPreviewMarkdown(gt("Thought")) } /> ) : threadLabel ? ( diff --git a/apps/web/src/components/chat/markdownIslands.test.ts b/apps/web/src/components/chat/markdownIslands.test.ts new file mode 100644 index 0000000000000..f328c9ea51251 --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.test.ts @@ -0,0 +1,50 @@ +import type { Root } from "hast"; +import { renderToStaticMarkup } from "react-dom/server"; +import { createElement, Fragment } from "react"; +import { describe, expect, it } from "vite-plus/test"; + +import { renderHastWithIslands } from "./markdownIslands"; + +describe("renderHastWithIslands", () => { + it("writes SVG attributes by their SVG names in static HTML", () => { + const tree: Root = { + type: "root", + children: [ + { + type: "element", + tagName: "p", + properties: {}, + children: [ + { + type: "element", + tagName: "svg", + properties: { viewBox: "0 0 1 1" }, + children: [ + { + type: "element", + tagName: "text", + properties: { fontSize: "700", strokeWidth: "2" }, + children: [{ type: "text", value: "x" }], + }, + ], + }, + ], + }, + ], + }; + const html = renderToStaticMarkup( + createElement( + Fragment, + null, + renderHastWithIslands(tree, { + components: {}, + variant: "", + isIsland: () => false, + staticElement: (node) => node, + }), + ), + ); + expect(html).toContain('x'); + expect(html).toContain('viewBox="0 0 1 1"'); + }); +}); diff --git a/apps/web/src/components/chat/markdownIslands.ts b/apps/web/src/components/chat/markdownIslands.ts new file mode 100644 index 0000000000000..8c434daf099ce --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.ts @@ -0,0 +1,214 @@ +import type { Element, ElementContent, Properties, Root, RootContent } from "hast"; +import { find, html as htmlSchema, svg as svgSchema } from "property-information"; +import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; +import { createElement, Fragment as ReactFragment, type ReactNode } from "react"; +import { Fragment, jsx, jsxs } from "react/jsx-runtime"; + +export interface MarkdownIslandOptions { + readonly components: Partial; + /** Elements that need their React component; everything else renders as static HTML. */ + readonly isIsland: (node: Element) => boolean; + /** What a static element's component would have added, or the node itself when nothing. */ + readonly staticElement: (node: Element) => Element; + /** Separates static HTML that `staticElement` renders differently, such as a heading offset. */ + readonly variant: string; +} + +const VOID_ELEMENTS = new Set( + "area base br col embed hr img input link meta source track wbr".split(" "), +); + +const jsxOptions = (components: Partial) => + ({ + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + }) as const; + +// Static HTML depends only on the cached, immutable tree and the variant. +const innerHtmlCache = new WeakMap(); + +function transformStatic( + node: ElementContent, + staticElement: MarkdownIslandOptions["staticElement"], +): ElementContent { + if (node.type !== "element") return node; + const element = staticElement(node); + let children: ElementContent[] | undefined; + for (let index = 0; index < element.children.length; index++) { + const child = element.children[index]!; + const next = transformStatic(child, staticElement); + if (next !== child) { + children ??= element.children.slice(); + children[index] = next; + } + } + return children ? { ...element, children } : element; +} + +function innerHtml(node: Element, options: MarkdownIslandOptions): string { + const cached = innerHtmlCache.get(node); + if (cached?.variant === options.variant) return cached.html; + let html = ""; + for (const child of node.children) { + html += serialize(transformStatic(child, options.staticElement)); + } + innerHtmlCache.set(node, { variant: options.variant, html }); + return html; +} + +interface AttributeInfo { + readonly name: string; + readonly boolean: boolean; + readonly separator: string; +} + +const attributeInfo = new Map(); + +// SVG names its attributes differently (`fontSize` is `font-size`), so its lookups key apart. +function infoFor(property: string, inSvg: boolean): AttributeInfo { + const key = inSvg ? `svg:${property}` : property; + let info = attributeInfo.get(key); + if (!info) { + const found = find(inSvg ? svgSchema : htmlSchema, property); + info = { + name: found.attribute, + boolean: found.boolean || found.overloadedBoolean, + separator: found.commaSeparated ? ", " : " ", + }; + attributeInfo.set(key, info); + } + return info; +} + +const escapeText = (value: string) => + value.includes("&") || value.includes("<") || value.includes(">") + ? value.replace(/&/g, "&").replace(//g, ">") + : value; +const escapeAttribute = (value: string) => + value.includes("&") || value.includes('"') + ? value.replace(/&/g, "&").replace(/"/g, """) + : value; + +/** HTML for the elements and text this pipeline builds; the DOM matches hast-util-to-html's. */ +function serialize(node: ElementContent, inSvg = false): string { + if (node.type === "text") return escapeText(node.value); + if (node.type !== "element") return ""; + const svg = inSvg || node.tagName === "svg"; + let html = `<${node.tagName}`; + const { properties } = node; + for (const key in properties) { + const value = properties[key]; + if (value === null || value === undefined || value === false || Number.isNaN(value)) continue; + const info = infoFor(key, svg); + if (info.boolean && value) { + html += ` ${info.name}`; + continue; + } + const text = Array.isArray(value) + ? value.join(info.separator) + : value === true + ? "" + : String(value); + html += ` ${info.name}="${escapeAttribute(text)}"`; + } + html += ">"; + if (VOID_ELEMENTS.has(node.tagName)) return html; + for (const child of node.children) html += serialize(child, svg); + return `${html}`; +} + +/** React props for an element, converted as hast-util-to-jsx-runtime converts them. */ +function shallowProps(node: Element, components: Partial): Record { + const element = toJsxRuntime( + { ...node, children: [] }, + { ...jsxOptions(components), components: {}, passNode: false }, + ) as { props: Record }; + const { children: _children, ...props } = element.props; + return props; +} + +interface Plan { + readonly islands: Set; + /** Elements with an island somewhere below them. */ + readonly ancestors: Set; +} + +function renderContent( + node: RootContent, + key: number, + options: MarkdownIslandOptions, + plan: Plan, +): ReactNode { + if (node.type === "text") return node.value; + if (node.type !== "element") return null; + if (plan.islands.has(node)) { + return createElement( + ReactFragment, + { key }, + toJsxRuntime(node, jsxOptions(options.components)), + ); + } + const element = options.staticElement(node); + const props: Record = { ...shallowProps(element, options.components), key }; + if (plan.ancestors.has(node)) { + return createElement( + element.tagName, + props, + ...element.children.map((child, index) => renderContent(child, index, options, plan)), + ); + } + if (element.children.length > 0 && !VOID_ELEMENTS.has(element.tagName)) { + props.dangerouslySetInnerHTML = { __html: innerHtml(node, options) }; + } + return createElement(element.tagName, props); +} + +/** + * Renders a hast tree with React only on the path to elements that need a component: subtrees + * without one become static HTML, which the browser builds without React reconciling each node. + */ +export function renderHastWithIslands(tree: Root, options: MarkdownIslandOptions): ReactNode { + // The same elements again let React skip the block; islands still follow their context. + let signature = options.variant; + const plan: Plan = { islands: new Set(), ancestors: new Set() }; + const visit = (node: Root | Element): boolean => { + let below = false; + for (const child of node.children) { + if (child.type !== "element") continue; + const island = options.isIsland(child); + signature += island ? "1" : "0"; + if (island) { + plan.islands.add(child); + below = true; + continue; + } + if (visit(child)) { + plan.ancestors.add(child); + below = true; + } + } + return below; + }; + visit(tree); + const cached = renderedTrees.get(tree); + if (cached?.signature === signature && cached.components === options.components) { + return cached.node; + } + const node = tree.children.map((child, index) => renderContent(child, index, options, plan)); + renderedTrees.set(tree, { signature, components: options.components, node }); + return node; +} + +const renderedTrees = new WeakMap< + Root, + { signature: string; components: Partial; node: ReactNode } +>(); + +export function withProperties(node: Element, properties: Properties): Element { + return { ...node, properties: { ...node.properties, ...properties } }; +} diff --git a/apps/web/src/components/chat/markdownRenderer.test.tsx b/apps/web/src/components/chat/markdownRenderer.test.tsx index f15fe49584aea..a9a60c545b37b 100644 --- a/apps/web/src/components/chat/markdownRenderer.test.tsx +++ b/apps/web/src/components/chat/markdownRenderer.test.tsx @@ -1,88 +1,41 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; import { describe, expect, it } from "vite-plus/test"; -import { createIncrementalMarkdownPlugin } from "../../markdown-incremental"; import { createMarkdownRenderer } from "./markdownRenderer"; // Visible in the markup, so every URL attribute must pass through it. const urlTransform = (url: string) => `${url}#seen`; describe("createMarkdownRenderer", () => { - const render = createMarkdownRenderer({ - remarkPlugins: CHAT_MARKDOWN_REMARK_PLUGINS, - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, + const renderer = createMarkdownRenderer({ + markdown: { math: false, breaks: false, escapeHtml: false, insights: false, extensions: {} }, components: {}, urlTransform, }); + const render = (text: string) => renderer.element(renderer.parse(text)); + const renderAndRemember = (text: string) => { + const entry = renderer.parse(text); + renderer.remember(text, entry); + return renderer.element(entry); + }; - it.each([ - '# Title\n\nText with `code`, **bold**, [a link](https://example.com "t") and https://bare.example.com.', - "![shot](./shot.png) and [file](file:///C:/repo/a.ts) and [bad](javascript:alert(1))", - "
More\n\nHidden bold \n\n
", - "| a | b |\n| - | - |\n|
| [x](#frag) |\n\n- [ ] task\n- [x] done", - '```ts title="a.ts"\nconst a = 1;\n```\n\n> [!WARNING]\n> careful
bare', - "Footnote[^1] and ~~strike~~\n\n[^1]: the note", - // Each GFM construct the parser skips when its text cannot match, next to one that can. - "Mail me@example.com, see www.example.com and HTTPS://example.com/a, not [x](https://y.z).", - "a.b-c_d+e@x.io and @user\n\n`me@x.io` ", - "A table without pipes\n:--", - "> | quoted |\n> | - |\n> | body |\n\n- [ ] open\n- [X] done", - "Escaped www\\.example.com and me@example.com", - "\ufeffA byte order mark\n\n| a |\n| - |\n| b |", - "> - | a |\r\n> | - |\r\n> | me@x.io |\r\n\n-\t[ ] tab\n\n ~~lazy~~", - ])("renders what react-markdown renders: %j", (source) => { - const expected = renderToStaticMarkup( - - {source} - , + it("passes every URL attribute through the transform", () => { + const html = renderToStaticMarkup( + render('![shot](./shot.png) and [a link](https://example.com "t") and '), ); - const element = render(source); - expect(renderToStaticMarkup(element)).toBe(expected); - render.remember(source, element); - expect(render(source)).toBe(element); + expect(html).toContain('src="./shot.png#seen"'); + expect(html).toContain('href="https://example.com#seen"'); + expect(html).toContain('src="b.png#seen"'); }); - it("renders what react-markdown renders while a reply streams through the incremental parser", () => { - const reply = - "```ts\nconst a = 1;\n```\n\n| a | b |\n| - | - |\n| me@x.io | www.x.io |\n\nDone ~~now~~."; - // As ChatMarkdown streams: one incremental plugin for the reply, a fresh renderer per update. - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 1; end <= reply.length; end++) { - const source = reply.slice(0, end); - const streamed = createMarkdownRenderer({ - remarkPlugins: [...CHAT_MARKDOWN_REMARK_PLUGINS, incremental], - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, - components: {}, - urlTransform, - })(source); - expect(renderToStaticMarkup(streamed)).toBe( - renderToStaticMarkup( - - {source} - , - ), - ); - } + it("reuses a remembered message's element", () => { + const element = renderAndRemember("# Title\n\nText with `code` and **bold**."); + expect(render("# Title\n\nText with `code` and **bold**.")).toBe(element); }); it("keeps cached messages when one far larger than the cache is rendered", () => { - const element = render("Kept *message*"); - render.remember("Kept *message*", element); - const large = "x".repeat(600_000); - render.remember(large, render(large)); + const element = renderAndRemember("Kept *message*"); + renderAndRemember("x".repeat(600_000)); expect(render("Kept *message*")).toBe(element); }); }); diff --git a/apps/web/src/components/chat/markdownRenderer.ts b/apps/web/src/components/chat/markdownRenderer.ts index 9637d68e8f158..c2aa499a9583d 100644 --- a/apps/web/src/components/chat/markdownRenderer.ts +++ b/apps/web/src/components/chat/markdownRenderer.ts @@ -3,18 +3,13 @@ import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; import { urlAttributes } from "html-url-attributes"; import type { ReactElement } from "react"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { type PluggableList, unified } from "unified"; -import { VFile } from "vfile"; -import { remarkParseWithoutUnusedSyntax } from "./markdownSyntaxGates"; +import { wordsHast, type WordsHastOptions } from "../../markdown/wordsHast"; export type MarkdownUrlTransform = (url: string, key: string, node: Element) => string; interface MarkdownRendererOptions { - readonly remarkPlugins: PluggableList; - readonly rehypePlugins: PluggableList; + readonly markdown: WordsHastOptions; readonly components: Partial; readonly urlTransform: MarkdownUrlTransform; } @@ -23,7 +18,11 @@ interface MarkdownRendererOptions { // reuses one instead of parsing again. Parsing is most of the cost of rendering markdown. // An element and the hast it keeps hold about 20 bytes per source character, so ~10 MB. const MAX_CACHED_CHARS = 500_000; -const rendered = new Map(); +interface Rendered { + readonly tree: Root; + element?: ReactElement; +} +const rendered = new Map(); let cachedChars = 0; let nextRendererId = 0; @@ -31,10 +30,10 @@ let nextRendererId = 0; const ENTRY_OVERHEAD_CHARS = 200; const entrySize = (key: string) => key.length + ENTRY_OVERHEAD_CHARS; -function remember(key: string, element: ReactElement) { +function remember(key: string, entry: Rendered) { // One huge message would otherwise evict everything else. if (entrySize(key) > MAX_CACHED_CHARS / 4) return; - rendered.set(key, element); + rendered.set(key, entry); cachedChars += entrySize(key); for (const oldest of rendered.keys()) { if (cachedChars <= MAX_CACHED_CHARS) break; @@ -43,32 +42,18 @@ function remember(key: string, element: ReactElement) { } } -/** Renders markdown as react-markdown does, with one processor per plugin set. */ +/** Renders markdown with Words, keeping one parse cache per option set. */ export function createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, + markdown, components, urlTransform, }: MarkdownRendererOptions) { - const processor = unified() - .use(remarkParse) - .use(remarkParseWithoutUnusedSyntax) - .use(remarkPlugins) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(rehypePlugins) - .freeze(); const keyPrefix = `${nextRendererId++}\u0000`; - // Literal raw HTML that survived the rehype plugins, and URL attributes, as react-markdown treats them. + // URL attributes, as react-markdown transformed them. const prepare = (node: Nodes) => { if (!("children" in node)) return; - const { children } = node; - for (let index = 0; index < children.length; index++) { - const child = children[index]!; - if (child.type === "raw") { - children[index] = { type: "text", value: child.value }; - continue; - } + for (const child of node.children) { if (child.type !== "element") continue; const { properties } = child; for (const key in properties) { @@ -82,7 +67,7 @@ export function createMarkdownRenderer({ } }; - const render = (text: string): ReactElement => { + const parse = (text: string): Rendered => { const key = keyPrefix + text; const cached = rendered.get(key); if (cached !== undefined) { @@ -91,24 +76,27 @@ export function createMarkdownRenderer({ rendered.set(key, cached); return cached; } - const file = new VFile(text); - const tree = processor.runSync(processor.parse(file), file) as Root; + const tree = wordsHast(text, markdown); prepare(tree); - return toJsxRuntime(tree, { - Fragment, - components, - ignoreInvalidStyle: true, - jsx, - jsxs, - passKeys: true, - passNode: true, - }); + return { tree }; }; - return Object.assign(render, { - remember(text: string, element: ReactElement) { + return { + /** A cached entry, or a fresh one that `remember` can keep. Cached trees are shared, so callers must not change them. */ + parse, + element: (entry: Rendered): ReactElement => + (entry.element ??= toJsxRuntime(entry.tree, { + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + })), + remember(text: string, entry: Rendered) { const key = keyPrefix + text; - if (!rendered.has(key)) remember(key, element); + if (!rendered.has(key)) remember(key, entry); }, - }); + }; } diff --git a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx b/apps/web/src/components/chat/markdownStreamBlocks.test.ts similarity index 81% rename from apps/web/src/components/chat/markdownStreamBlocks.test.tsx rename to apps/web/src/components/chat/markdownStreamBlocks.test.ts index 38ecff7666508..b89940489ec32 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx +++ b/apps/web/src/components/chat/markdownStreamBlocks.test.ts @@ -1,32 +1,19 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkMath from "remark-math"; -import type { PluggableList } from "unified"; +import { toHtml } from "hast-util-to-html"; import { describe, expect, it } from "vite-plus/test"; +import { wordsHast } from "~/markdown/wordsHast"; import { splitMarkdownBlocks } from "./markdownStreamBlocks"; -import { rehypeHeadingIds } from "./markdownFragments"; - -const MATH_PLUGINS: PluggableList = [[remarkMath, { singleDollarTextMath: true }]]; // Whitespace between top-level blocks collapses in the rendered message. const renderMarkdown = (source: string, math = false) => - renderToStaticMarkup( - - {source} - , + toHtml( + wordsHast(source, { + math, + breaks: false, + escapeHtml: false, + insights: source.includes("★ Insight"), + extensions: {}, + }), ) .replace(/>\s+<") .trim(); diff --git a/apps/web/src/components/chat/markdownSyntaxGates.ts b/apps/web/src/components/chat/markdownSyntaxGates.ts deleted file mode 100644 index 57587a51b9d13..0000000000000 --- a/apps/web/src/components/chat/markdownSyntaxGates.ts +++ /dev/null @@ -1,204 +0,0 @@ -import type { Nodes as MdastNodes } from "mdast"; -import { - type Extension as MdastExtension, - fromMarkdown, - type Options as FromMarkdownOptions, - type Transform, -} from "mdast-util-from-markdown"; -import { combineExtensions } from "micromark-util-combine-extensions"; -import type { Construct, Extension, TokenizeContext } from "micromark-util-types"; -import type { Processor } from "unified"; - -// A table needs a delimiter row: dashes with a `|` or `:`, after any `>` or indent. -// One character class per pattern: overlapping ones backtrack quadratically on a run of dashes. -const DELIMITER_LINE = /^[ \t>|:-]+$/gm; -const isDelimiterRow = (line: string) => line.includes("-") && /[|:]/.test(line); -const NEXT_LINE = /[^\r\n]*(?:\r\n?|\n)([^\r\n]*)/y; - -function hasDelimiterRow(text: string) { - for (const [line] of text.matchAll(DELIMITER_LINE)) if (isDelimiterRow(line)) return true; - return false; -} -const PROTOCOL = /https?:\/\//iy; -const WWW = /www\./iy; -const EMAIL_ATEXT = /[\w+.-]*@/y; - -const matchesAt = (pattern: RegExp, text: string, offset: number) => { - pattern.lastIndex = offset; - return pattern.test(text); -}; - -interface Gate { - readonly names: ReadonlyArray; - /** False when the construct cannot match anywhere in the text. */ - readonly inText: (text: string) => boolean; - /** False when it cannot start at this offset, which keeps micromark from trying it there. */ - readonly at?: (context: TokenizeContext, text: string, offset: number) => boolean; -} - -// micromark tries these at every candidate character: email autolinks at every word, tables -// at every line. That is most of what GFM adds to a parse, and most texts cannot match them. -const GATES: ReadonlyArray = [ - { - names: ["emailAutolink"], - inText: (text) => text.includes("@"), - at: (_, text, offset) => matchesAt(EMAIL_ATEXT, text, offset), - }, - { - names: ["protocolAutolink"], - inText: (text) => /https?:\/\//i.test(text), - at: (_, text, offset) => matchesAt(PROTOCOL, text, offset), - }, - { - names: ["wwwAutolink"], - inText: (text) => /www\./i.test(text), - at: (_, text, offset) => matchesAt(WWW, text, offset), - }, - { - names: ["table"], - inText: hasDelimiterRow, - at: (context, text, offset) => { - NEXT_LINE.lastIndex = offset; - const nextLine = NEXT_LINE.exec(text)?.[1]; - return (nextLine !== undefined && hasDelimiterRow(nextLine)) || continuesTable(context); - }, - }, - { names: ["strikethrough"], inText: (text) => text.includes("~") }, - { - names: ["gfmFootnoteCall", "gfmPotentialFootnoteCall", "gfmFootnoteDefinition"], - inText: (text) => text.includes("[^"), - }, - { names: ["tasklistCheck"], inText: (text) => /\[[\sxX]\]/.test(text) }, -]; - -// A body row follows the head or another row. Mirrors `start` in micromark-extension-gfm-table's -// lib/syntax.js: recheck it when that package changes. -function continuesTable({ events }: TokenizeContext) { - let index = events.length - 1; - while (index > -1 && /^(?:lineEnding|linePrefix)$/.test(events[index]![1].type)) index--; - // The table extension's token types are not in micromark's map unless its types are loaded. - const tail: string | undefined = events[index]?.[1].type; - return tail === "tableHead" || tail === "tableRow"; -} - -let parsing = ""; -const gated = new WeakMap(); - -function gatedConstruct(construct: Construct, gate: Gate): Construct { - const at = gate.at; - if (!at) return construct; - let wrapped = gated.get(construct); - if (!wrapped) { - const { previous, tokenize } = construct; - wrapped = { - ...construct, - tokenize(effects, ok, nok) { - return at(this, parsing, this.now().offset) ? tokenize.call(this, effects, ok, nok) : nok; - }, - ...(previous && { - previous(code) { - return previous.call(this, code) && at(this, parsing, this.now().offset); - }, - }), - }; - gated.set(construct, wrapped); - } - return wrapped; -} - -type ConstructMap = Record; - -function gateExtension(extension: Extension, absent: ReadonlySet): Extension { - const gateOf = (name: string | undefined) => - GATES.find((gate) => name && gate.names.includes(name)); - const result: Record = {}; - for (const [field, value] of Object.entries(extension)) { - if (field === "disable" || field === "attentionMarkers" || !value) { - result[field] = value; - continue; - } - const map: ConstructMap = {}; - for (const [code, entry] of Object.entries(value as ConstructMap)) { - const kept = (Array.isArray(entry) ? entry : [entry]).flatMap((construct) => { - const gate = construct && gateOf(construct.name); - if (!construct || !gate) return construct ? [construct] : []; - return absent.has(gate) ? [] : [gatedConstruct(construct, gate)]; - }); - if (kept.length > 0) map[code] = Array.isArray(entry) ? kept : kept[0]; - } - result[field] = map; - } - return result as Extension; -} - -type MdastExtensions = NonNullable; - -// Merged once, as mdast-util-from-markdown merges them on every call: lists in order, handlers by key. -function mergeMdastExtensions(extensions: MdastExtensions): MdastExtension { - const merged = { - canContainEols: [] as string[], - enter: {}, - exit: {}, - transforms: [] as Transform[], - }; - for (const extension of extensions.flat()) { - merged.canContainEols.push(...(extension.canContainEols ?? [])); - Object.assign(merged.enter, extension.enter); - Object.assign(merged.exit, extension.exit); - // GFM looks for autolink literals again in the decoded text outside links, so `www\.x.io` - // links too. Most texts have URLs only in link destinations and code, where it finds nothing. - for (const transform of extension.transforms ?? []) { - merged.transforms.push( - extension.enter?.literalAutolink - ? (tree) => (hasAutolinkText(tree) ? transform(tree) : undefined) - : transform, - ); - } - } - return merged; -} - -const AUTOLINK_TEXT = /@|https?:\/\/|www\./i; - -function hasAutolinkText(node: MdastNodes): boolean { - if (node.type === "text") return AUTOLINK_TEXT.test(node.value); - if (node.type === "link" || node.type === "linkReference" || !("children" in node)) return false; - return node.children.some(hasAutolinkText); -} - -/** - * Parses as remark-parse does, without the syntax extension constructs that cannot match the - * text. Same tree, in about half the time. - */ -function attachParserWithoutUnusedSyntax(this: Processor) { - const data = this.data(); - const byMask = new Map(); - let mdastExtensions: MdastExtension[] | undefined; - this.parser = (document) => { - let mask = 0; - GATES.forEach((gate, index) => { - if (!gate.inText(document)) mask |= 1 << index; - }); - let extensions = byMask.get(mask); - if (!extensions) { - const absent = new Set(GATES.filter((_, index) => mask & (1 << index))); - extensions = [ - combineExtensions( - (data.micromarkExtensions ?? []).map((extension) => gateExtension(extension, absent)), - ), - ]; - byMask.set(mask, extensions); - } - mdastExtensions ??= [mergeMdastExtensions(data.fromMarkdownExtensions ?? [])]; - const outer = parsing; - // Gates read micromark offsets, which skip a leading byte order mark. - parsing = document.charCodeAt(0) === 0xfeff ? document.slice(1) : document; - try { - return fromMarkdown(document, { ...data.settings, extensions, mdastExtensions }); - } finally { - parsing = outer; - } - }; -} - -export const remarkParseWithoutUnusedSyntax = attachParserWithoutUnusedSyntax; diff --git a/apps/web/src/components/chat/markdownTextDirection.ts b/apps/web/src/components/chat/markdownTextDirection.ts index ffdbde76c1148..a4c78d3342754 100644 --- a/apps/web/src/components/chat/markdownTextDirection.ts +++ b/apps/web/src/components/chat/markdownTextDirection.ts @@ -1,4 +1,4 @@ -import { textDirection } from "~/textDirection"; +import { LETTER, RTL_LETTER, textDirection } from "~/textDirection"; type HastNode = { type?: string; @@ -57,11 +57,32 @@ function isolateInlineCode(node: HastNode): void { */ export function rehypeTextDirection() { return (tree: HastNode) => { - for (const block of tree.children ?? []) { - if (block.type !== "element" || block.tagName === "pre") continue; - const dir = textDirection(proseText(block)); - if (dir) block.properties = { ...block.properties, dir }; - } + blockTextDirections(tree); isolateInlineCode(tree); }; } + +/** Each top-level block's direction, from its prose; an RTL letter decides as textDirection does. */ +function blockTextDirections(tree: HastNode) { + for (const block of tree.children ?? []) { + if (block.type !== "element" || block.tagName === "pre") continue; + const dir = scriptOf(block) === "rtl" ? textDirection(proseText(block)) : scriptOf(block); + if (dir) block.properties = { ...block.properties, dir }; + } +} + +/** "rtl" when any prose letter is right-to-left; otherwise what textDirection would say. */ +function scriptOf(node: HastNode): "rtl" | "ltr" | undefined { + let found: "ltr" | undefined; + const visit = (current: HastNode): boolean => { + if (current.type === "text") { + const value = current.value ?? ""; + if (RTL_LETTER.test(value)) return true; + if (!found && LETTER.test(value)) found = "ltr"; + return false; + } + if (current.tagName === "code") return false; + return (current.children ?? []).some(visit); + }; + return visit(node) ? "rtl" : found; +} diff --git a/apps/web/src/components/chat/threadFindHighlights.ts b/apps/web/src/components/chat/threadFindHighlights.ts index c8ce0b31b9c9e..fe6a3ba5d3056 100644 --- a/apps/web/src/components/chat/threadFindHighlights.ts +++ b/apps/web/src/components/chat/threadFindHighlights.ts @@ -1,6 +1,6 @@ import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { useEffect, useEffectEvent, useRef } from "react"; -import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText"; +import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindBlockTags"; import { observeResize } from "~/lib/observeResize"; diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index 151a02d88175e..57f6229c99526 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -4,10 +4,9 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; -import type { Nodes } from "mdast"; -import remarkGfm from "remark-gfm"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import type { Nodes } from "hast"; + +import { markdownTree } from "~/markdown/wordsHast"; import type { MessagesTimelineRow } from "./MessagesTimeline.logic"; @@ -58,50 +57,49 @@ function resolveFinalAssistantTextForTurn( return finalAssistantText; } -const markdownPreviewParser = unified().use(remarkParse).use(remarkGfm).freeze(); - -const INLINE_PARENT_TYPES = new Set([ - "paragraph", - "heading", - "tableCell", - "emphasis", +// Elements whose children run together; every other element is separated by a space. +const INLINE_PARENTS = new Set([ + "p", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "td", + "th", + "em", "strong", - "delete", - "link", - "linkReference", + "del", + "a", + "code", + "span", + "sup", + "sub", ]); function markdownNodeText(node: Nodes): string { - if (node.type === "html") { - return node.value - .replace(/|$)/g, "") - .replace(/<\/?([a-z][\w-]*)(?:[^"'<>]|"[^"]*"|'[^']*')*>/gi, (_, tag: string) => - /^(?:address|article|aside|blockquote|br|dd|details|div|dl|dt|figcaption|figure|footer|h[1-6]|header|hr|li|main|nav|ol|p|pre|section|summary|table|tbody|td|th|thead|tr|ul)$/i.test( - tag, - ) - ? " " - : "", - ); - } - if (node.type === "break") return " "; - if ("value" in node) return node.value; - if (node.type === "image" || node.type === "imageReference") return node.alt ?? ""; - if (!("children" in node)) return ""; - const separator = INLINE_PARENT_TYPES.has(node.type) ? "" : " "; + if (node.type === "text") return node.value; + if (node.type === "element" && node.tagName === "br") return " "; + if (node.type === "element" && node.tagName === "img") return String(node.properties.alt ?? ""); + if (node.type !== "element" && node.type !== "root") return ""; + const separator = node.type === "element" && INLINE_PARENTS.has(node.tagName) ? "" : " "; const text = node.children.map(markdownNodeText).join(separator); // A thread autolink's only text is its URL. - return node.type === "link" && parseThreadLinkHref(text) !== null ? "a thread" : text; + return node.type === "element" && node.tagName === "a" && parseThreadLinkHref(text) !== null + ? "a thread" + : text; } /** Markdown as one line of the text it renders, without markup or link targets. */ export function markdownPlainText(markdown: string): string { - return markdownNodeText(markdownPreviewParser.parse(markdown)).replace(/\s+/g, " ").trim(); + return markdownNodeText(markdownTree(markdown)).replace(/\s+/g, " ").trim(); } // The tooltip shows a few lines; bound parsing work for long messages and streaming responses. function markdownMinimapPreview(markdown: string | null) { if (markdown === null) return null; - const compact = markdownNodeText(markdownPreviewParser.parse(markdown.slice(0, 1_500))) + const compact = markdownNodeText(markdownTree(markdown.slice(0, 1_500))) .replace(/\s+/g, " ") .trim(); return compact.length > 0 ? compact : null; diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index c020113815dfa..2c27cfb8d80d1 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -132,7 +132,7 @@ import { shouldShowFileExplorer, workspaceAssetResource, } from "./filePreviewMode"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { changeFileSaveSession, useFileSaveSession } from "./fileSaveSessions"; import { revisionedQuery } from "~/state/revisionedQuery"; import { diff --git a/apps/web/src/components/files/NotebookPreview.tsx b/apps/web/src/components/files/NotebookPreview.tsx index 35d0203818850..c2104ad2ddec6 100644 --- a/apps/web/src/components/files/NotebookPreview.tsx +++ b/apps/web/src/components/files/NotebookPreview.tsx @@ -2,8 +2,8 @@ import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { T, useGT, useMessages } from "gt-react"; import { useEffect, useRef, useState } from "react"; -import type { Root, RootContent } from "mdast"; import ChatMarkdown from "~/components/ChatMarkdown"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { Button } from "~/components/ui/button"; import ReadOnlySourcePreview from "./ReadOnlySourcePreview"; import DocumentPages from "./DocumentPages"; @@ -11,24 +11,7 @@ import { FileSurfaceNotice } from "./fileSurfaceChrome"; import type { OfficeWorkerResult } from "./officePreviewProtocol"; // Saved notebooks must not load URLs or turn authored links into app actions. -function inertNotebookMarkdown() { - function clean(nodes: RootContent[]): RootContent[] { - return nodes.flatMap((node): RootContent[] => { - if (node.type === "html" || node.type === "definition") return []; - if (node.type === "image" || node.type === "imageReference") - return [{ type: "text", value: node.alt ?? "" }]; - if (node.type === "link" || node.type === "linkReference") return clean(node.children); - if (node.type === "inlineCode") return [{ type: "text", value: node.value }]; - if (node.type === "code" && node.lang === "mermaid") return [{ ...node, lang: "text" }]; - if ("children" in node) node.children = clean(node.children) as typeof node.children; - return [node]; - }); - } - return (tree: Root) => { - tree.children = clean(tree.children) as Root["children"]; - }; -} -const NOTEBOOK_PLUGINS = [inertNotebookMarkdown]; +const NOTEBOOK_MARKDOWN: MarkdownExtensions = { inert: true }; function NotebookSource(props: { readonly name: string; readonly text: string }) { const [height, setHeight] = useState(Math.min(360, props.text.split("\n").length * 20 + 16)); @@ -129,7 +112,7 @@ export default function NotebookPreview(props: { text={cell.source} cwd={undefined} parseRawHtml={false} - extraRemarkPlugins={NOTEBOOK_PLUGINS} + extensions={NOTEBOOK_MARKDOWN} className="px-4 py-3" /> ) : cell.source.trim() ? ( diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 1e0fa7680c405..cbf9de56dbbb2 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -112,7 +112,7 @@ import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState"; import type { PullRequestAgentSelectionInput } from "./PullRequestCodeTab"; import { openOnHostLabel } from "./pullRequestLinkContextMenu"; import { PullRequestMarkdownContext } from "./PullRequestMarkdown"; -import { pullRequestMarkdownPlugins } from "./pullRequestMarkdown.logic"; +import { pullRequestMarkdownExtensions } from "./pullRequestMarkdown.logic"; import { PullRequestComposer } from "./PullRequestComposer"; import { PullRequestSummaryTab } from "./PullRequestSummaryTab"; import { PullRequestTimelineTab } from "./PullRequestTimelineTab"; @@ -298,7 +298,7 @@ function pullRequestMarkdownContext( threadRef: ScopedThreadRef | null, ) { return { - remarkPlugins: pullRequestMarkdownPlugins(detail), + extensions: pullRequestMarkdownExtensions(detail), lineBreaks: sourceControlClients.find(detail?.provider ?? "")?.hardLineBreaks ?? false, threadRef, repository: detail?.repository ?? null, diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx index fae5270d27123..f1cd6b6ba6708 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx @@ -24,7 +24,7 @@ async function renderBody( ) { const { repository = null, text = "first line\nsecond line", ...props } = options; const context = { - remarkPlugins: [], + extensions: {}, lineBreaks: sourceControlClients.get(host).hardLineBreaks ?? false, threadRef: null, repository, diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx index 071e8dbe45d17..82012eae8f0a7 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdown.tsx @@ -9,7 +9,7 @@ import { type ScopedThreadRef, } from "@t3tools/contracts"; import { createContext, useContext } from "react"; -import type { PluggableList } from "unified"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls"; import { cn } from "~/lib/utils"; @@ -21,7 +21,7 @@ import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequest export const PullRequestMarkdownContext = createContext<{ /** Stable per repository, so comments share one renderer and its parse cache. */ - remarkPlugins: PluggableList; + extensions: MarkdownExtensions; lineBreaks: boolean; threadRef: ScopedThreadRef | null; /** The change request's `owner/name`, which can differ from the checkout the body renders in. */ @@ -129,7 +129,7 @@ function PullRequestBodySegmentView({ threadRef={threadRef} pullRequestPanelRef={threadRef ?? listPanelRef} environmentId={environmentId} - {...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})} + {...(context ? { extensions: context.extensions } : {})} lineBreaks={lineBreaks} sourceControlMedia sourceControlMediaRepository={repository} diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx index dd4cf2f811c72..1f409d282ecc3 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx @@ -87,7 +87,7 @@ import { startDescriptionSave, type DescriptionDraft, } from "@t3tools/client-runtime/pull-request-editing"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { PullRequestMarkdown } from "./PullRequestMarkdown"; import { PullRequestCommentBody } from "./PullRequestCommentBody"; import { PullRequestMoreReplies } from "./PullRequestMoreReplies"; diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 4f25b26f3276e..3d0ae22b15017 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -1280,6 +1280,15 @@ describe("adding a remark to the chat", () => { }); expect(context?.text).toBe("octocat: This leaks the token.\n\n```html\n\n```"); + // A stray backtick before the comment opens no code span across the paragraphs. + const stray = buildPullRequestCommentContext(pullRequest, { + kind: "comment", + comment: remark( + "c2", + "Avoid `foo.\n\n\nSee `bar` and `` a ` ``.", + ), + }); + expect(stray?.text).toBe("octocat: Avoid `foo.\n\nSee `bar` and `` a ` ``."); }); it("keeps comments inside a quoted fence as code", () => { diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index 238038730b93f..d98ec3ff114ec 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -5,8 +5,9 @@ import { resolvePullRequestReviewAnchor, } from "@t3tools/shared/pullRequestAnchor"; import { stripInlineContextReferences } from "~/lib/composerContextReferences"; -import type { Nodes as MdastNodes } from "mdast"; -import { fromMarkdown } from "mdast-util-from-markdown"; +import type { Nodes } from "hast"; + +import { markdownHtmlComments, markdownTree } from "~/markdown/wordsHast"; import { sourceControlClients, type ChangeRequestTerminology, @@ -693,27 +694,18 @@ export function pagePullRequestConversationItems( function readableBody(raw: string): string | null { if (visibleBody(raw) === null) return null; const body = raw.replace(/\r\n?/gu, "\n"); - const cuts: Array<[number, number]> = []; - const visit = (node: MdastNodes) => { - if (node.type === "html" && node.position?.start.offset !== undefined) { - cuts.push([node.position.start.offset, node.position.end.offset ?? body.length]); - } - if ("children" in node) for (const child of node.children) visit(child); - }; - visit(fromMarkdown(body)); let readable = ""; let from = 0; - for (const [start, end] of cuts) { + for (const { start, end } of markdownHtmlComments(body)) { + // A comment opened inside another one ends with it. + if (start < from) continue; readable += body.slice(from, start); - // An HTML block can carry markup around its comment; only the comment itself is hidden. - const html = body.slice(start, end).replace(/|$)/gu, ""); // A line that was all comment is dropped rather than left as a blank one. const ownLine = /(?:^|\n)[ \t>]*$/u.test(readable) && /^[ \t]*(?:\n|$)/u.test(body.slice(end)); - if (ownLine && html.trim() === "") { + if (ownLine) { readable = readable.replace(/[ \t>]*$/u, ""); from = end + (/^[ \t]*\n/u.exec(body.slice(end))?.[0].length ?? 0); } else { - readable += html; from = end; } } @@ -740,11 +732,12 @@ const LINK_EXCERPT_LENGTH = 280; /** The words of a markdown body, without markup, HTML or images, for a short preview. */ function markdownExcerpt(body: string): string | null { const words: string[] = []; - const visit = (node: MdastNodes) => { - if (node.type === "text" || node.type === "inlineCode") words.push(node.value); - if (node.type !== "code" && "children" in node) for (const child of node.children) visit(child); + const visit = (node: Nodes) => { + if (node.type === "text") words.push(node.value); + if (node.type === "element" && node.tagName === "pre") return; + if ("children" in node) for (const child of node.children) visit(child); }; - visit(fromMarkdown(body)); + visit(markdownTree(body, { skipHtml: true })); // GitHub's alert marker (`> [!NOTE]`) parses as text but reads as markup. const text = words .join(" ") diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts index 1655427b2d4e9..7c4ffac84b8a5 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts @@ -1,45 +1,44 @@ -import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import type { Element, Root } from "hast"; import { describe, expect, it } from "vite-plus/test"; +import { wordsHast } from "~/markdown/wordsHast"; import { pullRequestCommentPreview, - pullRequestMarkdownPlugins, - remarkPullRequestAutolinks, + pullRequestMarkdownExtensions, } from "./pullRequestMarkdown.logic"; -type Node = { - type: string; - value?: string; - url?: string; - data?: { hProperties?: Record }; - children?: Node[]; -}; - function links(markdown: string) { - const autolinks = changeRequestReferenceAutolinker({ + const extensions = pullRequestMarkdownExtensions({ provider: "github", url: "https://github.com/team/repo/pull/8", - })!; - const tree = unified().use(remarkParse).parse(markdown) as Node; - remarkPullRequestAutolinks({ autolinks })(tree as never); - const found: Array<[string | undefined, string | undefined, unknown]> = []; - const visit = (node: Node) => { - if (node.type === "link") { - found.push([ - node.children?.[0]?.value, - node.url, - node.data?.hProperties?.["dataPullRequestAutolink"], - ]); + }); + const tree = wordsHast(markdown, { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions, + }); + const found: Array<[string, unknown, unknown]> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "a") { + const label = child.children[0]; + found.push([ + label?.type === "text" ? label.value : "", + child.properties.href, + child.properties.dataPullRequestAutolink, + ]); + } + visit(child); } - node.children?.forEach(visit); }; visit(tree); return found; } -describe("remarkPullRequestAutolinks", () => { +describe("pullRequestMarkdownExtensions", () => { it("links the host's references in prose and leaves links and code alone", () => { expect(links("Fixes #12 in **abcdef1**. [#13](https://example.com) `#14`")).toEqual([ ["#12", "https://github.com/team/repo/issues/12", "reference"], @@ -47,22 +46,25 @@ describe("remarkPullRequestAutolinks", () => { ["#13", "https://example.com", undefined], ]); }); -}); - -describe("pullRequestMarkdownPlugins", () => { it("renders GitHub emoji shortcodes in prose and leaves code literal", () => { - const processor = unified() - .use(remarkParse) - .use( - pullRequestMarkdownPlugins({ - provider: "github", - url: "https://github.com/team/repo/pull/8", - }), - ); - const tree = processor.runSync(processor.parse("Ship it :tada: :+1: `:tada:`")) as Node; - const text = (node: Node): string => - (node.type === "inlineCode" ? `\`${node.value}\`` : (node.value ?? "")) + - (node.children ?? []).map(text).join(""); + const extensions = pullRequestMarkdownExtensions({ + provider: "github", + url: "https://github.com/team/repo/pull/8", + }); + const tree = wordsHast("Ship it :tada: :+1: `:tada:`", { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions, + }); + const text = (node: Root | Element | Root["children"][number]): string => { + if (node.type === "text") return node.value; + if (node.type === "element" && node.tagName === "code") { + return `\`${node.children.map(text).join("")}\``; + } + return "children" in node ? node.children.map(text).join("") : ""; + }; expect(text(tree)).toBe("Ship it 🎉 👍 `:tada:`"); }); }); diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts index 21f3574838e06..560b6ee03fd37 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts @@ -1,130 +1,63 @@ -import { - changeRequestReferenceAutolinker, - expandGithubEmojiAliases, - resolveChangeRequestMediaUrl, -} from "@t3tools/client-runtime/pull-request-markdown"; -import { - sourceControlClients, - type ReferenceAutolink, -} from "@t3tools/client-runtime/source-control-clients"; -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-references"; +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import type { Nodes } from "hast"; -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { unified, type PluggableList } from "unified"; -export { - splitPullRequestBody, +import { + splitPullRequestBody as splitBody, type PullRequestBodySegment, } from "@t3tools/client-runtime/pull-request-markdown"; +import { + markdownReferenceDefinitions, + wordsHast, + type MarkdownExtensions, +} from "~/markdown/wordsHast"; -type MarkdownNode = { - type: string; - value?: string; - children?: MarkdownNode[]; - url?: string; - data?: unknown; -}; - -const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]); - -export function remarkPullRequestAutolinks(options: { - readonly autolinks: (text: string) => ReadonlyArray; -}) { - const visit = (node: MarkdownNode): void => { - const children = node.children; - if (children === undefined) return; - for (let index = 0; index < children.length; index += 1) { - const child = children[index]!; - if (AUTOLINK_IGNORED_TYPES.has(child.type)) continue; - if (child.type !== "text" || child.value === undefined) { - visit(child); - continue; - } - const value = child.value; - const links = options.autolinks(value); - if (links.length === 0) continue; - const replacements: MarkdownNode[] = []; - let start = 0; - for (const link of links) { - if (start < link.index) { - replacements.push({ type: "text", value: value.slice(start, link.index) }); - } - replacements.push({ - type: "link", - url: link.url, - data: { hProperties: { dataPullRequestAutolink: link.kind } }, - children: [{ type: "text", value: link.label }], - }); - start = link.index + link.text.length; - } - if (start < value.length) replacements.push({ type: "text", value: value.slice(start) }); - children.splice(index, 1, ...replacements); - index += replacements.length - 1; - } - }; - return (tree: MarkdownNode) => visit(tree); -} +export type { PullRequestBodySegment }; -function remarkChangeRequestMediaUrls(options: { readonly changeRequestUrl: string }) { - const visit = (node: MarkdownNode): void => { - if ((node.type === "image" || node.type === "definition") && node.url !== undefined) { - node.url = resolveChangeRequestMediaUrl(node.url, options.changeRequestUrl); - } - node.children?.forEach(visit); - }; - return (tree: MarkdownNode) => visit(tree); +export function splitPullRequestBody(body: string): ReadonlyArray { + return splitBody(body, markdownReferenceDefinitions); } -/** GitHub renders `:alias:` emoji in prose; code keeps them, being `inlineCode`/`code`, not `text`. */ -function remarkGithubEmoji() { - const visit = (node: MarkdownNode): void => { - if (node.type === "text" && node.value !== undefined) - node.value = expandGithubEmojiAliases(node.value); - node.children?.forEach(visit); - }; - return (tree: MarkdownNode) => visit(tree); -} - -const NO_PLUGINS: PluggableList = []; -const markdownPlugins = new Map(); +const NO_EXTENSIONS: MarkdownExtensions = {}; +const markdownExtensions = new Map(); /** - * One plugin list per repository, so every comment of a pull request shares one markdown + * One extension object per repository, so every comment of a pull request shares one markdown * renderer and its parse cache instead of parsing again on each render. */ -export function pullRequestMarkdownPlugins( +export function pullRequestMarkdownExtensions( changeRequest: { readonly provider: string; readonly url: string } | null, -): PluggableList { - if (changeRequest === null) return NO_PLUGINS; +): MarkdownExtensions { + if (changeRequest === null) return NO_EXTENSIONS; const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link .repositoryUrl; - if (repositoryUrl === undefined) return NO_PLUGINS; + if (repositoryUrl === undefined) return NO_EXTENSIONS; const key = `${changeRequest.provider}\u0000${repositoryUrl}`; - let plugins = markdownPlugins.get(key); - if (plugins === undefined) { - const autolinks = changeRequestReferenceAutolinker(changeRequest); - plugins = [[remarkChangeRequestMediaUrls, { changeRequestUrl: repositoryUrl }]]; - if (changeRequest.provider === "github") plugins.push(remarkGithubEmoji); - if (autolinks) plugins.push([remarkPullRequestAutolinks, { autolinks }]); - markdownPlugins.set(key, plugins); + let extensions = markdownExtensions.get(key); + if (extensions === undefined) { + extensions = { + changeRequest: { + repositoryUrl, + autolinks: changeRequestReferenceAutolinker(changeRequest), + }, + githubEmoji: changeRequest.provider === "github", + }; + markdownExtensions.set(key, extensions); } - return plugins; + return extensions; } -const commentPreviewProcessor = (plugins: PluggableList) => - unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(plugins) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(CHAT_MARKDOWN_REHYPE_PLUGINS) - .freeze(); -const commentPreview = commentPreviewProcessor(NO_PLUGINS); -const githubCommentPreview = commentPreviewProcessor([remarkGithubEmoji]); +const PREVIEW_MARKDOWN = { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions: NO_EXTENSIONS, +}; +const GITHUB_PREVIEW_MARKDOWN = { + ...PREVIEW_MARKDOWN, + extensions: { githubEmoji: true }, +}; const PREVIEW_BLOCK_TAGS = new Set([ "blockquote", @@ -164,7 +97,6 @@ function commentPreviewText(node: Nodes): string { } export function pullRequestCommentPreview(body: string, provider: string): string { - const processor = provider === "github" ? githubCommentPreview : commentPreview; - const tree = processor.runSync(processor.parse(body), body); - return commentPreviewText(tree).replace(/\s+/gu, " ").trim(); + const options = provider === "github" ? GITHUB_PREVIEW_MARKDOWN : PREVIEW_MARKDOWN; + return commentPreviewText(wordsHast(body, options)).replace(/\s+/gu, " ").trim(); } diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index d91d6da4a42d7..4252fccc9c7d0 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -512,6 +512,7 @@ export const SETTINGS_SEARCH_ITEMS = [ targetId: "boring-sidebar", searchTerms: [msg("beta boring sidebar folder rows multiline branch pull request details")], }, + { id: "tool-call-visibility", title: msg("Tool calls in chat"), diff --git a/apps/web/src/components/ui/shared-tooltip.tsx b/apps/web/src/components/ui/shared-tooltip.tsx new file mode 100644 index 0000000000000..0858fa656e6bb --- /dev/null +++ b/apps/web/src/components/ui/shared-tooltip.tsx @@ -0,0 +1,262 @@ +import { + cloneElement, + createContext, + use, + useEffect, + useId, + useRef, + useState, + type FocusEvent, + type PointerEvent, + type ReactElement, + type ReactNode, +} from "react"; + +import { Tooltip, TooltipPopup, TooltipTrigger, useTooltipScrollTracker } from "./tooltip"; + +// Base UI's tooltip timing: open after a rest, reopen at once right after another closed. +const OPEN_DELAY_MS = 600; +const REOPEN_WINDOW_MS = 400; +// Time to travel from the trigger into a hoverable popup. +const CLOSE_GRACE_MS = 100; + +interface SharedTooltipContent { + readonly render: () => ReactNode; + /** Comparable key that changes whenever `render()` output changes while open. */ + readonly contentKey?: unknown; + readonly side?: "top" | "bottom" | "left" | "right"; + readonly variant?: "default" | "glass" | "code"; +} + +interface SharedTooltipState extends SharedTooltipContent { + readonly anchor: HTMLElement; + readonly open: boolean; +} + +interface SharedTooltipApi { + show(anchor: HTMLElement, content: SharedTooltipContent, immediate: boolean): void; + refresh(anchor: HTMLElement, content: SharedTooltipContent): void; + hide(anchor: HTMLElement): void; + /** A press closes it at once, as Base UI's closeOnClick does. */ + dismiss(anchor: HTMLElement): void; + holdOpen(): void; +} + +function setAriaDescribedBy(element: HTMLElement, id: string, present: boolean) { + const tokens = (element.getAttribute("aria-describedby") ?? "").split(/\s+/).filter(Boolean); + const next = present + ? tokens.includes(id) + ? tokens + : [...tokens, id] + : tokens.filter((token) => token !== id); + if (next.length > 0) element.setAttribute("aria-describedby", next.join(" ")); + else element.removeAttribute("aria-describedby"); +} + +const SharedTooltipContext = createContext(null); + +/** + * One tooltip for many triggers: a long message would otherwise mount a Base UI tooltip per + * link and file chip, and almost none of them are ever hovered. + */ +export function SharedTooltipProvider({ children }: { children: ReactNode }) { + const popupId = useId(); + const [state, setState] = useState(null); + const timer = useRef | null>(null); + const pending = useRef(null); + const lastClosedAt = useRef(0); + const current = useRef(null); + + const commit = (next: SharedTooltipState | null) => { + current.current = next; + setState(next); + }; + const clearTimer = () => { + if (timer.current !== null) clearTimeout(timer.current); + timer.current = null; + pending.current = null; + }; + const [api] = useState(() => ({ + show(anchor, content, immediate) { + clearTimer(); + const open = current.current?.open === true; + const reopen = performance.now() - lastClosedAt.current < REOPEN_WINDOW_MS; + if (immediate || open || reopen) { + commit({ ...content, anchor, open: true }); + return; + } + pending.current = { ...content, anchor, open: true }; + timer.current = setTimeout(() => { + const next = pending.current; + pending.current = null; + if (next) commit(next); + }, OPEN_DELAY_MS); + }, + refresh(anchor, content) { + if (pending.current?.anchor === anchor) { + pending.current = { ...pending.current, ...content }; + } + const active = current.current; + if (!active || active.anchor !== anchor) return; + if ( + active.contentKey === content.contentKey && + active.side === content.side && + active.variant === content.variant + ) { + return; + } + commit({ ...active, ...content }); + }, + hide(anchor) { + if (current.current && current.current.anchor !== anchor) { + clearTimer(); + return; + } + clearTimer(); + timer.current = setTimeout(() => { + if (current.current?.open) lastClosedAt.current = performance.now(); + if (current.current) commit({ ...current.current, open: false }); + }, CLOSE_GRACE_MS); + }, + dismiss(anchor) { + clearTimer(); + if (current.current?.anchor !== anchor) return; + if (current.current.open) lastClosedAt.current = 0; + commit({ ...current.current, open: false }); + }, + holdOpen() { + clearTimer(); + }, + })); + + const activeAnchor = state?.open ? state.anchor : null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links the active trigger DOM element to the shared tooltip popup via aria-describedby + useEffect(() => { + if (!activeAnchor) return; + setAriaDescribedBy(activeAnchor, popupId, true); + return () => setAriaDescribedBy(activeAnchor, popupId, false); + }, [activeAnchor, popupId]); + + return ( + + {children} + {state ? ( + { + if (!open) api.hide(state.anchor); + }} + > + api.holdOpen()} + onMouseLeave={() => api.hide(state.anchor)} + > + {state.render()} + + + ) : null} + + ); +} + +export interface SharedTooltipTriggerProps { + onPointerEnter: (event: PointerEvent) => void; + onPointerLeave: (event: PointerEvent) => void; + onFocus: (event: FocusEvent) => void; + onBlur: (event: FocusEvent) => void; + onPointerDown: (event: PointerEvent) => void; +} + +/** Props that show `content` on the shared tooltip, or null outside a SharedTooltipProvider. */ +export function useSharedTooltip(content: SharedTooltipContent): SharedTooltipTriggerProps | null { + const api = use(SharedTooltipContext); + const scrollTracker = useTooltipScrollTracker(); + const anchorRef = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes an open shared tooltip when its trigger's label changes + useEffect(() => { + if (api && anchorRef.current) api.refresh(anchorRef.current, content); + }, [api, content]); + if (!api) return null; + return { + // Touch never opens it, as Base UI's mouseOnly trigger; taps also send compatibility mouse events. + onPointerEnter: (event) => { + if (event.pointerType === "touch") return; + const trigger = event.currentTarget; + anchorRef.current = trigger; + api.show(trigger, content, false); + // Scrolling the timeline closes it, as it does a TooltipTrigger's. + scrollTracker?.hover(trigger, api, () => api.dismiss(trigger)); + }, + onPointerLeave: (event) => api.hide(event.currentTarget), + // Keyboard focus shows it at once, as Base UI does. + onFocus: (event) => { + if (event.currentTarget.matches(":focus-visible")) { + anchorRef.current = event.currentTarget; + api.show(event.currentTarget, content, true); + } + }, + onBlur: (event) => api.hide(event.currentTarget), + onPointerDown: (event) => api.dismiss(event.currentTarget), + }; +} + +type Handlers = Partial void>>; + +/** The trigger's own handlers run first, then the shared tooltip's. */ +export function withSharedTooltip( + element: ReactElement, + tooltip: SharedTooltipTriggerProps, + children?: ReactNode, +): ReactElement { + const own = element.props as Handlers; + const merged: Record void> = {}; + for (const key of Object.keys(tooltip) as Array) { + const shared = tooltip[key] as (event: never) => void; + const mine = own[key]; + merged[key] = mine + ? (event) => { + mine(event); + shared(event); + } + : shared; + } + return children === undefined + ? cloneElement(element, merged as Partial) + : cloneElement(element, merged as Partial, children); +} + +/** A tooltip on `render`: the shared one inside a SharedTooltipProvider, Base UI's otherwise. */ +export function SharedTooltipTrigger({ + render, + children, + label, + side = "top", + variant, +}: { + render: ReactElement; + children?: ReactNode; + label: ReactNode; + side?: SharedTooltipContent["side"]; + variant?: SharedTooltipContent["variant"]; +}) { + const tooltip = useSharedTooltip({ + render: () => label, + contentKey: label, + side, + ...(variant ? { variant } : {}), + }); + if (tooltip) return withSharedTooltip(render, tooltip, children); + return ( + + {children} + + {label} + + + ); +} diff --git a/apps/web/src/components/ui/tooltip.browser.test.tsx b/apps/web/src/components/ui/tooltip.browser.test.tsx index 24d76784e8a5a..bcb62ee2fdaf0 100644 --- a/apps/web/src/components/ui/tooltip.browser.test.tsx +++ b/apps/web/src/components/ui/tooltip.browser.test.tsx @@ -3,41 +3,114 @@ import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { render } from "../../../test/render"; +import { SharedTooltipProvider, SharedTooltipTrigger } from "./shared-tooltip"; import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "./tooltip"; +function TimelineAction({ shared }: { shared: boolean }) { + if (shared) { + return ( + + }> + Timeline action + + + ); + } + return ( + + Timeline action + Description + + ); +} + it.each([ - { focus: "mouse", keptOpen: false }, - { focus: "keyboard", keptOpen: true }, -])("scrolling with a $focus-focused hovered trigger keeps it open: $keptOpen", async (c) => { - const onScroll = vi.fn(); + { shared: false, focus: "mouse", keptOpen: false }, + { shared: false, focus: "keyboard", keptOpen: true }, + { shared: true, focus: "mouse", keptOpen: false }, + { shared: true, focus: "keyboard", keptOpen: true }, +])( + "scrolling with a $focus-focused hovered trigger (shared: $shared) keeps it open: $keptOpen", + async (c) => { + const onScroll = vi.fn(); + await using screen = await render( + + +
+ , + ); + const trigger = screen.getByRole("button", { name: "Timeline action" }); + if (c.focus === "mouse") { + // A press closes the tooltip; hovering again reopens it with mouse focus kept. + await userEvent.click(trigger); + await userEvent.unhover(trigger); + } else { + await userEvent.keyboard("{Tab}"); + } + await userEvent.hover(trigger); + await expect.element(trigger).toHaveFocus(); + await expect.element(page.getByText("Description")).toBeVisible(); + + // One pixel keeps the pointer over the trigger, so only the scroll can close it. + screen.getByTestId("timeline").element().scrollTop = 1; + await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + + if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); + else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); + }, +); + +it("refreshes an open shared tooltip's label and links aria-describedby on focus", async () => { await using screen = await render( - - - Timeline action - Description - -
- , + + }> + Copy + + , ); - const trigger = screen.getByRole("button", { name: "Timeline action" }); - if (c.focus === "mouse") { - // A press closes the tooltip; hovering again reopens it with mouse focus kept. - await userEvent.click(trigger); - await userEvent.unhover(trigger); - } else { - await userEvent.keyboard("{Tab}"); - } - await userEvent.hover(trigger); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.keyboard("{Tab}"); await expect.element(trigger).toHaveFocus(); - await expect.element(page.getByText("Description")).toBeVisible(); + const popup = page.getByText("Copy code"); + await expect.element(popup).toBeVisible(); + const popupId = trigger.element().getAttribute("aria-describedby"); + expect(popupId).toBeTruthy(); + expect(document.getElementById(popupId!)?.textContent).toBe("Copy code"); - screen.getByTestId("timeline").element().scrollTop = 20; - await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copied")).toBeVisible(); + + await userEvent.keyboard("{Tab}"); + await vi.waitFor(() => expect(trigger.element().getAttribute("aria-describedby")).toBeNull()); +}); - if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); - else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); +it("refreshes a pending shared tooltip if its label changes during the open delay", async () => { + await using screen = await render( + + }> + Copy + + , + ); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.hover(trigger); + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copy code")).toBeVisible(); + expect(page.getByText("Copied").query()).toBeNull(); }); diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx index 577aa48da87fa..e47a6b8d13afe 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/web/src/components/ui/tooltip.tsx @@ -21,13 +21,13 @@ type TooltipActionsRef = RefObject; // The compiler freezes context values; update hovered tooltips through calls instead of shared ref writes. function createTooltipHoverTracker() { - let hovered: { trigger: HTMLElement; actionsRef: TooltipActionsRef } | null = null; + let hovered: { trigger: HTMLElement; owner: object; close: () => void } | null = null; return { - hover(trigger: HTMLElement, actionsRef: TooltipActionsRef) { - hovered = { trigger, actionsRef }; + hover(trigger: HTMLElement, owner: object, close: () => void) { + hovered = { trigger, owner, close }; }, - release(actionsRef: TooltipActionsRef) { - if (hovered?.actionsRef === actionsRef) hovered = null; + release(owner: object) { + if (hovered?.owner === owner) hovered = null; }, dismissUnfocused() { const tooltip = hovered; @@ -37,8 +37,7 @@ function createTooltipHoverTracker() { return; } hovered = null; - // Base UI also cancels delayed hover opens through this action. - tooltip.actionsRef.current?.close(); + tooltip.close(); }, }; } @@ -96,7 +95,8 @@ function TooltipTrigger(props: TooltipPrimitive.Trigger.Props) { {...props} onMouseEnter={(event) => { props.onMouseEnter?.(event); - tracker.hover(event.currentTarget, actionsRef); + // Base UI also cancels delayed hover opens through this action. + tracker.hover(event.currentTarget, actionsRef, () => actionsRef.current?.close()); }} /> ); @@ -161,4 +161,14 @@ function TooltipPopup({ ); } -export { TooltipProvider, Tooltip, TooltipTrigger, TooltipPopup, TooltipScrollDismissArea }; +/** The enclosing TooltipScrollDismissArea's tracker, for triggers that bypass TooltipTrigger. */ +const useTooltipScrollTracker = () => use(TooltipScrollContext); + +export { + TooltipProvider, + Tooltip, + TooltipTrigger, + TooltipPopup, + TooltipScrollDismissArea, + useTooltipScrollTracker, +}; diff --git a/apps/web/src/composer-editor-mentions.ts b/apps/web/src/composer-editor-mentions.ts index 7f3e93b821488..6608d3b2a0439 100644 --- a/apps/web/src/composer-editor-mentions.ts +++ b/apps/web/src/composer-editor-mentions.ts @@ -7,6 +7,7 @@ import { composerMathRanges, type ComposerInlineToken, } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "~/markdown/wordsHast"; export type ComposerPromptSegment = | { @@ -89,7 +90,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray !taken.some((range) => mention.start < range.end && mention.end > range.start), @@ -98,7 +99,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray = []; for (const formula of formulas) { diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index c7095b8536469..92a2fa11cf7f2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -3694,7 +3694,6 @@ "7c1923203049d602": "Code kopieren", "637817e4ff79c90e": "Aktionen für Codeblock", "ebf3a2b1e314aa5f": "Im Terminal ausführen", - "fe219642547fa0bf": "Im Terminal ausführen", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Vollständiger Pfad", "f37e7d36b51c5b28": "Relativen Pfad kopieren", @@ -3706,10 +3705,6 @@ "4967584e8d0fb1c2": "Medienvorschau", "67589dd912eacb7c": "Im integrierten Browser öffnen", "a3c98d4c4b24cecb": "Dateioptionen für {label}", - "b4fe8a076e9fd2f8": "Abgesetzte Formel", - "085d1407e8c92cce": "Formel im Text", - "a2ef393fa7b48ae8": "Abgesetzte Formel scrollen", - "e94685ea5642e088": "Formel im Text scrollen", "3a04583c8500e23d": "Diagramm anzeigen", "16d64f650840fe06": "Code anzeigen", "6d329f7d3a50c7e7": "Tabelle kopieren", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2ff8148bb7329..b174085c87c95 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copy code", "637817e4ff79c90e": "Code block actions", "ebf3a2b1e314aa5f": "Run in terminal", - "fe219642547fa0bf": "Run in terminal", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Full path", "f37e7d36b51c5b28": "Copy relative path", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Preview media", "67589dd912eacb7c": "Open in integrated browser", "a3c98d4c4b24cecb": "File options for {label}", - "b4fe8a076e9fd2f8": "Display equation", - "085d1407e8c92cce": "Inline equation", - "a2ef393fa7b48ae8": "Scroll display equation", - "e94685ea5642e088": "Scroll inline equation", "3a04583c8500e23d": "Show diagram", "16d64f650840fe06": "Show code", "6d329f7d3a50c7e7": "Copy table", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 78c68c4c0dc2f..b12f6e7f0dc32 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Acciones del bloque de código", "ebf3a2b1e314aa5f": "Ejecutar en la terminal", - "fe219642547fa0bf": "Ejecutar en la terminal", "122a8512abc51180": "Detalles", "58c38c65c2783c5d": "Ruta completa", "f37e7d36b51c5b28": "Copiar ruta relativa", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Vista previa del contenido", "67589dd912eacb7c": "Abrir en el navegador integrado", "a3c98d4c4b24cecb": "Opciones de archivo de {label}", - "b4fe8a076e9fd2f8": "Ecuación en bloque", - "085d1407e8c92cce": "Ecuación en línea", - "a2ef393fa7b48ae8": "Desplazar la ecuación en bloque", - "e94685ea5642e088": "Desplazar la ecuación en línea", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabla", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 873767a296ba5..c5f7562a38e7d 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copier le code", "637817e4ff79c90e": "Actions du bloc de code", "ebf3a2b1e314aa5f": "Exécuter dans le terminal", - "fe219642547fa0bf": "Exécuter dans le terminal", "122a8512abc51180": "Détails", "58c38c65c2783c5d": "Chemin complet", "f37e7d36b51c5b28": "Copier le chemin relatif", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Aperçu du média", "67589dd912eacb7c": "Ouvrir dans le navigateur intégré", "a3c98d4c4b24cecb": "Options du fichier {label}", - "b4fe8a076e9fd2f8": "Équation en bloc", - "085d1407e8c92cce": "Équation en ligne", - "a2ef393fa7b48ae8": "Faire défiler l’équation en bloc", - "e94685ea5642e088": "Faire défiler l’équation en ligne", "3a04583c8500e23d": "Afficher le diagramme", "16d64f650840fe06": "Afficher le code", "6d329f7d3a50c7e7": "Copier le tableau", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 69ac82ad8a247..a0a71c4814184 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -3688,7 +3688,6 @@ "7c1923203049d602": "コードをコピー", "637817e4ff79c90e": "コードブロックの操作", "ebf3a2b1e314aa5f": "ターミナルで実行", - "fe219642547fa0bf": "ターミナルで実行", "122a8512abc51180": "詳細", "58c38c65c2783c5d": "フルパス", "f37e7d36b51c5b28": "相対パスをコピー", @@ -3700,10 +3699,6 @@ "4967584e8d0fb1c2": "メディアをプレビュー", "67589dd912eacb7c": "統合ブラウザーで開く", "a3c98d4c4b24cecb": "{label} のファイルオプション", - "b4fe8a076e9fd2f8": "ディスプレイ数式", - "085d1407e8c92cce": "インライン数式", - "a2ef393fa7b48ae8": "ディスプレイ数式をスクロール", - "e94685ea5642e088": "インライン数式をスクロール", "3a04583c8500e23d": "図を表示", "16d64f650840fe06": "コードを表示", "6d329f7d3a50c7e7": "表をコピー", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 10782b2ca6166..ba0da8c82495a 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -3688,7 +3688,6 @@ "7c1923203049d602": "코드 복사", "637817e4ff79c90e": "코드 블록 작업", "ebf3a2b1e314aa5f": "터미널에서 실행", - "fe219642547fa0bf": "터미널에서 실행", "122a8512abc51180": "세부 정보", "58c38c65c2783c5d": "전체 경로", "f37e7d36b51c5b28": "상대 경로 복사", @@ -3700,10 +3699,6 @@ "4967584e8d0fb1c2": "미디어 미리 보기", "67589dd912eacb7c": "통합 브라우저에서 열기", "a3c98d4c4b24cecb": "{label} 파일 옵션", - "b4fe8a076e9fd2f8": "블록 수식", - "085d1407e8c92cce": "인라인 수식", - "a2ef393fa7b48ae8": "블록 수식 스크롤", - "e94685ea5642e088": "인라인 수식 스크롤", "3a04583c8500e23d": "다이어그램 표시", "16d64f650840fe06": "코드 표시", "6d329f7d3a50c7e7": "표 복사", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2b9e2b9b381..66d4f0b457e35 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Ações do bloco de código", "ebf3a2b1e314aa5f": "Executar no terminal", - "fe219642547fa0bf": "Executar no terminal", "122a8512abc51180": "Detalhes", "58c38c65c2783c5d": "Caminho completo", "f37e7d36b51c5b28": "Copiar caminho relativo", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Pré-visualizar mídia", "67589dd912eacb7c": "Abrir no navegador integrado", "a3c98d4c4b24cecb": "Opções do arquivo {label}", - "b4fe8a076e9fd2f8": "Equação em destaque", - "085d1407e8c92cce": "Equação em linha", - "a2ef393fa7b48ae8": "Rolar a equação em destaque", - "e94685ea5642e088": "Rolar a equação em linha", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabela", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0ecadaba9ded1..879d2684c207f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Копировать код", "637817e4ff79c90e": "Действия с блоком кода", "ebf3a2b1e314aa5f": "Выполнить в терминале", - "fe219642547fa0bf": "Выполнить в терминале", "122a8512abc51180": "Подробности", "58c38c65c2783c5d": "Полный путь", "f37e7d36b51c5b28": "Копировать относительный путь", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Предпросмотр медиа", "67589dd912eacb7c": "Открыть во встроенном браузере", "a3c98d4c4b24cecb": "Параметры файла {label}", - "b4fe8a076e9fd2f8": "Формула в отдельной строке", - "085d1407e8c92cce": "Формула в строке", - "a2ef393fa7b48ae8": "Прокрутить формулу", - "e94685ea5642e088": "Прокрутить формулу в строке", "3a04583c8500e23d": "Показать диаграмму", "16d64f650840fe06": "Показать код", "6d329f7d3a50c7e7": "Копировать таблицу", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 1c01b1112768f..3de08f6ce6252 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -3693,7 +3693,6 @@ "7c1923203049d602": "Kopiera kod", "637817e4ff79c90e": "Åtgärder för kodblock", "ebf3a2b1e314aa5f": "Kör i terminalen", - "fe219642547fa0bf": "Kör i terminalen", "122a8512abc51180": "Detaljer", "58c38c65c2783c5d": "Fullständig sökväg", "f37e7d36b51c5b28": "Kopiera relativ sökväg", @@ -3705,10 +3704,6 @@ "4967584e8d0fb1c2": "Förhandsvisa media", "67589dd912eacb7c": "Öppna i den integrerade webbläsaren", "a3c98d4c4b24cecb": "Filalternativ för {label}", - "b4fe8a076e9fd2f8": "Fristående ekvation", - "085d1407e8c92cce": "Ekvation i texten", - "a2ef393fa7b48ae8": "Rulla fristående ekvation", - "e94685ea5642e088": "Rulla ekvation i texten", "3a04583c8500e23d": "Visa diagram", "16d64f650840fe06": "Visa kod", "6d329f7d3a50c7e7": "Kopiera tabell", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 43790340d1167..0193a3db09720 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -3698,7 +3698,6 @@ "7c1923203049d602": "复制代码", "637817e4ff79c90e": "代码块操作", "ebf3a2b1e314aa5f": "在终端中运行", - "fe219642547fa0bf": "在终端中运行", "122a8512abc51180": "详情", "58c38c65c2783c5d": "完整路径", "f37e7d36b51c5b28": "复制相对路径", @@ -3710,10 +3709,6 @@ "4967584e8d0fb1c2": "预览媒体", "67589dd912eacb7c": "在内置浏览器中打开", "a3c98d4c4b24cecb": "{label} 的文件选项", - "b4fe8a076e9fd2f8": "独立公式", - "085d1407e8c92cce": "行内公式", - "a2ef393fa7b48ae8": "滚动查看独立公式", - "e94685ea5642e088": "滚动查看行内公式", "3a04583c8500e23d": "显示图表", "16d64f650840fe06": "显示代码", "6d329f7d3a50c7e7": "复制表格", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 4ba107059f2b7..2b19b90cc28e3 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1887,10 +1887,6 @@ code { margin: 0.65rem 0; } -.chat-markdown-math-display .katex-display { - margin: 0; -} - :is(.chat-markdown, .composer-tiptap) h1, :is(.chat-markdown, .composer-tiptap) h2, :is(.chat-markdown, .composer-tiptap) h3, @@ -2312,6 +2308,15 @@ code { overflow-wrap: break-word; } +.chat-markdown [data-markdown-math] { + font-weight: normal; + font-style: normal; +} + +.chat-markdown [data-markdown-math] > svg { + font-size: 1.21em; +} + /* Formula cells keep their natural width and scroll with the table. */ .chat-markdown :is(th, td):has([data-markdown-math]) { max-width: none; diff --git a/apps/web/src/markdown-clipboard.test.ts b/apps/web/src/markdown-clipboard.test.ts index 1b0aa804a8437..7a50785c726c7 100644 --- a/apps/web/src/markdown-clipboard.test.ts +++ b/apps/web/src/markdown-clipboard.test.ts @@ -11,19 +11,27 @@ import { collectAssistantCitations, serializeAssistantCitation, } from "@t3tools/shared/assistantCitations"; -import { markdownMathRanges, parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; +import type { Element as HastElement, ElementContent, Root } from "hast"; -import { unified } from "unified"; -import remarkParse from "remark-parse"; -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_USER_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; +import { markdownTree } from "./markdown/wordsHast"; -const userMarkdown = unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(CHAT_USER_MARKDOWN_REMARK_PLUGINS); +// Copied Markdown read back as the chat reads it, to check it says what was copied. +const elementsOf = (node: Root | HastElement) => + (node.children as ElementContent[]).filter( + (child): child is HastElement => child.type === "element", + ); +const textOf = (node: ElementContent): string => + node.type === "text" + ? node.value + : node.type === "element" + ? node.children.map(textOf).join("") + : ""; +const readBack = (markdown: string, options?: Parameters[1]) => + elementsOf(markdownTree(markdown, options))[0]!; +// A user message's reading: a single `~` stays text. +const readUserBack = (markdown: string) => readBack(markdown, { singleTilde: false }); +const inline = (node: ElementContent) => + node.type === "element" ? [node.tagName, textOf(node)] : [node.type, textOf(node)]; const TEXT_NODE = 3; const ELEMENT_NODE = 1; @@ -223,10 +231,10 @@ describe("serializeRenderedMarkdownFragment", () => { new FakeText(" here."), ), ); - const paragraph = parseMarkdownWithMath(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children.find((child) => child.type === "inlineCode")?.value).toBe(value); + const paragraph = readBack(serializeRenderedMarkdownFragment(asNode(container))); + const code = elementsOf(paragraph).find((child) => child.tagName === "code"); + expect(paragraph.tagName).toBe("p"); + expect(code && textOf(code)).toBe(value); }); it.each([ @@ -238,28 +246,24 @@ describe("serializeRenderedMarkdownFragment", () => { String.raw`before\ after\ end`, ])("copies prose that parses back unchanged: %s", (value) => { const container = new FakeElement("DIV").append(new FakeText(value)); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ type: "paragraph", children: [{ type: "text", value }] }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.tagName).toBe("p"); + expect(paragraph.children.map(inline)).toEqual([["text", value]]); }); it.each([ - ["*", "EM", "word", "emphasis"], - ["\\", "CODE", "value", "inlineCode"], - ])("keeps a text edge %j beside %s", (edge, tag, value, type) => { + ["*", "EM", "word"], + ["\\", "CODE", "value"], + ])("keeps a text edge %j beside %s", (edge, tag, value) => { const container = new FakeElement("DIV").append( new FakeText(edge), new FakeElement(tag).append(new FakeText(value)), ); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ - type: "paragraph", - children: [ - { type: "text", value: edge }, - type === "inlineCode" ? { type, value } : { type, children: [{ type: "text", value }] }, - ], - }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.children.map(inline)).toEqual([ + ["text", edge], + [tag.toLowerCase(), value], + ]); }); it("copies email links with their address and drops in-app destinations", () => { @@ -288,10 +292,10 @@ describe("serializeRenderedMarkdownFragment", () => { expect(copied).toBe( "Write to support@example.com, [Support](mailto:support@example.com?subject=Help), [Support](mailto:support@example.com?subject=Help\\)) or the thread.", ); - const paragraph = parseMarkdownWithMath(copied).children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); expect( - paragraph.children.filter((child) => child.type === "link").map((link) => link.url), + elementsOf(readBack(copied)) + .filter((child) => child.tagName === "a") + .map((link) => link.properties.href), ).toEqual([ "mailto:support@example.com", "mailto:support@example.com?subject=Help", @@ -312,12 +316,14 @@ describe("serializeRenderedMarkdownFragment", () => { ])("keeps the link label and destination: %s", (label, href) => { const anchor = new FakeElement("A", [], { href }).append(new FakeText(label)); const container = new FakeElement("DIV").append(anchor); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children).toMatchObject([ - { type: "link", url: href, children: [{ type: "text", value: label }] }, - ]); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect( + paragraph.children.map((child) => + child.type === "element" + ? [child.tagName, decodeURI(String(child.properties.href)), textOf(child)] + : [child.type, textOf(child)], + ), + ).toEqual([["a", href, label]]); }); it("copies alert and insight callouts as their Markdown instead of the rendered label", () => { @@ -484,31 +490,25 @@ describe("copying rendered Markdown tables", () => { ); const markdown = serializeTableElementToMarkdown(table as unknown as Element); - const tree = parseMarkdownWithMath(markdown); - const parsed = tree.children[0]; - if (parsed?.type !== "table") throw new Error("Expected a table"); - expect(parsed.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2, 2]); - expect(markdownMathRanges(markdown, tree).map((formula) => formula.tex)).toEqual([ - "|x|", - "\\|x\\|", - "|y|", - "|z|", - ]); - expect(parsed.children[1]?.children[1]?.children).toMatchObject([ - { type: "text", value: "*a* | ~~b~~" }, - ]); - expect(parsed.children[4]?.children[1]?.children).toMatchObject([ - { type: "text", value: "> c | d" }, - ]); - const [, , codeRow, linkRow] = parsed.children; - expect(codeRow?.children[1]?.children[0]).toMatchObject({ - type: "inlineCode", - value: "\\(c|d\\)", - }); - expect(linkRow?.children[0]?.children[0]).toMatchObject({ - type: "link", - url: "https://example.com/?q=a|b", - }); + const parsed = readBack(markdown, { math: true }); + expect(parsed.tagName).toBe("table"); + const rows = elementsOf(parsed).flatMap((section) => elementsOf(section)); + const cells = rows.map((row) => elementsOf(row)); + expect(cells.map((row) => row.length)).toEqual([2, 2, 2, 2, 2]); + const formulas: string[] = []; + const visit = (node: HastElement) => { + if (node.tagName === "svg") formulas.push(String(node.properties.ariaLabel)); + else elementsOf(node).forEach(visit); + }; + visit(parsed); + expect(formulas).toEqual(["|x|", "\\|x\\|", "|y|", "|z|"]); + expect(textOf(cells[1]![1]!)).toBe("*a* | ~~b~~"); + expect(textOf(cells[4]![1]!).trim()).toBe("> c | d"); + expect(inline(cells[2]![1]!.children[0]!)).toEqual(["code", "\\(c|d\\)"]); + const link = cells[3]![0]!.children[0]!; + expect(link.type === "element" && decodeURI(String(link.properties.href))).toBe( + "https://example.com/?q=a|b", + ); }); it("copies code and diagrams in cells without markers or unescaped pipes", () => { diff --git a/apps/web/src/markdown-clipboard.ts b/apps/web/src/markdown-clipboard.ts index 7421dbadd4bae..39ef90b2ec19a 100644 --- a/apps/web/src/markdown-clipboard.ts +++ b/apps/web/src/markdown-clipboard.ts @@ -1,4 +1,4 @@ -import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownWindowsPaths"; +import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownLinks"; const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]); const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"]; @@ -428,7 +428,7 @@ export function serializeTableElementToMarkdown(table: Element): string { return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim(); } -// The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops +// The wrapper wordsHast puts on every formula it renders. The sanitizer drops // the attribute from authored HTML. const MATH_SELECTOR = "[data-markdown-math]"; diff --git a/apps/web/src/markdown-incremental.test.tsx b/apps/web/src/markdown-incremental.test.tsx deleted file mode 100644 index 3682deb281fa9..0000000000000 --- a/apps/web/src/markdown-incremental.test.tsx +++ /dev/null @@ -1,135 +0,0 @@ -import { CHAT_MARKDOWN_REHYPE_PLUGINS } from "@t3tools/shared/markdownPipeline"; -import type { Root } from "mdast"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkGfm from "remark-gfm"; -import type { Plugin } from "unified"; -import { describe, expect, it } from "vite-plus/test"; - -import { remarkCodexDirectives } from "@t3tools/shared/codexMarkdownDirectives"; -import { remarkGithubAlerts } from "@t3tools/shared/markdownGithubAlerts"; -import { createIncrementalMarkdownPlugin } from "./markdown-incremental"; -import { remarkNormalizeListItemIndentation } from "@t3tools/shared/markdownListIndentation"; - -function render(source: string, incremental?: Plugin<[], Root>, parsedSources?: string[]) { - let tree: Root | undefined; - const observeParsing: Plugin<[], Root> = function () { - const original = this.parser; - if (original) { - this.parser = (text, file) => { - parsedSources?.push(text); - return original(text, file); - }; - } - }; - const capture: Plugin<[], Root> = () => (root) => { - tree = structuredClone(root); - }; - const html = renderToStaticMarkup( - - {source} - , - ); - return { html, tree }; -} - -const prefix = "# Before\n\n```ts\nconst values = [1, 2];\n```\n\n"; - -describe("incremental Markdown parsing", () => { - it("keeps the document prefix cached when list recovery parses contain fences", () => { - const source = - prefix + - "- first block\n\n ```ts\n const nested = 1;\n ```\n\n tail"; - const incremental = createIncrementalMarkdownPlugin(); - const parsedSources: string[] = []; - expect(render(source, incremental, parsedSources)).toEqual(render(source)); - parsedSources.length = 0; - const next = source + " more"; - expect(render(next, incremental, parsedSources)).toEqual(render(next)); - expect(parsedSources).not.toContain(next); - expect(parsedSources.some((text) => text.startsWith("t3-markdown-inline-prefix:"))).toBe(true); - }); - - it.each([ - "a\n===\n\nb\n---\n", - "- first\n\n continued\n\n- next\n", - "> quoted\n>\n> ```js\n> abc\n> ```\n\nend", - "
\nhello\n\n
\n\nend", - "[ref]\n\n[ref]: /later", - "a[^x]\n\n[^x]: note", - "a | b\n--|--\na | b\n", - "```\na\n```\n\nnext\n\n~~~\nb\n~~~\n\nmore", - "\n\n\tcode\n\nmore", - "text *bold*", - "> [!NOTE]\n> alert\n\n- [ ] task", - "\uFEFFtext after a byte-order mark", - ])("preserves the parse tree, positions, and HTML while streaming %j", (tail) => { - const source = prefix + tail; - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental), `prefix ${end}`).toEqual(render(text)); - } - }); - - it.each(["\r\n", "\r"])("preserves partial %j line endings", (newline) => { - const source = (prefix + "next\n\n```\nlast\n```\n\nend").replaceAll("\n", newline); - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental)).toEqual(render(text)); - } - }); - - it("updates earlier references when definitions arrive after the cached prefix", () => { - const before = "[later] and footnote[^note]\n\n" + prefix; - const incremental = createIncrementalMarkdownPlugin(); - for (const tail of ["text", "[later]: /target", "[later]: /target\n\n[^note]: a note"]) { - expect(render(before + tail, incremental)).toEqual(render(before + tail)); - } - }); - - it("handles edits, replacements, and repeated renders without leaking transformed nodes", () => { - const incremental = createIncrementalMarkdownPlugin(); - const documents = [ - prefix + "- first\n - second", - prefix + "> [!NOTE]\n> transformed alert", - prefix + "plain text", - "replacement without fences", - prefix.replace("Before", "Edited") + "edited prefix", - prefix + "plain text", - prefix + "plain text", - ]; - for (const document of documents) { - expect(render(document, incremental)).toEqual(render(document)); - } - }); - - it("does not freeze unclosed, nested, indented, or mismatched fences", () => { - const prefixes = [ - "```\nopen\n\n", - "````\n```\n\n", - "> ```\n> code\n> ```\n\n", - "- ```\n code\n ```\n\n", - " ```\n code\n ```\n\n", - " $y$', + { ...ASSISTANT, math: true }, + ), + ); + expect(html).not.toMatch(/onload|javascript|position| ReadonlyArray) | null; + }; + /** Expand GitHub `:alias:` emoji shortcodes in prose outside code. */ + readonly githubEmoji?: boolean; +} + +export interface WordsHastOptions { + /** `$…$`, `$$…$$` and `math` code blocks render as SVG. */ + readonly math: boolean; + /** Soft line breaks render as `
`, as remark-breaks does. */ + readonly breaks: boolean; + /** Raw HTML shows as the text it was written as. */ + readonly escapeHtml: boolean; + /** `★ Insight ───` blocks render as insight callouts. */ + readonly insights: boolean; + readonly extensions: MarkdownExtensions; +} + +const CODEX_DIRECTIVES = ["codex-file-citation", "codex-followup", "artifact-template"]; + +const VOID = new Set("area base br col embed hr img input link meta source track wbr".split(" ")); + +const TAG = + /<(\/?)([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|)|]*>|<\?[\s\S]*?\?>/g; +const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g; + +// Start tags an HTML parser closes an open `

` for, and the elements that scope that search. +const CLOSES_PARAGRAPH = new Set( + "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split( + " ", + ), +); +const PARAGRAPH_SCOPE = new Set([ + "applet", + "caption", + "table", + "td", + "th", + "marquee", + "object", + "template", + "button", +]); + +type RenderOptions = Omit; + +const decoder = new TextDecoder(); +const encoder = new TextEncoder(); + +function renderToHtml(markdown: string, options: RenderOptions): Uint8Array { + try { + return wordsRenderToHtml(markdown, options); + } catch { + return encoder.encode( + `

${markdown.replaceAll("&", "&").replaceAll("<", "<").replaceAll("\n", "
")}

`, + ); + } +} + +const decode = (value: string) => (value.includes("&") ? decodeHTML(value) : value); + +function properties(source: string | undefined, inSvg: boolean): Element["properties"] { + const result: Element["properties"] = {}; + if (!source) return result; + for (const match of source.matchAll(ATTRIBUTE)) { + const name = match[1]!; + const info = find(inSvg ? svgSchema : htmlSchema, inSvg ? name : name.toLowerCase()); + const raw = match[2] ?? match[3] ?? match[4]; + if (raw === undefined) { + result[info.property] = info.boolean || info.overloadedBoolean ? true : ""; + continue; + } + // Attribute values decode as attributes: `©=` in a query stays as written. + const value = raw.includes("&") ? decodeHTMLAttribute(raw) : raw; + result[info.property] = + info.spaceSeparated || info.commaSeparated + ? value.split(info.commaSeparated ? "," : /\s+/).filter(Boolean) + : info.boolean + ? true + : value; + } + return result; +} + +interface Tokenized { + readonly root: Root; + /** Elements with a `data-sourcepos`, which raw HTML can write too. */ + readonly positioned: Element[]; +} + +/** + * Hast for Words' HTML. Its own markup is well formed; raw HTML closes where its end tags say, + * and is sanitized afterwards, so a misnested tag can only change structure, never safety. + */ +function tokenize(html: string, offsetOf: (byte: number) => number): Tokenized { + const root: Root = { type: "root", children: [] }; + const positioned: Element[] = []; + const stack: Array = [root]; + let svgDepth = 0; + let last = 0; + // rehypePreserveBareAnchorPlaceholders: an `
` with no attributes that never closes is text. + const anchors: Array<{ element: Element; parent: Root | Element; tag: string } | null> = []; + const text = (end: number) => { + if (end <= last) return; + const parent = stack.at(-1)!; + const value = decode(html.slice(last, end)); + const previous = parent.children.at(-1); + if (previous?.type === "text") previous.value += value; + else parent.children.push({ type: "text", value } as Text); + }; + for (const match of html.matchAll(TAG)) { + text(match.index); + last = match.index + match[0].length; + const tagName = match[2]?.toLowerCase(); + if (!tagName) continue; + if (match[1]) { + if (tagName === "a") anchors.pop(); + if (tagName === "p" && openParagraph(stack) < 0) { + // A stray `

` is an empty paragraph to an HTML parser. + (stack.at(-1)!.children as ElementContent[]).push({ + type: "element", + tagName: "p", + properties: {}, + children: [], + }); + continue; + } + const at = stack.findLastIndex((node) => node.type === "element" && node.tagName === tagName); + if (at > 0) { + for (let index = at; index < stack.length; index++) { + if ((stack[index] as Element).tagName === "svg") svgDepth--; + } + stack.length = at; + } + continue; + } + const inSvg = svgDepth > 0 || tagName === "svg"; + if (!inSvg && CLOSES_PARAGRAPH.has(tagName)) { + const paragraph = openParagraph(stack); + if (paragraph > 0) stack.length = paragraph; + } + const element: Element = { + type: "element", + tagName: inSvg ? match[2]! : tagName, + properties: properties(match[3], inSvg), + children: [], + }; + const sourcepos = element.properties.dataSourcepos; + if (typeof sourcepos === "string") { + delete element.properties.dataSourcepos; + const [start, end] = sourcepos.split("-").map((byte) => offsetOf(Number(byte))); + element.position = { + start: { line: 1, column: start! + 1, offset: start! }, + end: { line: 1, column: end! + 1, offset: end! }, + }; + positioned.push(element); + } + const parent = stack.at(-1)!; + (parent.children as ElementContent[]).push(element); + if (tagName === "a") { + anchors.push(match[3]?.trim() ? null : { element, parent, tag: match[0] }); + } + // The HTML parser ignores `/>` on elements that are not void, such as `
`. + if (!VOID.has(tagName) && (!match[4] || !inSvg)) { + stack.push(element); + if (tagName === "svg") svgDepth++; + } + } + text(html.length); + for (const anchor of anchors) { + if (!anchor) continue; + const siblings = anchor.parent.children as ElementContent[]; + const at = siblings.indexOf(anchor.element); + if (at >= 0) + siblings.splice(at, 1, { type: "text", value: anchor.tag }, ...anchor.element.children); + } + normalizeRawTables(root); + // Words ends each block with a newline; hast from remark has none after the last. + const end = root.children.at(-1); + if (end?.type === "text") { + end.value = end.value.replace(/\n$/, ""); + if (end.value.trim() === "") root.children.pop(); + } + return { root, positioned }; +} + +const positionKey = (node: Element) => + `${node.tagName.toLowerCase()}:${node.position!.start.offset}-${node.position!.end.offset}`; + +/** + * Words' HTML for `markdown` as hast. A position marks what Words generated, so raw HTML that + * writes its own `data-sourcepos` keeps none: Words' elements are those it also writes with raw + * HTML escaped, and a range claimed more often than that is trusted for none of its claimants. + */ +function parse(markdown: string, options: RenderOptions): Root { + const offsetOf = utf16Offsets(markdown); + const render = (escapeHtml?: true) => + tokenize( + decoder.decode( + renderToHtml(markdown, { + ...options, + ...(escapeHtml ? { escapeHtml } : {}), + sourcePositions: true, + }), + ), + offsetOf, + ); + const { root, positioned } = render(); + if (options.escapeHtml || options.skipHtml || !/data-sourcepos/i.test(markdown)) return root; + const generated = new Map(); + for (const node of render(true).positioned) { + const key = positionKey(node); + generated.set(key, (generated.get(key) ?? 0) + 1); + } + const claimed = new Map(); + for (const node of positioned) { + const key = positionKey(node); + claimed.set(key, (claimed.get(key) ?? 0) + 1); + } + for (const node of positioned) { + const key = positionKey(node); + if (claimed.get(key)! > (generated.get(key) ?? 0)) delete node.position; + } + return root; +} + +/** The stack index of the `

` an HTML parser would close, or -1 when none is in scope. */ +function openParagraph(stack: ReadonlyArray): number { + for (let index = stack.length - 1; index > 0; index--) { + const tagName = (stack[index] as Element).tagName; + if (tagName === "p") return index; + if (PARAGRAPH_SCOPE.has(tagName)) return -1; + } + return -1; +} + +/** parse5 puts a raw HTML table's rows in a ``; Words' own tables start with ``. */ +function normalizeRawTables(node: Root | Element) { + for (const child of node.children) { + if (child.type === "element") normalizeRawTables(child); + } + if (node.type !== "element" || node.tagName !== "table") return; + const first = node.children.findIndex((child) => isElement(child, "tr")); + if (first < 0) return; + node.children = [ + ...node.children.slice(0, first), + { type: "element", tagName: "tbody", properties: {}, children: node.children.slice(first) }, + ]; +} + +// Words leaves these raw in Markdown destinations, where micromark percent-encodes them. +const UNSAFE_URL_CHARACTERS = /[\\[\]`{}|^"<> ]/g; +const normalizeUri = (value: string) => + value.replace(UNSAFE_URL_CHARACTERS, (character) => encodeURIComponent(character)); + +const windowsPath = (url: string) => { + const path = url.replace(/%5C/gi, "\\"); + return /^[A-Za-z]:[\\/]/.test(path) ? path : undefined; +}; + +const isElement = (node: unknown, tagName?: string): node is Element => + (node as Element | undefined)?.type === "element" && + (tagName === undefined || (node as Element).tagName === tagName); + +const isElementNode = (node: ElementContent): node is Element => node.type === "element"; + +const isMarkdownImage = (node: unknown): boolean => + (isElement(node, "img") && node.position !== undefined) || + (isElement(node, "a") && + node.position !== undefined && + node.children.length === 1 && + isMarkdownImage(node.children[0])); + +const BREAK: ElementContent = { type: "element", tagName: "br", properties: {}, children: [] }; + +// Words' math: these elements and presentation attributes, and no links or handlers. +const MATH_ELEMENTS = new Set(["svg", "g", "text", "tspan", "rect", "path"]); +const MATH_PROPERTIES = new Set([ + "xmlns", + "width", + "height", + "viewBox", + "fill", + "fontFamily", + "fontSize", + "fontStyle", + "fontWeight", + "role", + "ariaLabel", + "x", + "y", + "dx", + "dy", + "d", + "transform", + "stroke", + "strokeWidth", + "textAnchor", +]); +const MATH_STYLE = /^(?:display|vertical-align|overflow|margin|white-space)$/; + +function sanitizeMath(node: Element): Element | null { + if (!MATH_ELEMENTS.has(node.tagName)) return null; + const properties: Element["properties"] = {}; + for (const [key, value] of Object.entries(node.properties)) { + if (MATH_PROPERTIES.has(key)) properties[key] = value; + } + if (typeof node.properties.style === "string") { + const style = node.properties.style + .split(";") + .filter((rule) => MATH_STYLE.test(rule.split(":")[0]!.trim())) + .join(";"); + if (style) properties.style = style; + } + const children: ElementContent[] = []; + for (const child of node.children) { + if (child.type === "text") children.push(child); + else if (child.type === "element") { + const clean = sanitizeMath(child); + if (clean) children.push(clean); + } + } + return { ...node, properties, children }; +} + +interface Walk { + /** Words' hast for more Markdown, rendered with the same options; `indent` as leadingWhitespace's. */ + readonly render: (markdown: string, indent: number) => Root; + readonly source: string; + readonly options: WordsHastOptions; + readonly math: Map; + /** A per-render id prefix for math placeholders, which authored ids cannot share. */ + readonly mathKey: string; + /** What insightSource opened each insight block with, when it opened any. */ + readonly insightMarker: RegExp | null; +} + +/** UTF-16 offsets for the UTF-8 byte offsets in Words' `data-sourcepos`. */ +function utf16Offsets(source: string): (byte: number) => number { + if (!/[^\x00-\x7f]/.test(source)) return (byte) => byte; + const offsets: number[] = []; + for (let index = 0; index < source.length; index++) { + const code = source.codePointAt(index)!; + const bytes = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4; + for (let byte = 0; byte < bytes; byte++) offsets.push(index); + if (code >= 0x10000) index++; + } + offsets.push(source.length); + return (byte) => offsets[byte] ?? source.length; +} + +const sourceOf = (node: Element, source: string) => + node.position ? source.slice(node.position.start.offset, node.position.end.offset) : ""; + +const textOf = (node: ElementContent): string => + node.type === "text" + ? node.value + : node.type === "element" + ? node.children.map(textOf).join("") + : ""; + +/** A directive's attributes, as strings; anything else Words would never write reads as none. */ +function directiveAttributes(node: Element): Record { + let parsed: unknown; + try { + parsed = JSON.parse(String(node.properties.dataAttributes ?? "{}")); + } catch { + return {}; + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {}; + return Object.fromEntries( + Object.entries(parsed).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ), + ); +} + +/** remarkCodexDirectives: what a directive Words parsed becomes, as the remark plugin builds it. */ +function codexDirective(node: Element, walk: Walk, inLink: boolean): ElementContent { + const name = node.properties.dataDirective; + const attributes = directiveAttributes(node); + const asText = (): ElementContent => { + const value: ElementContent = { type: "text", value: sourceOf(node, walk.source) }; + return node.tagName === "div" + ? { type: "element", tagName: "p", properties: {}, children: [value] } + : value; + }; + if (name === "codex-file-citation") { + const citation = resolveCodexFileCitationLink(attributes); + if (!citation || inLink) return asText(); + return { + type: "element", + tagName: "a", + properties: { href: citation.href }, + children: [{ type: "text", value: citation.label }], + ...(node.position ? { position: node.position } : {}), + }; + } + if (name === "codex-followup") { + if (!attributes.prompt?.trim() || !node.children.map(textOf).join("").trim()) return asText(); + return { type: "element", tagName: "span", properties: {}, children: node.children }; + } + const template = resolveCodexArtifactTemplate(attributes); + if (!template) return asText(); + return { + type: "element", + tagName: "div", + properties: { + dataCodexArtifactTemplate: "true", + dataArtifactKind: template.artifactKind, + dataDisplayName: template.displayName, + ...(template.galleryKind === undefined ? {} : { dataGalleryKind: template.galleryKind }), + dataSkillDirectory: template.skillDirectory, + dataSkillName: template.skillName, + }, + children: [], + }; +} + +const INLINE_PREFIX = "t3-markdown-inline-prefix:"; + +function stripPositions(node: ElementContent) { + delete node.position; + if (node.type === "element") node.children.forEach(stripPositions); +} + +/** + * remarkNormalizeListItemIndentation: four spaces after a list marker make indented code, but + * agents mean wide indentation, so code starting on the marker's line is Markdown again. True + * when it recovered the item, whose children it then has transformed. + */ +function recoverIndentedCode( + item: Element, + list: Root | Element, + walk: Walk, + inLink: boolean, + inCode: boolean, +): boolean { + const code = item.children.find((child) => child.type === "element"); + const start = code?.position?.start.offset; + const itemStart = item.position?.start.offset; + if (!isElement(code, "pre") || start === undefined || itemStart === undefined) return false; + const value = textOf(code); + if (!/^[\t ]/.test(value)) return false; + if (walk.source.slice(itemStart, start).includes("\n") || /[`~]/.test(walk.source[start]!)) { + return false; + } + // The trimmed first line sets where the item's content starts. + const indent = [.../^[\t ]*/.exec(value)![0]].reduce( + (column, character) => (character === "\t" ? (Math.floor(column / 4) + 1) * 4 : column + 1), + 0, + ); + // The prefix keeps block syntax at the start, such as `#`, from opening a block. + const source = `${INLINE_PREFIX}${value.trim()}`; + const recovered = walk.render(source, indent); + const paragraph = recovered.children.find((child) => child.type === "element"); + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + if (first?.type !== "text" || !first.value.startsWith(INLINE_PREFIX)) return false; + first.value = first.value.slice(INLINE_PREFIX.length); + if (first.value === "") paragraph!.children.shift(); + transform(recovered, { ...walk, source }, inLink, inCode); + transform(item, walk, inLink, inCode); + let blocks = recovered.children.filter( + (child) => !(child.type === "text" && child.value.trim() === ""), + ) as ElementContent[]; + // Their positions point into `source`, not the message. + blocks.forEach(stripPositions); + let at = item.children.indexOf(code); + let remove = 1; + if (!isLooseList(list, walk.source)) { + // A tight item shows its text bare, as remark-rehype unwraps its paragraphs. + blocks = blocks.flatMap((block, index) => [ + ...(index > 0 ? [{ type: "text", value: "\n" } as Text] : []), + ...(isElement(block, "p") ? block.children : [block]), + ]); + const isBlank = (node: ElementContent | undefined) => + node?.type === "text" && node.value.trim() === ""; + if (at === 1 && isBlank(item.children[0])) [at, remove] = [0, 2]; + if (at + remove === item.children.length - 1 && isBlank(item.children.at(-1))) remove++; + } + item.children.splice(at, remove, ...blocks); + return true; +} + +/** remark-rehype's listLoose: a blank line between items, or an item Words wrote as paragraphs. */ +function isLooseList(list: Root | Element, source: string): boolean { + const items = (list.children as ElementContent[]).filter((child): child is Element => + isElement(child, "li"), + ); + return items.some( + (item, index) => + item.children.some((child) => isElement(child, "p")) || + (index > 0 && + /\n[ \t>]*\n/.test( + source.slice( + items[index - 1]!.position?.end.offset ?? 0, + item.position?.start.offset ?? 0, + ), + )), + ); +} + +const WRITTEN_NUMBER = /[ \t]*(\d{1,9})[.)]/y; + +function keepListNumbers(list: Element, source: string) { + let expected = Number(list.properties.start ?? 1); + for (const item of list.children) { + if (!isElement(item, "li")) continue; + const offset = item.position?.start.offset; + WRITTEN_NUMBER.lastIndex = offset ?? 0; + const digits = offset === undefined ? undefined : WRITTEN_NUMBER.exec(source)?.[1]; + const value = digits === undefined ? expected : Number(digits); + if (value !== expected) item.properties.value = String(value); + expected = value + 1; + } +} + +/** What the chat's remark plugins add that Words does not. */ +const link = (href: string, label: string, properties: Element["properties"] = {}): Element => ({ + type: "element", + tagName: "a", + properties: { href, ...properties }, + children: [{ type: "text", value: label }], +}); + +/** Links in text: absolute file paths (remarkLinkAbsoluteFilePaths), then a change request's references. */ +function linkText(value: string, walk: Walk): ElementContent[] | null { + let parts: ElementContent[] = []; + let offset = 0; + for (const { index, path } of absoluteFilePathMatches(value)) { + if (index > offset) parts.push({ type: "text", value: value.slice(offset, index) }); + parts.push(link(path, path)); + offset = index + path.length; + } + if (offset < value.length) parts.push({ type: "text", value: value.slice(offset) }); + const autolinks = walk.options.extensions.changeRequest?.autolinks; + if (autolinks) { + parts = parts.flatMap((part) => { + if (part.type !== "text") return [part]; + const found = autolinks(part.value); + if (found.length === 0) return [part]; + const linked: ElementContent[] = []; + let start = 0; + for (const reference of found) { + if (start < reference.index) { + linked.push({ type: "text", value: part.value.slice(start, reference.index) }); + } + linked.push( + link(reference.url, reference.label, { dataPullRequestAutolink: reference.kind }), + ); + start = reference.index + reference.text.length; + } + if (start < part.value.length) linked.push({ type: "text", value: part.value.slice(start) }); + return linked; + }); + } + return parts.length === 1 && parts[0]!.type === "text" ? null : parts; +} + +function transform(node: Root | Element, walk: Walk, inLink: boolean, inCode: boolean) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type === "text") { + if (inCode) continue; + if (walk.options.extensions.githubEmoji && child.value.includes(":")) { + child.value = expandGithubEmojiAliases(child.value); + } + if (inLink) continue; + const parts = linkText(child.value, walk); + if (!parts) continue; + children.splice(index, 1, ...parts); + index += parts.length - 1; + continue; + } + if (child.type !== "element") continue; + // Words gives what it generates a source position; raw HTML that copies its attributes has none. + if (child.properties.dataDirective !== undefined && child.position) { + children[index] = codexDirective(child, walk, inLink); + index--; + continue; + } + const { tagName, properties: props } = child; + if (tagName === "svg") { + // Sanitizing drops SVG, so math waits under a placeholder until after it. + const clean = walk.options.math && child.position ? sanitizeMath(child) : null; + if (clean) { + const key = `${walk.mathKey}-${walk.math.size}`; + walk.math.set(key, clean); + children[index] = { + type: "element", + tagName: "span", + properties: { id: key }, + children: [], + }; + } + continue; + } + if (tagName === "a" && props.dataFootnoteRef !== undefined) { + // remark-rehype's footnote markup, before rehype-sanitize prefixes ids again. + props.href = `#user-content-${String(props.href).slice(1)}`; + props.id = `user-content-${String(props.id)}`; + props.ariaDescribedBy = ["footnote-label"]; + } else if (tagName === "a" && props.dataFootnoteBackref !== undefined) { + const { href, ariaLabel } = props; + child.properties = { + href: `#user-content-${String(href).slice(1)}`, + dataFootnoteBackref: "", + ariaLabel, + className: ["data-footnote-backref"], + }; + } else if (tagName === "li" && typeof props.id === "string" && props.id.startsWith("fn-")) { + props.id = `user-content-${props.id}`; + } else if (tagName === "section" && props.dataFootnotes !== undefined) { + child.properties = { dataFootnotes: "", className: ["footnotes"] }; + child.children.unshift({ + type: "element", + tagName: "h2", + properties: { className: ["sr-only"], id: "footnote-label" }, + children: [{ type: "text", value: "Footnotes" }], + }); + } else if (tagName === "a" && typeof props.href === "string") { + // remarkNormalizeLinksAndTagInlineCode: a Windows drive path links as a file URL. + const path = windowsPath(props.href); + props.href = path ? `file:///${path.replaceAll("\\", "/")}` : normalizeUri(props.href); + } else if (tagName === "img" && typeof props.src === "string") { + const changeRequest = walk.options.extensions.changeRequest; + const src = changeRequest + ? resolveChangeRequestMediaUrl(props.src, changeRequest.repositoryUrl) + : props.src; + props.src = windowsPath(src) ?? normalizeUri(src); + } else if (tagName === "code" && isElement(node, "pre")) { + if (props.dataMeta !== undefined) { + props.dataCodeMeta = props.dataMeta; + delete props.dataMeta; + } + } else if (tagName === "code" && !inLink) { + props.dataInlineCode = ""; + } else if (tagName === "ol" && walk.options.extensions.userMessage) { + keepListNumbers(child, walk.source); + } else if (tagName === "li") { + const firstBlock = child.children.find(isElementNode); + if (isElement(firstBlock, "pre") && recoverIndentedCode(child, node, walk, inLink, inCode)) { + continue; + } + // Tight items put the checkbox directly in `

  • `, loose ones inside its first `

    `. + const checkbox = isElement(child.children[0], "input") + ? child.children[0] + : isElement(firstBlock, "p") && isElement(firstBlock.children[0], "input") + ? firstBlock.children[0] + : undefined; + if (checkbox) { + props.className = ["task-list-item"]; + const { checked } = checkbox.properties; + checkbox.properties = { type: "checkbox", checked, disabled: true }; + if (node.type === "element") node.properties.className = ["contains-task-list"]; + } + breakLines(child, walk.options.breaks); + } else if (tagName === "p") { + breakLines(child, walk.options.breaks); + } else if (tagName === "blockquote") { + // remarkGithubAlerts + const paragraph = child.children.find((item) => item.type === "element"); + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + const text = first?.type === "text" ? first.value : ""; + const insight = walk.insightMarker?.exec(text); + const alert = GITHUB_ALERT_MARKER.exec(text); + // An alert marker followed by more inline content on its line is text, as remarkGithubAlerts reads it. + const match = insight + ? ([insight[0], "insight"] as const) + : alert && (alert[0].endsWith("\n") || (paragraph as Element).children.length === 1) + ? alert + : null; + if (match && first?.type === "text" && isElement(paragraph, "p")) { + first.value = first.value.slice(match[0].length); + if (first.value === "") paragraph.children.shift(); + if (paragraph.children.length === 0) { + const at = child.children.indexOf(paragraph); + const next = child.children[at + 1]; + // The line ending after it goes too, as remark leaves none for a removed paragraph. + const blank = next?.type === "text" && next.value.trim() === "" ? 2 : 1; + child.children.splice(at, blank); + } + props.dataAlert = match[1]!.toLowerCase(); + } + } + transform( + child, + walk, + inLink || tagName === "a", + inCode || tagName === "code" || tagName === "pre", + ); + } +} + +/** + * remark-breaks puts a `
    ` before every soft line ending, and remarkBreakAroundImageLines + * before those next to a Markdown image. Both keep the line ending after it. + */ +/** A Markdown image alone on its line: nothing but a line ending (or the paragraph's edge) around it. */ +function imageOwnsLine(items: ElementContent[], at: number): boolean { + if (!isMarkdownImage(items[at])) return false; + const before = items[at - 1]; + const after = items[at + 1]; + const startsLine = + before === undefined || + (before.type === "text" && /\n[ \t]*$/.test(before.value)) || + isElement(before, "br"); + const endsLine = after === undefined || (after.type === "text" && /^[ \t]*\n/.test(after.value)); + return startsLine && endsLine; +} + +const isBlockElement = (node: ElementContent | undefined) => + node?.type === "element" && CLOSES_PARAGRAPH.has(node.tagName); + +function breakLines(paragraph: Element, breaks: boolean) { + const items = paragraph.children; + for (let at = 0; at < items.length; at++) { + const item = items[at]!; + if ( + item.type === "element" && + breaks && + item.tagName !== "code" && + !CLOSES_PARAGRAPH.has(item.tagName) + ) { + breakLines(item, breaks); + } + if (item.type !== "text" || !item.value.includes("\n")) continue; + const afterImage = imageOwnsLine(items, at - 1); + const beforeImage = imageOwnsLine(items, at + 1); + const afterBlock = isBlockElement(items[at - 1]) || (at === 0 && paragraph.tagName === "li"); + const beforeBlock = + isBlockElement(items[at + 1]) || (at === items.length - 1 && paragraph.tagName === "li"); + const lines = item.value.split("\n"); + const parts: ElementContent[] = []; + lines.forEach((line, index) => { + // A hard break's own line ending follows its
    , and adds no second one; + // structural line endings around a list item's block children stay breaks between blocks. + const afterHardBreak = index === 1 && isElement(items[at - 1], "br"); + const blockBoundary = + (index === 1 && lines[0] === "" && afterBlock) || + (index === lines.length - 1 && line === "" && beforeBlock); + const breaksHere = + index > 0 && + !afterHardBreak && + !blockBoundary && + (breaks || (index === 1 && afterImage) || (index === lines.length - 1 && beforeImage)); + if (index > 0) { + if (breaksHere) { + const previous = parts.at(-1); + if (previous?.type === "text") previous.value = previous.value.replace(/[ \t]+$/, ""); + parts.push(BREAK); + } + parts.push({ type: "text", value: `\n${line}` }); + } else if (line) { + parts.push({ type: "text", value: line }); + } + }); + // Rejoin text that did not break, so the tree matches remark's text nodes. + const merged: ElementContent[] = []; + for (const part of parts) { + const previous = merged.at(-1); + if (part.type === "text" && previous?.type === "text") previous.value += part.value; + else merged.push(part); + } + items.splice(at, 1, ...merged); + at += merged.length - 1; + } +} + +/** + * The wrapper copying reads (markdown-clipboard's MATH_SELECTOR): the formula's TeX, as the source + * Words drew it from, so copying any part of a formula copies the whole of it. + */ +// A formula wider than its block scrolls, with room for the glyphs that reach past its box; in a +// table it keeps its width and the table scrolls. +const MATH_SCROLL = [ + "max-w-full", + "overflow-x-auto", + "overflow-y-hidden", + "px-0.5", + "py-0.75", + "in-[.chat-markdown-table-container]:max-w-none", + "in-[.chat-markdown-table-container]:overflow-visible", +]; + +function mathWrapper(svg: Element): Element { + const tex = String(svg.properties.ariaLabel ?? "").trim(); + const display = /display:\s*block/.test(String(svg.properties.style ?? "")); + return { + type: "element", + tagName: "span", + properties: display + ? { + className: ["chat-markdown-math-display", "block", ...MATH_SCROLL], + dataMarkdownMath: "display", + dataMarkdownCopy: `\\[\n${tex}\n\\]\n\n`, + } + : { + className: ["inline-block", "align-middle", ...MATH_SCROLL], + dataMarkdownMath: "inline", + dataMarkdownCopy: `\\(${tex}\\)`, + }, + children: [svg], + }; +} + +function restoreMath(node: Root | Element, math: Map) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + const id = child.properties.id; + const svg = typeof id === "string" ? math.get(id.replace(/^user-content-/, "")) : undefined; + if (svg) children[index] = mathWrapper(svg); + else restoreMath(child, math); + } +} + +const addHeadingIds = rehypeHeadingIds(); +const addTextDirection = rehypeTextDirection(); +const preserveImageSourceMeta = rehypePreserveImageSourceMeta(); +const normalizeLocalEditorLinks = rehypeNormalizeLocalEditorLinks(); +const groupChipPunctuation = rehypeChipPunctuation(); + +const INSIGHT_OPENING = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; +const INSIGHT_CLOSING = /^( {0,3})(`?)─{3,}\2[ \t]*$/u; + +interface InsightSource { + readonly source: string; + readonly tree: Root; + readonly marker: RegExp; + /** The offset in the message for an offset in `source`. */ + readonly toOriginal: (offset: number) => number; +} + +/** + * remarkAssistantInsights: a `★ Insight ───` line opens a quoted insight block, which a `───` line + * at the same indentation closes; the end of the text closes one that never does. Lines in code + * neither open nor close one, and an opening Words does not read as a quote's first line, as in + * an HTML block or a quote's lazy line, stays text. + */ +function insightSource(text: string, options: RenderOptions): InsightSource | null { + if (!text.includes("★ Insight")) return null; + const code: Array = []; + const findCode = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "pre" && child.position) { + code.push([child.position.start.offset!, child.position.end.offset!]); + } else findCode(child); + } + }; + findCode(parse(text, options)); + const nonce = Math.random().toString(36).slice(2); + const marker = new RegExp(String.raw`^\[!T3-INSIGHT-${nonce}-(\d+)\](?:\r?\n)?`); + const anywhere = new RegExp(String.raw`\[!T3-INSIGHT-${nonce}-(\d+)\]`, "g"); + const lines = text.split(/(?<=\n)/u); + const skipped = new Set(); + for (;;) { + // Each line's offset in the message and in the source, and how much longer it got. + const offsets: Array<{ original: number; source: number; length: number; delta: number }> = []; + let original = 0; + let rewritten = 0; + let opened = 0; + let indent: string | undefined; + const source = lines + .map((line, lineIndex) => { + const value = line.replace(/[\r\n]+$/u, ""); + const ending = line.slice(value.length); + const inCode = code.some(([start, end]) => original >= start && original < end); + let output = line; + if (indent === undefined) { + const opening = inCode ? null : INSIGHT_OPENING.exec(value); + if (opening && !skipped.has(lineIndex)) { + indent = opening[1] ?? ""; + opened++; + output = `> [!T3-INSIGHT-${nonce}-${lineIndex}]${ending}`; + } + } else { + const closing = inCode ? null : INSIGHT_CLOSING.exec(value); + if (closing && closing[1] === indent) { + indent = undefined; + output = ending; + } else output = `> ${line}`; + } + offsets.push({ + original, + source: rewritten, + length: line.length, + delta: output.length - line.length, + }); + original += line.length; + rewritten += output.length; + return output; + }) + .join(""); + if (opened === 0) return null; + const tree = parse(source, options); + let stranded = false; + const visit = (node: Root | Element, quoteStart: Text | undefined) => { + for (const child of node.children) { + if (child.type === "text") { + for (const found of child.value.matchAll(anywhere)) { + if (child === quoteStart && found.index === 0) continue; + skipped.add(Number(found[1])); + stranded = true; + } + } else if (child.type === "element") { + const paragraph = + child.tagName === "blockquote" ? child.children.find(isElementNode) : undefined; + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + visit(child, first?.type === "text" ? first : quoteStart); + } + } + }; + visit(tree, undefined); + if (stranded) continue; + return { + source, + tree, + marker, + toOriginal: (offset) => { + const line = offsets.findLast((entry) => entry.source <= offset) ?? offsets[0]!; + return ( + line.original + Math.min(Math.max(offset - line.source - line.delta, 0), line.length) + ); + }, + }; + } +} + +/** Positions that point into an insight's rewritten source, moved back into the message. */ +function restorePositions(node: Root | Element, toOriginal: (offset: number) => number) { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.position) { + const start = toOriginal(child.position.start.offset!); + const end = toOriginal(child.position.end.offset!); + child.position = { + start: { line: 1, column: start + 1, offset: start }, + end: { line: 1, column: end + 1, offset: end }, + }; + } + restorePositions(child, toOriginal); + } +} + +const PREVIEW_SEPARATED = new Set([ + "blockquote", + "ul", + "ol", + "li", + "table", + "thead", + "tbody", + "tr", +]); + +/** remarkThoughtPreview: the message as one line of text, keeping math, cut at `maxLength`. */ +function flattenPreview(tree: Root, preview: NonNullable): Root { + const children: ElementContent[] = []; + let remaining = preview.maxLength; + let fragments: string[] = []; + const flush = () => { + if (fragments.length === 0) return; + children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") }); + fragments = []; + }; + const take = (value: string) => { + const text = value.slice(0, remaining); + remaining = text.length < value.length ? 0 : remaining - text.length; + // A cut must not leave half a surrogate pair. + return text.replace(/[\uD800-\uDBFF]$/, ""); + }; + const visit = (node: Root | ElementContent) => { + if (remaining === 0) return; + if (node.type === "text") { + fragments.push(take(node.value)); + return; + } + if (node.type === "element" && node.properties.dataMarkdownMath !== undefined) { + flush(); + // One line has no room for display math, which a preview shows inline. + const svg = node.children[0]; + children.push( + node.properties.dataMarkdownMath === "display" && svg?.type === "element" + ? mathWrapper({ + ...svg, + properties: { + ...svg.properties, + style: "display:inline;vertical-align:middle;overflow:visible", + }, + }) + : node, + ); + return; + } + if (node.type === "element" && node.tagName === "img") { + fragments.push(take(String(node.properties.alt ?? ""))); + return; + } + if (node.type === "element" && node.tagName === "br") { + fragments.push(take(" ")); + return; + } + if (node.type !== "root" && node.type !== "element") return; + const separates = node.type === "root" || PREVIEW_SEPARATED.has(node.tagName); + let first = true; + for (const child of node.children as ElementContent[]) { + if (remaining === 0) break; + if (child.type === "text" && child.value.trim() === "" && separates) continue; + if (!first && separates) fragments.push(take(" ")); + first = false; + visit(child); + } + }; + visit(tree); + flush(); + const head = children[0]; + const tail = children.at(-1); + if (head?.type === "text") head.value = head.value.trimStart(); + if (tail?.type === "text") tail.value = tail.value.trimEnd(); + const visible = children.some((child) => child.type !== "text" || child.value); + return { + type: "root", + children: visible ? children : [{ type: "text", value: preview.fallback }], + }; +} + +/** Links become their text, images their alt text, inline code plain text, Mermaid plain code. */ +function makeInert(node: Root | Element) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + if (child.tagName === "a") { + children.splice(index, 1, ...child.children); + index--; + continue; + } + if (child.tagName === "img") { + children[index] = { type: "text", value: String(child.properties.alt ?? "") }; + continue; + } + if (child.tagName === "code" && child.properties.dataInlineCode !== undefined) { + children[index] = { type: "text", value: textOf(child) }; + continue; + } + if ( + child.tagName === "code" && + String(child.properties.className ?? "").includes("language-mermaid") + ) { + child.properties.className = ["language-text"]; + } + makeInert(child); + } +} + +/** ChatMarkdown's sanitized hast for `text`, rendered by Words. */ +export function wordsHast(text: string, options: WordsHastOptions): Root { + const { extensions } = options; + const renderOptions: RenderOptions = { + math: options.math, + // llm-math's `\(…\)` and `\[…\]`, which agents write as often as `$`. + texDelimiters: options.math, + autolinkBoundaries: true, + singleTilde: !extensions.userMessage, + leadingWhitespace: extensions.leadingWhitespace === true, + windowsPaths: true, + codeMeta: true, + directives: CODEX_DIRECTIVES, + // Previews and inert Markdown drop raw HTML, as their remark plugins dropped html nodes. + ...(extensions.preview || extensions.inert + ? { skipHtml: true } + : { escapeHtml: options.escapeHtml }), + }; + const insights = options.insights ? insightSource(text, renderOptions) : null; + const source = insights?.source ?? text; + const tree = insights?.tree ?? parse(source, renderOptions); + const walk: Walk = { + render: (markdown, indent) => + parse(markdown, { + ...renderOptions, + leadingWhitespace: extensions.leadingWhitespace === true && { indent }, + }), + source, + options, + math: new Map(), + mathKey: `t3-math-${Math.random().toString(36).slice(2)}`, + insightMarker: insights?.marker ?? null, + }; + transform(tree, walk, false, false); + preserveImageSourceMeta(tree as never); + normalizeLocalEditorLinks(tree as never); + const hast = sanitizeChatHast(tree); + if (walk.math.size > 0) restoreMath(hast, walk.math); + if (insights) restorePositions(hast, insights.toOriginal); + if (extensions.inert) makeInert(hast); + if (extensions.preview) return flattenPreview(hast, extensions.preview); + addHeadingIds(hast); + addTextDirection(hast as never); + groupChipPunctuation(hast as never); + return hast; +} + +export interface CodexDirectiveSource { + readonly name: string; + readonly attributes: Record; + /** UTF-16 offsets of the whole directive in the source. */ + readonly start: number; + readonly end: number; + /** The label's text as written. */ + readonly label: string; + /** Inside a link, where a file citation stays text. */ + readonly inLink: boolean; +} + +/** The Codex directives in `markdown`, as Words reads them. */ +export function codexDirectiveSources(markdown: string): CodexDirectiveSource[] { + const found: CodexDirectiveSource[] = []; + const visit = (node: Root | Element, inLink: boolean) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const name = child.properties.dataDirective; + if (typeof name === "string" && child.position) { + const { start, end } = child.position; + found.push({ + name, + attributes: directiveAttributes(child), + start: start.offset!, + end: end.offset!, + label: directiveLabel(markdown.slice(start.offset, end.offset)), + inLink, + }); + } + visit(child, inLink || child.tagName === "a"); + } + }; + visit( + parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + directives: CODEX_DIRECTIVES, + }), + false, + ); + return found; +} + +/** The label of a directive as written, `:name[label]{…}`: brackets nest in it, and `\` escapes. */ +function directiveLabel(written: string): string { + const open = written.indexOf("["); + if (open < 0) return ""; + let depth = 0; + for (let index = open; index < written.length; index++) { + const character = written[index]; + if (character === "\\") index++; + else if (character === "[") depth++; + else if (character === "]" && --depth === 0) return written.slice(open + 1, index); + } + return ""; +} + +/** + * Words' HTML for `markdown` as hast, unsanitized and without the chat's additions. Code blocks, + * links, list items and math carry source positions. + */ +export function markdownTree( + markdown: string, + options: { skipHtml?: boolean; singleTilde?: boolean; math?: boolean } = {}, +): Root { + return parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + skipHtml: options.skipHtml === true, + singleTilde: options.singleTilde !== false, + math: options.math === true, + texDelimiters: options.math === true, + }); +} + +/** The formulas Words reads in `text`, as source offsets, for editors that keep math as source. */ +export function markdownMathRanges(text: string): Array<{ start: number; end: number }> { + if (!/[$\\]|(?:`{3,}|~{3,})[ \t]*math\b/.test(text)) return []; + const ranges: Array<{ start: number; end: number }> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "svg") { + if (child.position) { + ranges.push({ start: child.position.start.offset!, end: child.position.end.offset! }); + } + continue; + } + visit(child); + } + }; + visit(parse(text, { math: true, texDelimiters: true })); + return ranges; +} + +/** The HTML comments Words reads as raw HTML in `markdown`, not as code or text, as source offsets. */ +export function markdownHtmlComments(markdown: string): Array<{ start: number; end: number }> { + const openers = [...markdown.matchAll(/", start + 4); + return { start, end: close < 0 ? markdown.length : close + 3 }; + }); +} + +/** + * The first definition of each label in `markdown`, as one line of Markdown. Words decides which + * `[label]:` text defines one: each label is looked up again after the text. + */ +export function markdownReferenceDefinitions(markdown: string): string[] { + const labels = new Map(); + for (const match of markdown.matchAll(/\[((?:[^\\[\]]|\\.){1,999})\]:/g)) { + const key = match[1]!.replace(/\s+/g, " ").trim().toLowerCase(); + // `[^1]:` is a footnote. + if (key !== "" && !key.startsWith("^") && !labels.has(key)) labels.set(key, match[1]!); + } + if (labels.size === 0) return []; + let probe = `${markdown}\n\n`; + const lookups = new Map(); + for (const label of labels.values()) { + lookups.set(probe.length, label); + probe += `[${label}]\n\n`; + } + const definitions: string[] = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const label = lookups.get(child.position?.start.offset ?? -1); + if (child.tagName === "a" && label !== undefined) { + const href = String(child.properties.href ?? "").replace(/[<>\\\n]/g, encodeURIComponent); + const title = child.properties.title; + definitions.push( + `[${label}]: <${href}>${typeof title === "string" ? ` "${title.replace(/\s+/g, " ").replace(/["\\]/g, "\\$&")}"` : ""}`, + ); + } else visit(child); + } + }; + visit(parse(probe, { windowsPaths: true })); + return definitions; +} diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index fee70319c71de..92fad6b57ac9d 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -654,6 +654,10 @@ "./provider-instance-ids": { "types": "./src/providerInstanceIds.ts", "default": "./src/providerInstanceIds.ts" + }, + "./pull-request-references": { + "types": "./src/pullRequestReferences.ts", + "default": "./src/pullRequestReferences.ts" } }, "scripts": { @@ -680,16 +684,16 @@ "effect": "catalog:", "gt-i18n": "1.0.40", "jszip": "3.10.1", - "remark-gfm": "catalog:", - "remark-parse": "catalog:", "three": "0.180.0", - "unbash": "^5.0.0", - "unified": "catalog:" + "unbash": "^5.0.0" }, "devDependencies": { "@effect/vitest": "catalog:", "@types/mdast": "^4.0.4", "@types/three": "0.180.0", + "remark-gfm": "catalog:", + "remark-parse": "catalog:", + "unified": "catalog:", "vite-plus": "catalog:" } } diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index d4f19173758ec..7d9d162d76a05 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -4,19 +4,39 @@ import remarkParse from "remark-parse"; import { unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; +import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequestMarkdown.ts"; import { changeRequestReferenceAutolinker, resolveChangeRequestMediaUrl, - splitPullRequestBody, - type PullRequestBodySegment, -} from "./pullRequestMarkdown.ts"; +} from "./pullRequestReferences.ts"; + +const definitionParser = unified().use(remarkParse).use(remarkGfm); + +// The finder a client passes: each first definition, joined onto one line out of its quote. +const split = (body: string) => + splitPullRequestBody(body, (markdown) => { + const definitions = new Map(); + const visit = (node: Root | RootContent, quotes: number) => { + if (node.type === "definition" && !definitions.has(node.identifier)) { + const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu"); + const source = markdown.slice(node.position?.start.offset, node.position?.end.offset); + definitions.set(node.identifier, source.replace(wrap, " ")); + } + if ("children" in node) { + for (const child of node.children) + visit(child, quotes + (node.type === "blockquote" ? 1 : 0)); + } + }; + visit(definitionParser.parse(markdown), 0); + return [...definitions.values()]; + }); describe("pull request body segmentation", () => { // GitHub writes a dropped image into the body as an `` tag, so a bare attachment link on // its own line is the shape it uses for a video — every one sampled in the wild was one. it("lifts a dropped video out and keeps the prose around it", () => { expect( - splitPullRequestBody( + split( "Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter", ), ).toEqual([ @@ -43,7 +63,7 @@ describe("pull request body segmentation", () => { ? segment.rows.flat().flatMap((cell) => prose(cell.segments)) : [], ); - const runs = prose(splitPullRequestBody(body)); + const runs = prose(split(body)); expect(runs.map((segment) => segment.text)).toEqual([ "- [ ] Before", " - [ ] code\n- [x] After", @@ -59,9 +79,7 @@ describe("pull request body segmentation", () => { it("reads the source out of a video tag, including a multi-line one", () => { expect( - splitPullRequestBody( - '', - ), + split(''), ).toEqual([ { id: "attachment:0", @@ -75,21 +93,21 @@ describe("pull request body segmentation", () => { it("leaves the img tag GitHub writes for a dropped image as markdown", () => { const body = 'image'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("leaves an ordinary link alone, whether it is bare or written as markdown", () => { const body = "https://example.com/page\n\n[the docs](https://example.com/docs)"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("never lifts a link inside fenced code out of it", () => { const body = "```\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -97,14 +115,14 @@ describe("pull request body segmentation", () => { // GitHub keeps CRLF in a body written in its web editor. it("recognizes fences in a body with CRLF line endings", () => { const body = "```\r\nhttps://example.com/demo.mp4\r\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("closes a CRLF fence, so a video after it still lifts out", () => { const code = '```html\r\n\r\n```'; - expect(splitPullRequestBody(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ + expect(split(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 }, { id: "attachment:1", @@ -117,21 +135,21 @@ describe("pull request body segmentation", () => { it("does not let a different fence marker close an open fence", () => { const body = "```\n~~~\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("keeps a video tag that shares its line with prose as markdown", () => { const body = 'Before after'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("treats an info-string fence as a nested opener, not a close", () => { const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -139,9 +157,7 @@ describe("pull request body segmentation", () => { it("does not open a fence on a line of inline triple-backtick code", () => { const code = "```\nhttps://example.com/b.png\n```"; expect( - splitPullRequestBody( - `\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`, - ), + split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`), ).toEqual([ { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 }, { @@ -153,14 +169,14 @@ describe("pull request body segmentation", () => { { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 }, ]); const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```"; - expect(splitPullRequestBody(multilineSpan)).toEqual([ + expect(split(multilineSpan)).toEqual([ { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 }, ]); }); it("leaves an indented code line alone even when it is only a video link", () => { const body = " https://example.com/demo.mp4"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -169,14 +185,14 @@ describe("pull request body segmentation", () => { const body = ['

    ");
         expect(html).toContain("
  • for (const step of rest.steps) {
  • "); expect(html).toContain("
  • if (step.request.body) {
  • "); - expect(html).toContain("
  • step.request.body = "<redacted>";
  • "); + expect(html).toContain('
  • step.request.body = "";
  • '); }); it("preserves every recovered block separated by blank lines", () => { diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index 53b49a03762a3..6bb022f532942 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -1,4 +1,3 @@ -import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts"; import type { Heading, Link, @@ -15,7 +14,7 @@ import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import { find, html } from "property-information"; import rehypeRaw from "rehype-raw"; -import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; +import rehypeSanitize from "rehype-sanitize"; import remarkBreaks from "remark-breaks"; import remarkGfm from "remark-gfm"; import { remarkGithubAlerts } from "./markdownGithubAlerts.ts"; @@ -25,17 +24,18 @@ import { remarkEnableLeadingWhitespace, remarkKeepLeadingWhitespace, } from "./markdownLeadingWhitespace.ts"; -import { - CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES, - remarkCodexDirectives, -} from "./codexMarkdownDirectives.ts"; -import { - absoluteFilePathMatches, - isWindowsDrivePathHref, - normalizeMarkdownLinkDestination, -} from "./markdownLinks.ts"; +import { remarkCodexDirectives } from "./codexMarkdownDirectives.ts"; +import { absoluteFilePathMatches } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; -import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts"; +import { + CHAT_MARKDOWN_SANITIZE_SCHEMA, + chatMarkdownImageSource, + rehypeNormalizeLocalEditorLinks, + rehypePreserveImageSourceMeta, + type ChatMarkdownImageProperties, +} from "./markdownHast.ts"; + +export { chatMarkdownImageSource, type ChatMarkdownImageProperties }; export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts"; @@ -47,44 +47,6 @@ type MarkdownImageHastNode = { children?: MarkdownImageHastNode[]; }; -function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] { - return (node.children ?? []).filter( - (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""), - ); -} - -const STANDALONE_IMAGE_BLOCKS = new Set([ - "p", - "div", - "li", - "td", - "th", - "figure", - "center", - "blockquote", -]); - -function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined { - const children = meaningfulHastChildren(node); - if (children.length !== 1) return undefined; - const only = children[0]; - if (only?.type !== "element") return undefined; - if (only.tagName === "img") return only; - return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em" - ? soleImageDescendant(only) - : undefined; -} - -function markStandaloneImages(node: MarkdownImageHastNode) { - if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) { - const image = soleImageDescendant(node); - if (image) image.properties = { ...image.properties, dataStandalone: true }; - } - node.children?.forEach((child) => { - if (child.type === "element") markStandaloneImages(child); - }); -} - // Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag. const RAW_HTML_TAG_PATTERN = /|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g; @@ -133,121 +95,6 @@ function rehypePreserveBareAnchorPlaceholders() { }; } -const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i; - -/** - * The renderer resolves an ``'s `src` (workspace files, host media) but never a ``'s - * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves - * onto the `` for the renderer to pick by theme; every source is then dropped. - */ -function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) { - if (!picture.children) return; - const image = picture.children.find((child) => child.tagName === "img"); - for (const source of picture.children) { - if (source.tagName !== "source" || !image) continue; - const media = source.properties?.media; - const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined; - const srcSet = source.properties?.srcSet; - const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet; - // A candidate's URL runs to the first space (a descriptor such as `2x` may follow). - const url = - typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : ""; - const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc"; - // As in a browser, the first source that matches a scheme is the one shown. - if (scheme && url && image.properties?.[key] === undefined) { - // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path. - const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url; - image.properties = { ...image.properties, [key]: value }; - } - } - picture.children = picture.children.filter((child) => child.tagName !== "source"); -} - -function rehypePreserveImageSourceMeta() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const src = node.properties?.src; - const title = node.properties?.title; - if (node.type === "element" && node.tagName === "picture") { - moveColorSchemeSourcesToImage(node); - } - if (node.type === "element" && node.tagName === "img") { - node.properties = { - ...node.properties, - ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}), - ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}), - }; - } - node.children?.forEach(visit); - }; - - visit(tree); - markStandaloneImages(tree); - }; -} - -const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"]; - -// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first. -function rehypeNormalizeLocalEditorLinks() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const href = node.properties?.href; - if (node.type === "element" && node.tagName === "a" && typeof href === "string") { - try { - const url = new URL(href); - if (isLocalEditorFileUrl(url)) node.properties = { ...node.properties, href: url.href }; - } catch { - // Not an absolute URL; the sanitizer decides. - } - } - node.children?.forEach(visit); - }; - - visit(tree); - }; -} - -const CHAT_MARKDOWN_SANITIZE_SCHEMA = { - ...defaultSchema, - attributes: { - ...defaultSchema.attributes, - "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"), - // Fence languages plus the two math classes the web chat's math plugin emits. - code: [ - ["className", /^language-./, "math-inline", "math-display"], - "dataCodeMeta", - "dataInlineCode", - ], - blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"], - div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES], - a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"], - img: [ - ...(defaultSchema.attributes?.img ?? []), - "dataDarkSrc", - "dataLightSrc", - "dataLocalSrc", - "dataMarkdownTitle", - "dataStandalone", - ], - }, - protocols: { - ...defaultSchema.protocols, - href: [ - ...(defaultSchema.protocols?.href ?? []), - "file", - "t3-citation", - "t3-context", - THREAD_LINK_PROTOCOL, - // Scheme only: the renderer's URL transform checks the rest of the link shape. - ...LOCAL_FILE_LINK_SCHEMES, - ], - src: IMAGE_SRC_PROTOCOLS, - dataDarkSrc: IMAGE_SRC_PROTOCOLS, - dataLightSrc: IMAGE_SRC_PROTOCOLS, - }, -} satisfies Parameters[0]; - export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ remarkGfm, remarkEndAutolinksAtScriptPunctuation, @@ -752,10 +599,6 @@ function remarkNormalizeLinksAndTagInlineCode() { }; } -export function shouldPreserveAssistantLineBreaks(text: string): boolean { - return /^★ Insight(?:\s|─)/mu.test(text); -} - export function remarkAssistantInsights(this: Processor) { return (tree: Root, file: { value: unknown }) => { const source = String(file.value); @@ -840,37 +683,6 @@ const imageSourceProcessor = unified() .use(remarkRehype, { allowDangerousHtml: true }) .use(CHAT_MARKDOWN_REHYPE_PLUGINS); -export type ChatMarkdownImageProperties = { - readonly src?: unknown; - readonly dataLocalSrc?: unknown; - readonly dataDarkSrc?: unknown; - readonly dataLightSrc?: unknown; -}; - -/** Keep the authored path for file links and normalize Windows separators for classification. */ -export function chatMarkdownImageSource( - properties?: ChatMarkdownImageProperties, - theme?: "dark" | "light", -) { - const themeSrc = - theme === undefined - ? undefined - : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"]; - const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc; - const source = - typeof themeSrc === "string" - ? themeSrc - : typeof localSrc === "string" - ? localSrc - : properties?.src; - if (typeof source !== "string") return null; - const authoredSrc = normalizeMarkdownLinkDestination(source); - return { - authoredSrc, - classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc, - }; -} - interface ImageSourceNode { readonly type: string; readonly tagName?: string; diff --git a/packages/shared/src/markdownTaskEdits.ts b/packages/shared/src/markdownTaskEdits.ts new file mode 100644 index 0000000000000..2f33428613147 --- /dev/null +++ b/packages/shared/src/markdownTaskEdits.ts @@ -0,0 +1,28 @@ +/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ +export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { + const firstLineEnd = markdown.indexOf("\n", listItemStart); + const firstLine = markdown.slice( + listItemStart, + firstLineEnd === -1 ? markdown.length : firstLineEnd, + ); + const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); + if (!match?.[1]) return null; + return listItemStart + firstLine.indexOf(match[1]); +} + +export function setMarkdownTaskChecked( + markdown: string, + markerOffset: number, + checked: boolean, +): string { + if ( + markerOffset < 0 || + markdown[markerOffset] !== "[" || + !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || + markdown[markerOffset + 2] !== "]" + ) { + return markdown; + } + + return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; +} diff --git a/packages/shared/src/markdownTaskList.test.ts b/packages/shared/src/markdownTaskList.test.ts index 5e00a3926fa54..7f7519ce49ee5 100644 --- a/packages/shared/src/markdownTaskList.test.ts +++ b/packages/shared/src/markdownTaskList.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vite-plus/test"; -import { markdownTaskMarkerOffset, setMarkdownTaskChecked } from "./markdownTaskList.ts"; +import { markdownTaskMarkerOffset } from "./markdownTaskList.ts"; +import { setMarkdownTaskChecked } from "./markdownTaskEdits.ts"; describe("setMarkdownTaskChecked", () => { const markdown = "- [ ] First\n- [x] Second\n"; diff --git a/packages/shared/src/markdownTaskList.ts b/packages/shared/src/markdownTaskList.ts index fb02f757992b9..a4d18895505c6 100644 --- a/packages/shared/src/markdownTaskList.ts +++ b/packages/shared/src/markdownTaskList.ts @@ -3,36 +3,9 @@ import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import { unified } from "unified"; -const parser = unified().use(remarkParse).use(remarkGfm); - -/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ -export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { - const firstLineEnd = markdown.indexOf("\n", listItemStart); - const firstLine = markdown.slice( - listItemStart, - firstLineEnd === -1 ? markdown.length : firstLineEnd, - ); - const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); - if (!match?.[1]) return null; - return listItemStart + firstLine.indexOf(match[1]); -} - -export function setMarkdownTaskChecked( - markdown: string, - markerOffset: number, - checked: boolean, -): string { - if ( - markerOffset < 0 || - markdown[markerOffset] !== "[" || - !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || - markdown[markerOffset + 2] !== "]" - ) { - return markdown; - } +import { taskListMarkerOffset } from "./markdownTaskEdits.ts"; - return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; -} +const parser = unified().use(remarkParse).use(remarkGfm); /** Hard breaks as U+2028, as iOS draws them; soft breaks stay "\n". */ function plainText(node: Nodes): string { diff --git a/packages/shared/src/markdownWindowsPaths.ts b/packages/shared/src/markdownWindowsPaths.ts index c4c04490a2140..d7c827c8dba8c 100644 --- a/packages/shared/src/markdownWindowsPaths.ts +++ b/packages/shared/src/markdownWindowsPaths.ts @@ -1,5 +1,6 @@ import type { Processor } from "unified"; import { decodeString } from "micromark-util-decode-string"; +import { UNFINISHED_DRIVE_PATH } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; interface DestinationCompileContext { @@ -18,9 +19,6 @@ function keepWindowsPathDestination(this: DestinationCompileContext, token: unkn : decoded; } -// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`. -export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/; - interface EscapeCompileContext { readonly stack: ReadonlyArray<{ readonly type: string; diff --git a/packages/shared/src/textDirection.ts b/packages/shared/src/textDirection.ts index 0d4a7d88fd837..1efe672108cad 100644 --- a/packages/shared/src/textDirection.ts +++ b/packages/shared/src/textDirection.ts @@ -2,8 +2,8 @@ export type TextDirection = "ltr" | "rtl"; // Hebrew through Arabic Extended-A, their presentation forms, and the // supplementary right-to-left blocks. -const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; -const LETTER = /\p{L}/u; +export const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; +export const LETTER = /\p{L}/u; const SENTENCE_END = /(?<=[.!?؟])(?=0.5.1' + react: ^18.3.1 || ^19.0.0 + peerDependenciesMeta: + '@pierre/highlights': + optional: true + react: + optional: true + '@pinojs/redact@0.4.0': resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} @@ -11629,12 +11623,6 @@ packages: react-is@19.2.7: resolution: {integrity: sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==} - react-markdown@10.1.0: - resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==} - peerDependencies: - '@types/react': '>=18' - react: '>=18' - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz: resolution: {integrity: sha512-TdP2nTxn8W4jPJ5EU+9Ctgf6aOncENP/kMa9aEZpJDmWNLXkxPpcugHMWyZJt2o5WDYE4SPi0V6zV6mOl3+8cA==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz} version: 1.2.0-t3.18 @@ -16556,6 +16544,11 @@ snapshots: - '@shikijs/themes' - shiki + '@pierre/words@file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz(@pierre/highlights@0.5.1)(react@19.3.0)': + optionalDependencies: + '@pierre/highlights': 0.5.1 + react: 19.3.0 + '@pinojs/redact@0.4.0': {} '@polka/url@1.0.0-next.29': {} @@ -22531,24 +22524,6 @@ snapshots: react-is@19.2.7: {} - react-markdown@10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1): - dependencies: - '@types/hast': 3.0.5 - '@types/mdast': 4.0.4 - '@types/react': 19.3.0 - devlop: 1.1.0 - hast-util-to-jsx-runtime: 2.3.6(supports-color@8.1.1) - html-url-attributes: 3.0.1 - mdast-util-to-hast: 13.2.1(patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1) - react: 19.3.0 - remark-parse: 11.0.0(supports-color@8.1.1) - remark-rehype: 11.1.2 - unified: 11.0.5 - unist-util-visit: 5.1.0 - vfile: 6.0.3 - transitivePeerDependencies: - - supports-color - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz(katex@0.16.47)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0): dependencies: react: 19.3.0 diff --git a/scripts/check-changed.ts b/scripts/check-changed.ts index 135ff4ed201f7..d5881661f4cdc 100644 --- a/scripts/check-changed.ts +++ b/scripts/check-changed.ts @@ -433,6 +433,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { file === ".pnpmfile.cjs" || file.startsWith("patches/") || file.startsWith("apps/mobile/deps/") || + file.startsWith("apps/web/deps/") || path.basename(file) === "package.json", ); @@ -479,7 +480,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { if (yield* fs.exists(inRoot(manifest))) yield* copy(manifest); } } - for (const extra of ["apps/mobile/deps", "patches", ".pnpmfile.cjs"]) { + for (const extra of ["apps/mobile/deps", "apps/web/deps", "patches", ".pnpmfile.cjs"]) { if (yield* fs.exists(inRoot(extra))) yield* copy(extra); } const result = yield* vp(["install", "--lockfile-only", "--ignore-scripts"], temp); diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 3c58be4cbabbf..e7acbf1e76ff1 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -68,11 +68,12 @@ function copyWorkspaceManifestFixture(targetRoot: string): void { NodeFS.cpSync(sourcePath, destinationPath); } - const mobileDependencies = NodePath.resolve(repoRoot, "apps/mobile/deps"); - if (NodeFS.existsSync(mobileDependencies)) { - NodeFS.cpSync(mobileDependencies, NodePath.resolve(targetRoot, "apps/mobile/deps"), { - recursive: true, - }); + // Fork tarballs that file: dependencies install from. + for (const forks of ["apps/mobile/deps", "apps/web/deps"]) { + const source = NodePath.resolve(repoRoot, forks); + if (NodeFS.existsSync(source)) { + NodeFS.cpSync(source, NodePath.resolve(targetRoot, forks), { recursive: true }); + } } const patchesDirectory = NodePath.resolve(repoRoot, "patches"); From c1fbdf6cdbe1e16379beebf8658b12a0b8a84f70 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 21:53:58 -0800 Subject: [PATCH 005/162] fix(web): pasting text copied from Word inserts the text instead of an image (#40686) --- apps/web/src/components/chat/ChatComposer.tsx | 10 ++++- .../chat/composerAttachmentFiles.test.ts | 18 +++++++- .../chat/composerAttachmentFiles.ts | 44 +++++++++++++------ 3 files changed, 56 insertions(+), 16 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 2c3bc34529ffd..6d4487adef153 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -133,6 +133,7 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, + isImageOnlyClipboardHtml, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -2918,7 +2919,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (!pastedContext && activeThreadId && files.length > 0 && - shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment })) + shouldHandleComposerAttachmentPaste({ + files, + plainText, + bypassAutoAttachment, + htmlIsOnlyImage: + plainText.length > 0 && + isImageOnlyClipboardHtml(event.clipboardData.getData("text/html")), + })) ) { event.preventDefault(); event.stopPropagation(); diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index 2a487b1f237de..f842566d7cd60 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts @@ -121,10 +121,26 @@ describe("composer attachment files", () => { ).toBe(true); }); - it("leaves an image-and-text clipboard to the text path under Paste as Text", () => { + it("leaves a Word image-and-text clipboard to the text path, with or without Paste as Text", () => { const image = new File(["png"], "image.png", { type: "image/png" }); const input = { files: [image], plainText: "Hello from Word", bypassAutoAttachment: true }; expect(shouldHandleComposerAttachmentPaste(input)).toBe(false); + // A plain paste of the same Word clipboard keeps the text too. + expect(shouldHandleComposerAttachmentPaste({ ...input, bypassAutoAttachment: false })).toBe( + false, + ); + // Firefox's Copy Image adds the image URL as text and only an as HTML; the image attaches. + expect( + shouldHandleComposerAttachmentPaste({ + files: [image], + plainText: "https://example.com/image.png", + htmlIsOnlyImage: true, + }), + ).toBe(true); + // Finder adds a copied file's name as text. + expect(shouldHandleComposerAttachmentPaste({ files: [image], plainText: "image.png" })).toBe( + true, + ); }); it("preserves text when the clipboard also includes generic image files", () => { diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 041db7193d2e2..191c5841185ff 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -239,30 +239,46 @@ export function attachmentsToReleaseOnUploadCapabilityLoss( ); } +function isOnlyFileNames(text: string, files: ReadonlyArray): boolean { + const names = new Set(files.map((file) => file.name)); + return text + .split(/\r?\n/) + .filter((line) => line.length > 0) + .every((line) => names.has(line)); +} + +/** A browser's Copy Image puts only an in text/html; rich text sources put the text there. */ +export function isImageOnlyClipboardHtml(html: string): boolean { + if (html.length === 0) return false; + const body = new DOMParser().parseFromString(html, "text/html").body; + return body.querySelector("img") !== null && (body.textContent ?? "").trim().length === 0; +} + export function shouldHandleComposerAttachmentPaste(input: { readonly files: ReadonlyArray; readonly plainText: string; readonly bypassAutoAttachment?: boolean; + readonly htmlIsOnlyImage?: boolean; }): boolean { // Paste as Text keeps the text even when the source also put an image of it on the clipboard. if (input.bypassAutoAttachment && input.plainText.length > 0) return false; if ( - input.files.some((file) => { - if (isDngFile(file)) return true; - const classification = classifyComposerAttachmentFile(file); - return ( - classification === "image" || - classification === "unsupported-image" || - isSvgAttachment({ name: file.name, mimeType: file.type }) - ); - }) + input.files.some( + (file) => isDngFile(file) || isSvgAttachment({ name: file.name, mimeType: file.type }), + ) ) { return true; } - - if (input.plainText.length > 0) { - return false; + const hasImage = input.files.some((file) => { + const classification = classifyComposerAttachmentFile(file); + return classification === "image" || classification === "unsupported-image"; + }); + if (input.plainText.length === 0) { + return hasImage || input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); } - - return input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); + // Rich text sources (Word, Pages) add a picture of the text. Copy Image adds the image URL as + // text beside an , and a Finder copy adds the file names. + return ( + hasImage && (input.htmlIsOnlyImage === true || isOnlyFileNames(input.plainText, input.files)) + ); } From 3b3f8808f43cd67a82e19cbdc5cfcefa7f8d56d4 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 22 Nov 2026 00:03:48 -0600 Subject: [PATCH 006/162] fix(web): wait for image uploads before sending (#40672) Co-authored-by: Cursor Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../src/components/ChatView.browser.test.tsx | 103 ++++++++++++++++++ apps/web/src/components/ChatView.tsx | 24 +++- apps/web/src/components/chat/ChatComposer.tsx | 91 ++++++++++++---- .../chat/ComposerFooterControls.tsx | 2 + .../chat/ComposerHeldSendBanner.tsx | 50 +++++++++ .../chat/ComposerPrimaryActions.tsx | 30 +++-- .../chat/preparingComposerImages.test.ts | 58 ++++++++++ .../chat/preparingComposerImages.ts | 90 +++++++++++++++ .../chat/useComposerAttachmentIntake.ts | 34 +++--- .../components/chat/useComposerSelection.ts | 6 + .../src/components/chat/useComposerSend.ts | 36 +++++- apps/web/src/i18n/translations/de.json | 20 ++-- apps/web/src/i18n/translations/en.json | 20 ++-- apps/web/src/i18n/translations/es.json | 20 ++-- apps/web/src/i18n/translations/fr.json | 20 ++-- apps/web/src/i18n/translations/ja.json | 20 ++-- apps/web/src/i18n/translations/ko.json | 20 ++-- apps/web/src/i18n/translations/pt-BR.json | 20 ++-- apps/web/src/i18n/translations/ru.json | 20 ++-- apps/web/src/i18n/translations/sv.json | 20 ++-- apps/web/src/i18n/translations/zh.json | 20 ++-- 21 files changed, 594 insertions(+), 130 deletions(-) create mode 100644 apps/web/src/components/chat/ComposerHeldSendBanner.tsx create mode 100644 apps/web/src/components/chat/preparingComposerImages.test.ts diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index ae6628ba6733c..cfd06a8864e0d 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -112,6 +112,19 @@ vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (i return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; }); +// Null runs the real compression; a test sets it to hold an image in preparation. +const compression = vi.hoisted(() => ({ gate: null as Promise | null })); +vi.mock(import("~/lib/imageCompression"), async (original) => { + const actual = await original(); + return { + ...actual, + prepareImageForAttachment: async (...args) => { + await compression.gate; + return actual.prepareImageForAttachment(...args); + }, + }; +}); + vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ ...(await original()), trackRpcRequestSent: () => {}, @@ -438,6 +451,96 @@ it("an interrupted image-only first send of a new thread says it may not have be expect(page.getByText("Copy message", { exact: true }).query()).toBeNull(); }); +it.each(["new", "existing"] as const)( + "Enter while an image compresses shows a cancellable banner, cancels on edit or Esc, and still sends after leaving a %s thread", + async (kind) => { + const thread = threadWithHistory(`upload-wait-${kind}`, 1); + const other = threadWithHistory(`upload-wait-other-${kind}`, 1); + using _environment = installFakeEnvironment(kind === "existing" ? [thread, other] : [other], { + acceptCommands: true, + }); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const draftId = DraftId.make(`draft-upload-wait-${kind}`); + if (kind === "new") { + useComposerDraftStore + .getState() + .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { + threadId: thread.id, + }); + } + using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt); + const router = getRouter( + createMemoryHistory({ + initialEntries: [kind === "new" ? `/draft/${draftId}` : `/${ENVIRONMENT_ID}/${thread.id}`], + }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + const compressed = Promise.withResolvers(); + compression.gate = compressed.promise; + using _compression = { [Symbol.dispose]: () => (compression.gate = null) }; + using _uploads = acceptAttachmentUploads(); + const editor = page.getByTestId("composer-editor"); + await expect.element(editor).toBeVisible(); + await expect.element(page.getByText("render", { exact: true }).first()).toBeVisible(); + + await userEvent.click(editor); + const clipboardData = new DataTransfer(); + clipboardData.items.add(new File([PNG], "shot.png", { type: "image/png" })); + editor + .element() + .dispatchEvent( + new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }), + ); + + // Enter arms the send and shows the banner plus a disabled spinner button. + await userEvent.keyboard("check image{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + const waitingButton = page.getByRole("button", { name: "Sending when ready", exact: true }); + await expect.element(waitingButton).toBeDisabled(); + await expect.element(waitingButton).toHaveAttribute("aria-busy", "true"); + + // Typing disarms the queued send and keeps the edit. + await userEvent.keyboard(" now"); + await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument(); + await expect.element(editor).toHaveTextContent("check image now"); + + // Enter arms again; Esc cancels cleanly. + await userEvent.keyboard("{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + await userEvent.keyboard("{Escape}"); + await expect.element(page.getByText("Sending once image is ready")).not.toBeInTheDocument(); + + // Enter arms again; leaving the thread still sends once the image is ready. + await userEvent.keyboard("{Enter}"); + await expect.element(page.getByText("Sending once image is ready")).toBeVisible(); + await router.navigate({ to: `/${ENVIRONMENT_ID}/${other.id}` }); + await expect.element(page.getByText(`Answer 0 for upload-wait-other-${kind}.`)).toBeVisible(); + + compressed.resolve(); + await vi.waitFor(() => { + if (kind === "new") { + expect(launch.calls).toHaveLength(1); + } else { + expect(dispatchedCommands()).toContainEqual( + expect.objectContaining({ + type: "message.dispatch", + threadId: thread.id, + attachments: [expect.objectContaining({ type: "image", id: "upload-1" })], + }), + ); + } + }); + launch.release(); + }, +); + it("opens the thread actions menu for an older settled thread the shell leaves out", async () => { const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const }; using _environment = installFakeEnvironment([thread]); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index ea16d027fcfe9..254bbd4eb9e42 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -59,7 +59,9 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import type { UsageLimitSourceSnapshots } from "@t3tools/contracts"; import { feedbackBannerItem } from "./chat/ComposerFeedback"; import { freshSessionBannerItem } from "./chat/ComposerFreshSession"; +import { heldComposerSendBannerItem } from "./chat/ComposerHeldSendBanner"; import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./chat/freshSessionArms"; +import { cancelHeldComposerSend, useComposerSendHeld } from "./chat/preparingComposerImages"; import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel"; import { useWorktreeSetup } from "./chat/useWorktreeSetup"; import { useChatShortcuts } from "./chat/useChatShortcuts"; @@ -253,6 +255,7 @@ import { type ComposerFileAttachment, type ComposerImageAttachment, type DraftThreadEnvMode, + composerTargetKey, useComposerDraftStore, DraftId, } from "../composerDraftStore"; @@ -2658,7 +2661,16 @@ export default function ChatView(props: ChatViewProps) { // While a question or approval owns the composer, its text answers that, not the agent. const freshSessionCommandAvailable = freshSessionAvailable && activePendingApproval === null && pendingUserInputs.length === 0; - const toggleKeepFullHistory = () => setKeepFullHistory(routeThreadKey, !keepFullHistory); + const composerDraftTargetKey = composerTargetKey(composerDraftTarget); + const composerSendHeld = useComposerSendHeld(composerDraftTargetKey); + const cancelHeldSendStable = useStableCallback(() => { + cancelHeldComposerSend(composerDraftTargetKey); + focusComposerStable(); + }); + const toggleKeepFullHistory = () => { + cancelHeldComposerSend(composerDraftTargetKey); + setKeepFullHistory(routeThreadKey, !keepFullHistory); + }; const toggleKeepFullHistoryStable = useStableCallback(toggleKeepFullHistory); const armFreshSessionStable = useStableCallback(() => armFreshSession(routeThreadKey)); const handleRestoreThreadBranch = () => { @@ -2769,6 +2781,14 @@ export default function ChatView(props: ChatViewProps) { freshSessionPending && activePendingApproval === null ? [freshSessionBannerItem(() => disarmFreshSession(routeThreadKey), messages)] : []; + const heldSendItems = composerSendHeld + ? [ + heldComposerSendBannerItem( + { draftTarget: composerDraftTarget, onCancel: cancelHeldSendStable }, + messages, + ), + ] + : []; if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) { return [ ...feedbackBannerItems, @@ -2778,6 +2798,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, ]; } @@ -2789,6 +2810,7 @@ export default function ChatView(props: ChatViewProps) { ...usageLimitsItems, ...projectCloneItems, ...freshSessionItems, + ...heldSendItems, ...systemComposerBannerItems, branchMismatchBannerItem( { diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 6d4487adef153..6fb651c3471f6 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -252,6 +252,7 @@ import { useNavigate } from "@tanstack/react-router"; import { assistantCitationLabel } from "@t3tools/shared/assistantCitations"; import { assistantCitationNavigation } from "../../lib/assistantCitationNavigation"; import { Button } from "../ui/button"; +import { Spinner } from "../ui/spinner"; import { useManagedPolicy } from "../../state/managedPolicy"; import { hasProviderSetup } from "./ProviderStatusBanner"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; @@ -286,10 +287,13 @@ import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; import { + cancelHeldComposerSend, countPreparingComposerImages, + useComposerSendHeld, usePreparingComposerImages, useSubmitAfterPreparingImages, } from "./preparingComposerImages"; +import { HELD_COMPOSER_SEND_BANNER_ID } from "./ComposerHeldSendBanner"; import { ComposerControlsBar } from "./ComposerControlsBar"; import { composerCommandKeyHandler } from "./composerCommandKey"; import { promptSuggestionToAccept, usePromptSuggestion } from "./usePromptSuggestion"; @@ -729,8 +733,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) uncommittedSnapShotIds, standaloneComposerImages, } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations); - const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter( - (image) => !image.hidden, + const allPreparingComposerImages = usePreparingComposerImages(attachmentTargetKey); + const preparingComposerImages = allPreparingComposerImages.filter((image) => !image.hidden); + // A message send waits for these itself; an answer waits in the composer below. + const messageHasPreparingImages = + questionAttachmentTarget === null && allPreparingComposerImages.length > 0; + const composerSendHeld = useComposerSendHeld(composerDraftTargetKey); + const cancelHeldSend = () => cancelHeldComposerSend(composerDraftTargetKey); + const handleMultipleModelSelectionsChangeStable = useStableCallback( + (next: React.SetStateAction | null>) => { + cancelHeldSend(); + setMultipleModelSelections(next); + }, ); const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); @@ -1267,21 +1281,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isComplete: Boolean(activePendingResolvedAnswers), } : null; + const hasMessageToSend = composerSendState.hasSendableContent || messageHasPreparingImages; const showResumeAction = - canResume && !composerDraftHasUserContent(composerDraft) && !isEditingQueuedMessage; + canResume && + !composerDraftHasUserContent(composerDraft) && + !messageHasPreparingImages && + !isEditingQueuedMessage; const collapsedComposerPrimaryActionDisabled = phase === "running" || isSendBusy || + composerSendHeld || isSendDisabled || noProviderAvailable || projectSelectionRequired || environmentUnavailable !== null || - (!composerSendState.hasSendableContent && !showResumeAction); - const collapsedComposerPrimaryActionLabel = showResumeAction - ? gt("Resume thread") - : props.resumeCompactionTokens !== null && !props.keepFullHistory - ? gt("Open composer to compact and send") - : gt("Send message"); + (!hasMessageToSend && !showResumeAction); + const collapsedComposerPrimaryActionLabel = composerSendHeld + ? gt("Sending when ready") + : showResumeAction + ? gt("Resume thread") + : props.resumeCompactionTokens !== null && !props.keepFullHistory + ? gt("Open composer to compact and send") + : gt("Send message"); const showMobilePendingAnswerActions = isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null; @@ -2196,7 +2217,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (activePendingProgress) { return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers); } - return composerSendState.hasSendableContent; + return hasMessageToSend; }; const submitComposerRef = useRef< @@ -2282,9 +2303,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) event?.preventDefault(); return false; } - // Sending now would leave a still-compressing image out of the turn, so wait for it. + if (composerSendHeld) { + event?.preventDefault(); + return false; + } + // Sending now would leave a still-compressing image out of the answer, so wait for it. if ( activeThreadId && + questionAttachmentTarget && submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent)) ) { event?.preventDefault(); @@ -2467,8 +2493,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? promptSuggestion : null; - const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => - composerCommandKeyHandler({ + const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => { + if (key === "Escape" && composerSendHeld && !event.isComposing) { + cancelHeldSend(); + return true; + } + return composerCommandKeyHandler({ keybindings, getShortcutContext, sendShortcut: settings.sendShortcut, @@ -2507,6 +2537,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptSuggestion: offeredPromptSuggestion, dismissPromptSuggestion, })(key, event, isTaskItem); + }; const { stashQueue, @@ -2615,7 +2646,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isSendBusy={isSendBusy} multipleModelsEnabled={routeKind === "draft" && supportsMultipleModels} multipleModelSelections={multipleModelSelections} - onMultipleModelSelectionsChange={setMultipleModelSelections} + onMultipleModelSelectionsChange={handleMultipleModelSelectionsChangeStable} selectedModelSelection={selectedModelSelection} onProviderModelSelect={onProviderModelSelect} activeThreadModelSelection={activeThreadModelSelection} @@ -2713,7 +2744,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const shelfItems = hasBlockingComposerTopDrawer ? bannerItems.filter( (item) => - item.group === "environment" && (item.variant === "error" || item.variant === "warning"), + item.id === HELD_COMPOSER_SEND_BANNER_ID || + (item.group === "environment" && + (item.variant === "error" || item.variant === "warning")), ) : bannerItems; @@ -3518,6 +3551,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
    { + if ( + event.key === "Escape" && + composerSendHeld && + !event.defaultPrevented && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + cancelHeldSend(); + } + }} onFocusCapture={(event) => { const activeElement = event.target; if ( @@ -3652,7 +3696,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) canOperateThread={canOperateThread} canInterrupt={canInterrupt} runId={activeThread?.runtime?.activeRunId ?? null} - hasSendableContent={composerSendState.hasSendableContent} + hasSendableContent={hasMessageToSend} isEditingQueuedMessage={isEditingQueuedMessage} onInterrupt={handleInterruptPrimaryActionStable} > @@ -3662,6 +3706,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) className="flex size-8 shrink-0 items-center justify-center rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover disabled:opacity-64" disabled={collapsedComposerPrimaryActionDisabled} aria-label={collapsedComposerPrimaryActionLabel} + aria-busy={composerSendHeld || isSendBusy || undefined} onPointerDown={(event) => event.preventDefault()} onClick={(event) => { event.stopPropagation(); @@ -3671,7 +3716,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) else submitComposer(); }} > - {showResumeAction ? ( + {composerSendHeld || isSendBusy ? ( +
    @@ -575,7 +583,7 @@ function TopStatusIcon(props: { icon: keyof typeof TOP_STATUS_ICONS; className: type SidebarThreadRowProps = { thread: SidebarThreadSummary; // "folder" is a one-line row inside a boring sidebar project folder; - // "folder-multiline" adds the card's branch and PR line under it. + // "folder-multiline" adds the card's environment and PR line under it. variant: "card" | "slim" | "folder" | "folder-multiline"; navigationParent?: string | undefined; variantAction: SidebarSweepAction; @@ -598,10 +606,8 @@ type SidebarThreadRowProps = { // Read at click time; a prop would re-render every row on entering or leaving a thread route. readOpensPullRequestsInRightPanel: () => boolean; jumpLabel: string | null; - currentEnvironmentId: string | null; environmentLabel: string | null; environmentMachine: EnvironmentMachineKind; - scratchMachineLabel: string | null; project: EnvironmentProject | null; projectDisplayName: string | null; providerEntryByInstanceId: ReadonlyMap; @@ -863,9 +869,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ? getTriggerDisplayModelName(selectedModel, providerEntry?.driverKind) : thread.modelSelection.model; - const isRemote = thread.environmentId !== props.currentEnvironmentId; - const showsScratchMachine = !checkoutThread.branch && props.scratchMachineLabel !== null; - const detailsTooltip = ( - - - ) : null; const diff = latestRunDiff(thread); // Only the trailing icons would remain, so the row moves them to the title line instead. const metaLineEmpty = - !checkoutThread.branch && - !showsScratchMachine && + props.environmentLabel === null && prBadge === null && issueBadge === null && diff === null && runningTerminalIds.length === 0; const metaLine = metaLineEmpty ? null : (
    - {checkoutThread.branch ? ( - <> - - - - - - ) : showsScratchMachine ? ( + {props.environmentLabel !== null ? ( <> - {props.scratchMachineLabel} + {props.environmentLabel} ) : ( @@ -1305,7 +1294,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP aria-hidden className="pointer-events-none ml-auto inline-flex shrink-0 items-center gap-1" > - {remoteMachineIcon} - {remoteMachineIcon} Date: Sun, 22 Nov 2026 00:52:35 -0800 Subject: [PATCH 020/162] fix: a failed checkpoint capture keeps Edit from here for conversation rewind (#40745) --- .../CheckpointCaptureService.test.ts | 17 ++++++++++ .../CheckpointRollbackService.test.ts | 31 ++++++++++++++++--- .../CheckpointRollbackService.ts | 4 ++- .../src/orchestration-v2/Orchestrator.ts | 3 +- .../src/orchestration-v2/ProjectionStore.ts | 4 +-- .../src/orchestration-v2/runtimeLayer.test.ts | 22 +++++++++++++ apps/web/src/session-logic.test.ts | 10 +++++- apps/web/src/session-logic.ts | 6 ++-- .../client-runtime/src/operations/commands.ts | 4 +-- 9 files changed, 86 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts index aa85cd675dc1a..2110bc3eca027 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.test.ts @@ -956,6 +956,23 @@ it.layer(layerProjectionStoreTest)("CheckpointCaptureServiceV2", (it) => { scopeId: cancelledScopeId, }); assert.deepEqual(afterRewind.preservedCheckpointOrdinals, [0]); + + // A failed capture still records which run ended there; the next capture must keep that link. + yield* projectionStore.apply({ + id: EventId.make("event:checkpoint-capture-cancelled:captured-error"), + type: "checkpoint.captured", + threadId: cancelledThreadId, + runId: cancelledRunId, + nodeId: cancelledRootNodeId, + providerInstanceId, + occurredAt: cancelledAt, + payload: { ...captured, status: "error" }, + }); + const afterFailedCapture = yield* projectionStore.getCheckpointCaptureContext( + cancelledThreadId, + { runId: cancelledRunId, scopeId: cancelledScopeId }, + ); + assert.deepEqual([...afterFailedCapture.preservedCheckpointOrdinals].toSorted(), [0, 1]); }), ); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index 2f41a9a379306..ff368dccb64d9 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -401,9 +401,14 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.effect.each([{ restoreFiles: true }, { restoreFiles: false }])( - "holds turn starts inside the worktree during rollback with restoreFiles $restoreFiles", - ({ restoreFiles }) => +it.effect.each([ + { restoreFiles: true, status: "ready" }, + { restoreFiles: false, status: "ready" }, + // A failed capture still pins the conversation. + { restoreFiles: false, status: "error" }, +])( + "holds turn starts inside the worktree during rollback with restoreFiles $restoreFiles to a $status checkpoint", + ({ restoreFiles, status }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -438,7 +443,7 @@ it.effect.each([{ restoreFiles: true }, { restoreFiles: false }])( providerInstanceId, }, providerSession: undefined, - checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 }, + checkpoint: { id: checkpointId, scopeId, status, appRunOrdinal: 0 }, scope: { id: scopeId, cwd: worktreePath }, runsToRollback: [], targetAttempt: undefined, @@ -840,7 +845,7 @@ const seedRollbackHistory = Effect.gen(function* () { ), ), ); - const rollback = (ordinal: number) => + const rollback = (ordinal: number, restoreFiles?: boolean) => Effect.gen(function* () { const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; yield* service.execute({ @@ -848,6 +853,7 @@ const seedRollbackHistory = Effect.gen(function* () { providerThreadId, scopeId, checkpointId: checkpointId(ordinal), + ...(restoreFiles === undefined ? {} : { restoreFiles }), }); }).pipe(Effect.provide(serviceLayer)); @@ -943,6 +949,21 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe }), ); + it.effect("rewinds the conversation to a run whose snapshot capture failed", () => + Effect.gen(function* () { + const history = yield* seedRollbackHistory; + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE orchestration_v2_projection_checkpoints + SET status = 'error', payload_json = json_set(payload_json, '$.status', 'error') + WHERE checkpoint_id = ${history.checkpointId(2)}`; + + yield* history.rollback(2, false); + + assert.deepEqual(history.rollbackCounts, [4]); + assert.deepEqual(history.restored, []); + }), + ); + it.effect( "rewinds stopped runs repeatedly without counting discarded provider turns again", () => diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 6f9fe79cfde3b..8d6fd1c09441d 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -178,8 +178,10 @@ export const layer: Layer.Layer< // A repository's checkpoints follow the thread's; they are not a place to rewind to. typeof scope.repositoryPath === "string" || checkpoint.scopeId !== scope.id || - // Missing snapshots support conversation rewind, and restoring a task folder's repositories. + // Missing or failed snapshots support conversation rewind; missing ones also restoring a + // task folder's repositories. (checkpoint.status !== "ready" && + !(checkpoint.status === "error" && !restoreFiles) && !(checkpoint.status === "missing" && (!restoreFiles || linkedProjectFolder))) ) { return yield* invalidTarget(); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 995ff63b25747..61f5027793569 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14534,9 +14534,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio targetCheckpoint.appRunOrdinal ?? 0, ) !== null, ); - // Missing snapshots otherwise support conversation rewind only. + // Missing or failed snapshots otherwise support conversation rewind only. if ( targetCheckpoint.status !== "ready" && + !(targetCheckpoint.status === "error" && command.restoreFiles === false) && !( targetCheckpoint.status === "missing" && (command.restoreFiles === false || restoresRepositories) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 6c8308706b651..a42679d304765 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -6379,7 +6379,7 @@ export const layer: Layer.Layer = runRows[0] === undefined ? undefined : yield* decodeRunPayload(runRows[0].payload_json); - const preservedCheckpoint = sql`(status = 'ready' OR (status = 'missing' AND run_id IS NOT NULL))`; + const preservedCheckpoint = sql`(status = 'ready' OR (status IN ('missing', 'error') AND run_id IS NOT NULL))`; const [ nodeRows, scopeRows, @@ -6491,7 +6491,7 @@ export const layer: Layer.Layer = checkpoint === undefined || scope === undefined || checkpoint.scopeId !== scope.id || - (checkpoint.status !== "ready" && checkpoint.status !== "missing") || + checkpoint.status === "stale" || providerThread.id !== thread.activeProviderThreadId || providerThread.providerInstanceId !== thread.modelSelection.instanceId ) diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index b5072355659ef..843e51da40423 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1878,6 +1878,28 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { [], ); assert.deepEqual(yield* outbox.listByCommandId(commandId), []); + if (status === "error") { + // A failed capture still pins the conversation. + const conversationCommandId = CommandId.make("runtime-rollback-error-conversation"); + const conversationOnly = yield* orchestrator.dispatch({ + type: "checkpoint.rollback", + commandId: conversationCommandId, + threadId, + checkpointId, + scopeId: scope.id, + restoreFiles: false, + }); + assert.deepEqual( + conversationOnly.storedEvents.map((stored) => stored.event.type), + ["thread.metadata-updated", "checkpoint.rollback-requested"], + ); + assert.deepEqual( + (yield* outbox.listByCommandId(conversationCommandId)).map( + (effect) => effect.request.type, + ), + ["provider-thread.rollback"], + ); + } } } }).pipe(Effect.provide(Layer.fresh(layerTest))), diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index f4670665add6c..2155fedaa83c1 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -290,7 +290,10 @@ describe("V2 session presentation", () => { }, }; }); - const checkpoint = (ordinal: number, status: "ready" | "missing" | "stale" = "ready") => ({ + const checkpoint = ( + ordinal: number, + status: "ready" | "missing" | "stale" | "error" = "ready", + ) => ({ runId: runId(ordinal), checkpointTurnCount: ordinal, checkpointRef: `checkpoint-${ordinal}` as never, @@ -326,6 +329,11 @@ describe("V2 session presentation", () => { "user-1": 0, "user-2": 1, }); + // A failed snapshot capture still pins the conversation; only file restore needs one. + expect(targets([1, 2], [checkpoint(1, "error")])).toEqual({ + "user-1": 0, + "user-2": 1, + }); }); it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 1122c3122aca0..5196ee43458d8 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -1153,10 +1153,10 @@ export function deriveRevertTurnCountByUserMessageId(input: { return byUserMessageId; } -// A missing snapshot (no git, or a side chat) still pins a conversation position; only -// restoring files needs a ready one. +// A missing or failed snapshot (no git, a side chat, a capture error) still pins a +// conversation position; only restoring files needs a ready one. function isRewindableCheckpoint(checkpoint: Pick) { - return checkpoint.status === "ready" || checkpoint.status === "missing"; + return checkpoint.status !== "stale"; } export function findRevertCheckpoint( diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index 50e1449e3d5fc..0ea95420460a7 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -1074,9 +1074,9 @@ export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThrea ); if ( checkpoint === undefined || - // Missing snapshots support conversation rewind only. + // Missing or failed snapshots support conversation rewind only. (checkpoint.status !== "ready" && - !(input.restoreFiles === false && checkpoint.status === "missing")) + !(input.restoreFiles === false && checkpoint.status !== "stale")) ) { const target = input.checkpointId === undefined From 15a3daa32a745bc56be9d7dbb346d80661e6b7bd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:00:28 -0800 Subject: [PATCH 021/162] docs(claude): mobile shows the compact chip too (#40755) --- docs/user/providers-claude.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 84c13d30c4c84..00b27e02ae23d 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -63,8 +63,8 @@ When you return to a large thread after Claude's prompt cache expires, a **Compact** chip with the thread's token count shows next to the send button. While it is on, Enter summarizes the history first, then sends your message. Click the chip to switch it to **Keep** and keep the full -history for that message. The mobile app shows no chip: an eligible message sent -from it summarizes first. The cache lasts about an hour on a Claude +history for that message. The mobile app shows the same chip, labelled with the +token count: tap it to keep the full history for that message. The cache lasts about an hour on a Claude subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using composer commands. From e3f9db2447fcfd82e76f7782ca5254e2c7ad80a6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:08:22 -0800 Subject: [PATCH 022/162] fix(server): TanStack Source pull requests open from every client, and private ones work end to end (#40741) --- .../pull-requests/PullRequestListRow.tsx | 12 ++ .../pull-requests/PullRequestRouteScreen.tsx | 11 ++ .../pull-requests/pullRequestGlyphs.ts | 1 + .../features/pull-requests/pullRequestList.ts | 1 + apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + apps/server/src/git/GitManager.test.ts | 133 ++++++++++++++++ apps/server/src/git/GitManager.ts | 144 +++++++++++++++++- .../toolkits/pullRequests/handlers.test.ts | 15 +- .../src/mcp/toolkits/pullRequests/handlers.ts | 2 + .../src/mcp/toolkits/pullRequests/tools.ts | 8 + .../src/provider/agentContextBudget.json | 2 +- .../src/pullRequest/PullRequestService.ts | 4 + .../SourceControlProviderRegistry.ts | 9 ++ .../pullRequest/PullRequestDetailLayout.tsx | 29 +++- .../pullRequest/PullRequestDetailPanel.tsx | 2 + .../components/pullRequest/PullRequestRow.tsx | 4 + docs/user/source-control.md | 4 +- packages/contracts/src/pullRequest.ts | 8 + .../src/server/PullRequestProvider.ts | 3 + .../src/server/SourceControlProvider.ts | 14 ++ .../TanStackSourcePullRequestProvider.test.ts | 138 +++++++++++++++++ ...anStackSourceSourceControlProvider.test.ts | 107 ++++++++++++- .../TanStackSourceSourceControlProvider.ts | 46 +++++- .../src/server/tanStackSourceHosts.test.ts | 19 +++ .../src/server/tanStackSourceHosts.ts | 16 +- .../src/server/tanStackSourceJson.test.ts | 1 + .../src/server/tanStackSourceJson.ts | 27 +++- .../src/shared/definition.test.ts | 16 ++ .../src/shared/definition.ts | 19 ++- 38 files changed, 774 insertions(+), 31 deletions(-) create mode 100644 packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts create mode 100644 packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts diff --git a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx index 5daf5ef20565b..7b904c8e33105 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx @@ -122,6 +122,7 @@ export const PullRequestListRow = memo( ), item.title, status.label, + item.visibility === "private" ? gt("Private") : null, conflict ? conflict.label.toLowerCase() : null, gt("by {author}", { author: item.author?.login ?? gt("unknown author") }), review ? review.accessibleLabel : null, @@ -178,6 +179,17 @@ export const PullRequestListRow = memo( {item.repository} #{item.number} + {item.visibility === "private" ? ( + + + + ) : null} {item.stack ? ( {status.label} )} + {"visibility" in pr && pr.visibility === "private" ? ( + + + {gt("Private")} + + ) : null} {"changedFiles" in pr && pr.changedFiles !== undefined ? ( diff --git a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts index fa79d882cc23d..16b84c596d627 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts @@ -7,4 +7,5 @@ export const PullRequestGlyph = { merged: "arrow.triangle.merge", stack: "square.3.layers.3d", conflicting: "exclamationmark.triangle", + private: { ios: "lock.fill", android: "lock" }, } as const satisfies Record; diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.ts b/apps/mobile/src/features/pull-requests/pullRequestList.ts index e7c2f5de769c4..3b30c11d65e64 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestList.ts @@ -190,6 +190,7 @@ export function pullRequestListRowsAreEqual( previous.title === next.title && previous.url === next.url && previous.state === next.state && + previous.visibility === next.visibility && previous.isDraft === next.isDraft && previous.mergeability === next.mergeability && previous.baseBranch === next.baseBranch && diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index f538b87920412..039e1ddadd0bf 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tippe auf eine Person, um ein Review anzufordern. Tippe auf einen angefragten Reviewer, um die Anfrage zu entfernen. Änderungen werden beim Schließen dieses Fensters gesendet.", "8d3770f150f0bcb4": "Angefragt", "fff1c3d17603f394": "Dieser Anbieter akzeptiert eine Reviewer-ID, kann aber keine Kandidaten auflisten.", + "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Basis-Branch {branch} kopieren", "06a684782801e8f7": "Head-Branch {branch} kopieren", "8e4f3c862193b8a5": "Bearbeiten", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 745201ad99094..91170171c1621 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tap someone to request a review. Tap a requested reviewer to remove the request. Changes are sent when you close this sheet.", "8d3770f150f0bcb4": "Requested", "fff1c3d17603f394": "This provider accepts a reviewer ID but cannot list candidates.", + "bbb7d40a7ad7ab71": "Private", "85ae9979ad3b0c1e": "Copy base branch {branch}", "06a684782801e8f7": "Copy head branch {branch}", "8e4f3c862193b8a5": "Edit", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index fb134339cd3c4..398c20ce17f1f 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Toca a alguien para solicitarle una revisión. Toca a un revisor solicitado para quitar la solicitud. Los cambios se envían al cerrar esta hoja.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este proveedor acepta un ID de revisor, pero no puede listar candidatos.", + "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar la rama base {branch}", "06a684782801e8f7": "Copiar la rama head {branch}", "8e4f3c862193b8a5": "Editar", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index d6aef220df3a2..1734d91934a04 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Touchez une personne pour lui demander une revue. Touchez un relecteur sollicité pour retirer la demande. Les modifications sont envoyées à la fermeture de ce panneau.", "8d3770f150f0bcb4": "Sollicité", "fff1c3d17603f394": "Ce fournisseur accepte un ID de relecteur mais ne peut pas lister les candidats.", + "bbb7d40a7ad7ab71": "Privé", "85ae9979ad3b0c1e": "Copier la branche de base {branch}", "06a684782801e8f7": "Copier la branche de tête {branch}", "8e4f3c862193b8a5": "Modifier", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 8cd9fba5c8332..113ada551f17d 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -2844,6 +2844,7 @@ "f9d3c8aa453829ce": "ユーザーをタップするとレビューをリクエストします。リクエスト済みのレビュアーをタップするとリクエストを削除します。変更はこのシートを閉じたときに送信されます。", "8d3770f150f0bcb4": "リクエスト済み", "fff1c3d17603f394": "このプロバイダーはレビュアー ID を受け付けますが、候補を一覧表示できません。", + "bbb7d40a7ad7ab71": "プライベート", "85ae9979ad3b0c1e": "ベースブランチ {branch} をコピー", "06a684782801e8f7": "ヘッドブランチ {branch} をコピー", "8e4f3c862193b8a5": "編集", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 731eaeecaec22..7768bd410d434 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -2848,6 +2848,7 @@ "f9d3c8aa453829ce": "검토를 요청하려면 사람을 탭하세요. 요청을 제거하려면 요청된 검토자를 탭하세요. 변경 사항은 이 시트를 닫을 때 전송됩니다.", "8d3770f150f0bcb4": "요청됨", "fff1c3d17603f394": "이 제공자는 검토자 ID를 받지만 후보를 나열할 수 없습니다.", + "bbb7d40a7ad7ab71": "비공개", "85ae9979ad3b0c1e": "기준 브랜치 {branch} 복사", "06a684782801e8f7": "헤드 브랜치 {branch} 복사", "8e4f3c862193b8a5": "편집", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 2c4ee1bc64fc4..88dbb8da5cd87 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -2847,6 +2847,7 @@ "f9d3c8aa453829ce": "Toque em alguém para solicitar uma revisão. Toque em um revisor solicitado para remover a solicitação. As alterações são enviadas quando você fecha esta folha.", "8d3770f150f0bcb4": "Solicitado", "fff1c3d17603f394": "Este provedor aceita um ID de revisor, mas não consegue listar candidatos.", + "bbb7d40a7ad7ab71": "Privado", "85ae9979ad3b0c1e": "Copiar branch base {branch}", "06a684782801e8f7": "Copiar branch head {branch}", "8e4f3c862193b8a5": "Editar", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index c4f78e560083b..2d0fb55302031 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -2899,6 +2899,7 @@ "f9d3c8aa453829ce": "Нажмите на человека, чтобы запросить ревью. Нажмите на запрошенного ревьюера, чтобы отменить запрос. Изменения отправляются при закрытии этой панели.", "8d3770f150f0bcb4": "Запрошен", "fff1c3d17603f394": "Этот провайдер принимает ID ревьюера, но не может показать список кандидатов.", + "bbb7d40a7ad7ab71": "Приватный", "85ae9979ad3b0c1e": "Копировать базовую ветку {branch}", "06a684782801e8f7": "Копировать head-ветку {branch}", "8e4f3c862193b8a5": "Изменить", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index fa3a3dd6d039f..70617afd183ca 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -2851,6 +2851,7 @@ "f9d3c8aa453829ce": "Tryck på någon för att begära en granskning. Tryck på en begärd granskare för att ta bort begäran. Ändringarna skickas när du stänger det här bladet.", "8d3770f150f0bcb4": "Begärd", "fff1c3d17603f394": "Leverantören accepterar ett granskar-id men kan inte lista kandidater.", + "bbb7d40a7ad7ab71": "Privat", "85ae9979ad3b0c1e": "Kopiera basgrenen {branch}", "06a684782801e8f7": "Kopiera huvudgrenen {branch}", "8e4f3c862193b8a5": "Redigera", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index f36e76805c298..485d4206bf054 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -2848,6 +2848,7 @@ "f9d3c8aa453829ce": "轻点某人以请求审查。轻点已请求的审查者以移除请求。关闭此面板时会发送更改。", "8d3770f150f0bcb4": "已请求", "fff1c3d17603f394": "此提供方接受审查者 ID,但无法列出候选人。", + "bbb7d40a7ad7ab71": "私有", "85ae9979ad3b0c1e": "复制基础分支 {branch}", "06a684782801e8f7": "复制头部分支 {branch}", "8e4f3c862193b8a5": "编辑", diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 94247273e1ca0..1bce13cb0f020 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -86,6 +86,8 @@ interface FakeProviderScenario { kind?: string; /** False for a host that opens every change request ready for review. */ createsDraftChangeRequests?: boolean; + /** The companion repository of a host with private change requests. */ + privateRemote?: { readonly url: string; readonly repository: string }; /** Answers to successive change request listings, whatever their head selector. */ prListSequence?: ReadonlyArray>; prListByHeadSelector?: Record>; @@ -124,6 +126,7 @@ type FakeProviderCall = readonly headSelector: string; readonly title: string; readonly draft: unknown; + readonly private?: boolean; } | { readonly operation: "getChangeRequest"; readonly reference: string } | { @@ -483,6 +486,9 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { service: { kind, createsDraftChangeRequests: scenario.createsDraftChangeRequests ?? true, + ...(scenario.privateRemote === undefined + ? {} + : { privateChangeRequestRemote: () => Effect.succeed(scenario.privateRemote!) }), ...headBranchProbe, listChangeRequests: (input) => record(input.cwd, { @@ -517,6 +523,7 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { headSelector: input.headSelector, title: input.title, draft: "draft" in input ? input.draft : undefined, + ...(input.private === undefined ? {} : { private: input.private }), }), getDefaultBranch: (input) => record(input.cwd, { operation: "getDefaultBranch" }).pipe( @@ -5106,6 +5113,132 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect( + "createPullRequest opens a private PR from the companion and never pushes to origin", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const companionDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "sec/fix"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "fix.txt"), "fix\n"); + yield* runGit(repoDir, ["add", "fix.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Fix"]); + const heads = (remote: string) => + runGit(repoDir, ["ls-remote", "--heads", remote]).pipe( + Effect.map((result) => + result.stdout + .split("\n") + .flatMap((line) => (line ? [line.split("\t")[1]] : [])) + .toSorted(), + ), + ); + const createPrivate = (manager: GitManager.GitManager["Service"]) => + manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Fix", + body: "Body", + private: true, + }); + + // A host without private pull requests refuses before anything is pushed. + const unsupported = yield* makeManager({ providerScenario: { prListSequence: [[]] } }); + const refused = yield* Effect.flip(createPrivate(unsupported.manager)); + expect(refused.message).toContain("has no private pull requests"); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + expect(created(unsupported.providerCalls)).toEqual([]); + + const privateRemote = { url: companionDir, repository: "pingdotgg/codething-mvp.private" }; + const open = { + number: 9, + title: "Fix", + url: "https://source.tanstack.com/@pingdotgg/codething-mvp/pull/9", + baseRefName: "main", + headRefName: "sec/fix", + headRepositoryNameWithOwner: privateRemote.repository, + }; + const supported = yield* makeManager({ + providerScenario: { privateRemote, prListSequence: [[], [open]] }, + }); + expect(yield* createPrivate(supported.manager)).toMatchObject({ + status: "created", + number: 9, + }); + expect(yield* heads(companionDir)).toEqual(["refs/heads/sec/fix"]); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + // The branch tracks the companion, which is how status finds its pull request. + expect( + (yield* runGit(repoDir, [ + "rev-parse", + "--abbrev-ref", + "sec/fix@{upstream}", + ])).stdout.trim(), + ).toBe("pingdotgg/sec/fix"); + expect( + (yield* runGit(repoDir, ["config", "--get", "branch.sec/fix.pushRemote"])).stdout.trim(), + ).toBe("pingdotgg"); + expect( + supported.providerCalls.flatMap((call) => + call.operation === "createChangeRequest" ? [call] : [], + ), + ).toMatchObject([{ baseRefName: "main", headSelector: "sec/fix", private: true }]); + + // Later commits follow the recorded push remote. + NodeFS.writeFileSync(NodePath.join(repoDir, "late.txt"), "late\n"); + yield* runGit(repoDir, ["add", "late.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Late"]); + const again = yield* makeManager({ + providerScenario: { privateRemote, prListSequence: [[open]] }, + }); + expect(yield* createPrivate(again.manager)).toMatchObject({ + status: "opened_existing", + number: 9, + }); + const localHead = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim(); + expect( + (yield* runGit(repoDir, ["ls-remote", companionDir, "refs/heads/sec/fix"])).stdout, + ).toContain(localHead); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + expect(created(again.providerCalls)).toEqual([]); + + // A lookup answered before the create must not hide the pull request the create returns. + yield* runGit(repoDir, ["checkout", "-b", "sec/two", "main"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "two.txt"), "two\n"); + yield* runGit(repoDir, ["add", "two.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Two"]); + const two = { ...open, number: 10, headRefName: "sec/two" }; + const warmed = yield* makeManager({ + providerScenario: { privateRemote, prListByHeadSelector: { "sec/two": [two] } }, + }); + const lookup = warmed.manager.branchPullRequest({ cwd: repoDir, branch: "sec/two" }); + expect(yield* lookup).toBeNull(); + expect(yield* createPrivate(warmed.manager)).toMatchObject({ status: "opened_existing" }); + expect(yield* lookup).toMatchObject({ number: 10 }); + yield* runGit(repoDir, ["checkout", "sec/fix"]); + + // So does a create that forgets to ask for private: it never publishes the branch. + NodeFS.writeFileSync(NodePath.join(repoDir, "later.txt"), "later\n"); + yield* runGit(repoDir, ["add", "later.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Later"]); + const forgetful = yield* makeManager({ + providerScenario: { privateRemote, prListOtherwise: [open] }, + }); + yield* Effect.exit( + forgetful.manager.createPullRequest({ + cwd: repoDir, + projectId: ProjectId.make("project-1"), + title: "Fix", + body: "Body", + }), + ); + expect(yield* heads("origin")).toEqual(["refs/heads/main"]); + }), + ); + it.effect("createPullRequest pushes to the push remote and never to the base branch", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index db62af1f79b69..dedf2d19f54ed 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -199,6 +199,12 @@ export class GitManager extends Context.Service< readonly body: string; readonly baseBranch?: string | undefined; readonly draft?: boolean | undefined; + /** + * Opens it where only people with write access see it. The branch goes to the host's + * private companion repository and never to the repository itself. Fails on a host + * without private pull requests. + */ + readonly private?: boolean | undefined; }) => Effect.Effect; readonly subscribePullRequestStateChanges: Effect.Effect< Stream.Stream, @@ -2881,9 +2887,131 @@ export const make = Effect.gen(function* () { }), ); - const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( - "GitManager.createPullRequest", - )(function* (input) { + const openPrivatePullRequest = Effect.fn("GitManager.openPrivatePullRequest")(function* ( + input: Parameters[0], + ) { + const { cwd } = input; + const provider = yield* sourceControlProvider(cwd); + const definition = sourceControlDefinitions.get(provider.kind); + const terms = definition.changeRequest; + const fail = (detail: string, cause?: unknown) => + new GitManagerError({ + operation: "createPullRequest", + cwd, + detail, + ...(cause === undefined ? {} : { cause }), + }); + if (provider.privateChangeRequestRemote === undefined) { + return yield* fail( + `${definition.label} has no private ${terms.plural}. Nothing was pushed. Leave out private to open a public one.`, + ); + } + const status = yield* gitCore.statusDetails(cwd); + const branch = status.branch; + if (!branch) return yield* fail("Cannot create a pull request from detached HEAD."); + const resolved = yield* resolvePrBase(cwd, branch, status.upstreamRef, { + isCrossRepository: false, + remoteName: publishedRemoteName( + yield* readConfigValueNullable(cwd, `branch.${branch}.remote`), + ), + }); + const baseBranch = input.baseBranch ?? resolved.baseBranch; + if (baseBranch === branch) { + return yield* fail( + `${branch} is the base branch. Check out a feature branch to create ${terms.shortLabelWithArticle}.`, + ); + } + const companion = yield* provider.privateChangeRequestRemote({ cwd }); + const remoteName = yield* gitCore.ensureRemote({ + cwd, + preferredName: companion.repository.split("/")[0] || "private", + url: companion.url, + }); + // Recorded before the push, so a later push of this branch, by T3 or by plain `git push`, + // goes to the companion too and never publishes the branch. + yield* gitCore.writeConfigValue({ + cwd, + key: `branch.${branch}.pushRemote`, + value: remoteName, + }); + yield* gitCore + .execute({ + operation: "GitManager.openPrivatePullRequest.push", + cwd, + args: ["push", "--", remoteName, `refs/heads/${branch}:refs/heads/${branch}`], + timeoutMs: null, + }) + .pipe( + Effect.mapError((cause) => + fail(`Could not push ${branch} to ${companion.repository}: ${cause.detail}`, cause), + ), + Effect.tapError(() => invalidateStatus(cwd)), + ); + // The companion branch is the pull request's head, so status finds it through the upstream. + yield* gitCore + .setBranchUpstream({ cwd, branch, remoteName, remoteBranch: branch }) + .pipe(Effect.ensuring(invalidateStatus(cwd))); + const findOpen = provider + .listChangeRequests({ cwd, headSelector: branch, state: "open" }) + .pipe( + Effect.map( + (listed) => + listed.find( + (pr) => + pr.headRefName === branch && + pr.headRepositoryNameWithOwner?.toLowerCase() === + companion.repository.toLowerCase(), + ) ?? null, + ), + ); + const existing = yield* findOpen; + if (existing) { + return { + status: "opened_existing" as const, + url: existing.url, + number: existing.number, + baseBranch: existing.baseRefName, + headBranch: existing.headRefName, + title: existing.title, + }; + } + const bodyFile = path.join( + tempDir, + `t3code-pr-body-${process.pid}-${yield* randomUUIDv4(cwd)}.md`, + ); + yield* fileSystem + .writeFileString(bodyFile, input.body) + .pipe( + Effect.mapError((cause) => fail("Failed to write pull request body temp file.", cause)), + ); + yield* provider + .createChangeRequest({ + cwd, + baseRefName: baseBranch, + headSelector: branch, + title: input.title, + bodyFile, + private: true, + ...(input.draft === true ? { draft: true } : {}), + }) + .pipe( + Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.ignore)), + Effect.ensuring(invalidateStatus(cwd)), + ); + // The PR already exists at this point, so a failed lookup only loses its metadata. + const created = yield* findOpen.pipe(Effect.orElseSucceed(() => null)); + return { + status: "created" as const, + ...(created ? { url: created.url, number: created.number } : {}), + baseBranch: created?.baseRefName ?? baseBranch, + headBranch: created?.headRefName ?? branch, + title: created?.title ?? input.title, + }; + }); + + const pushAndOpenPullRequest = Effect.fn("GitManager.pushAndOpenPullRequest")(function* ( + input: Parameters[0], + ) { const status = yield* gitCore.statusDetails(input.cwd); const needsPush = yield* createPrNeedsPush(input.cwd, status); if (needsPush && status.branch) { @@ -2935,6 +3063,16 @@ export const make = Effect.gen(function* () { : Effect.void, ), ); + return result; + }); + + const createPullRequest: GitManager["Service"]["createPullRequest"] = Effect.fn( + "GitManager.createPullRequest", + )(function* (input) { + const result = + input.private === true + ? yield* openPrivatePullRequest(input) + : yield* pushAndOpenPullRequest(input); const openedAsDraft = result.status === "created" && (yield* sourceControlProvider(input.cwd)).createsDraftChangeRequests === true; diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index b7edff187579d..7caa425d32f2e 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -837,6 +837,7 @@ describe("source control tools", () => { body: "Adds tools.", state: "open", isDraft: false, + visibility: "private", author: null, headBranch: "tools", baseBranch: "main", @@ -892,6 +893,7 @@ describe("source control tools", () => { }); const compact = yield* harness.call("pull_request_read", {}); expect(compact).toMatchObject({ + visibility: "private", headSha: "abc123", checks: { passed: 2, pending: 1, failed: ["Lint", "E2E"], incomplete: true }, unresolvedThreads: 1, @@ -1178,7 +1180,11 @@ describe("source control tools", () => { it.effect("opens a PR from the thread's worktree and links it even if dismissed", () => Effect.gen(function* () { - const opened: Array<{ readonly cwd: string; readonly draft: boolean | undefined }> = []; + const opened: Array<{ + readonly cwd: string; + readonly draft: boolean | undefined; + readonly private: boolean | undefined; + }> = []; const harness = yield* makeHarness({ thread: { ...makeThread([makeLink(43, { source: "stack-dismissed" })]), @@ -1186,7 +1192,9 @@ describe("source control tools", () => { }, git: { createPullRequest: (input) => - Effect.sync(() => opened.push({ cwd: input.cwd, draft: input.draft })).pipe( + Effect.sync(() => + opened.push({ cwd: input.cwd, draft: input.draft, private: input.private }), + ).pipe( Effect.as({ status: "created" as const, url: "https://github.com/t3tools/t3code/pull/43", @@ -1202,9 +1210,10 @@ describe("source control tools", () => { title: "Add tools", body: "Adds tools.", draft: true, + private: true, }); expect(result).toMatchObject({ number: 43, created: true }); - expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true }]); + expect(opened).toEqual([{ cwd: "/workspace/worktree", draft: true, private: true }]); expect(yield* Ref.get(harness.commands)).toMatchObject([ { type: "thread.pull-request.link", number: 43, source: "created" }, ]); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index f85d8f0abac4a..e422a799f3d9a 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -617,6 +617,7 @@ const make = Effect.gen(function* () { title: detail.title, state: detail.state, isDraft: detail.isDraft, + ...(detail.visibility === undefined ? {} : { visibility: detail.visibility }), author: detail.author?.login ?? null, headBranch: detail.headBranch, baseBranch: detail.baseBranch, @@ -1052,6 +1053,7 @@ const make = Effect.gen(function* () { body: input.body, baseBranch: input.base, draft: input.draft, + private: input.private, }) .pipe(Effect.mapError(forgeFailure)); if (created.url === undefined) { diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 71d0a28d4e392..847ae4ef19e7d 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -16,6 +16,7 @@ import { PullRequestReviewGuideRun, PullRequestState, PullRequestUnavailableError, + PullRequestVisibility, PullRequestWatchUntil, ThreadPullRequestLinkSource, TrimmedNonEmptyString, @@ -517,6 +518,9 @@ export const ReadPullRequestResult = Schema.Struct({ title: Schema.String, state: PullRequestState, isDraft: Schema.Boolean, + visibility: Schema.optional(PullRequestVisibility).annotate({ + description: "Only on a host with private PRs.", + }), author: Schema.NullOr(Schema.String), headBranch: Schema.String, baseBranch: Schema.String, @@ -675,6 +679,10 @@ const CreatePullRequestTool = Tool.make("pull_request_create", { body: Schema.String, base: Schema.optional(TrimmedNonEmptyString), draft: Schema.optional(Schema.Boolean), + private: Schema.optional(Schema.Boolean).annotate({ + description: + "Visible to writers only; the branch never reaches origin. Fails on a host without private PRs.", + }), }), success: CreatePullRequestResult, failure: PullRequestToolError, diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 139eba175bc8a..9ec6f6509f48c 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59052 + "mcpToolListJsonBytes": 59192 } diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index e30938735c765..59ece029219df 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -1370,6 +1370,7 @@ export const make = Effect.gen(function* () { ...(input.item.checksState === undefined || input.item.checksState === null ? {} : { checksState: input.item.checksState }), + ...(input.item.visibility === undefined ? {} : { visibility: input.item.visibility }), viewerReviewRequested: input.item.author?.login.toLowerCase() !== viewer && input.item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer), @@ -1993,6 +1994,9 @@ export const make = Effect.gen(function* () { ...(changeRequest.mergeQueueRemoval === undefined ? {} : { mergeQueueRemoval: changeRequest.mergeQueueRemoval }), + ...(changeRequest.visibility === undefined + ? {} + : { visibility: changeRequest.visibility }), })), ), ), diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index 06616a914b1e9..98c560cbf4973 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -222,6 +222,15 @@ function bindProviderContext( context: input.context ?? context, }); }), + ...(provider.privateChangeRequestRemote === undefined + ? {} + : { + privateChangeRequestRemote: (input) => + provider.privateChangeRequestRemote!({ + ...input, + context: input.context ?? context, + }), + }), getRepositoryCloneUrls: Effect.fnUntraced(function* (input) { return yield* provider.getRepositoryCloneUrls({ ...input, diff --git a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx index a797a7984cbce..250240d2849fa 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx @@ -1,12 +1,39 @@ import { useGT } from "gt-react"; -import { ArrowLeftIcon, FileDiffIcon } from "lucide-react"; +import { ArrowLeftIcon, FileDiffIcon, LockIcon } from "lucide-react"; import { useEffect, useRef, type ComponentProps, type ReactNode } from "react"; import { cn } from "~/lib/utils"; +import { Badge } from "../ui/badge"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PullRequestMetaLine } from "./pullRequestPresentation"; +export function PullRequestPrivateMark({ className }: { className?: string }) { + const gt = useGT(); + const label = gt("Private"); + return ( + + } + /> + {label} + + ); +} + +export function PullRequestPrivateBadge() { + const gt = useGT(); + return ( + + + + {gt("Private")} + + + ); +} + export function PullRequestDetailHeaderBody({ title, author, diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index cbf9de56dbbb2..1e14ab19d9012 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -90,6 +90,7 @@ import { MiddleTruncate } from "../ui/middle-truncate"; import { PullRequestChecksStatusLine, PullRequestDetailHeaderBody, + PullRequestPrivateBadge, PullRequestDetailTabBar, } from "./PullRequestDetailLayout"; import { PullRequestDetailGhost, PullRequestTimelineGhost } from "./PullRequestGhosts"; @@ -1578,6 +1579,7 @@ export function PullRequestDetailPanel({
    {detail ? ( + {detail.visibility === "private" ? : null} {context === "page" ? ( + {entry.visibility === "private" ? ( + + ) : null} {entry.checksState === undefined ? null : ( ; readonly reviewDecision?: PullRequestReviewDecision | null | undefined; readonly checksState?: PullRequestChecksState | null | undefined; + /** Absent where the host has no private change requests or names no visibility. */ + readonly visibility?: PullRequestVisibility; } export interface ProviderChangeRequestSummary { diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts index 4a6e93ab74f45..ccf23f59b2258 100644 --- a/packages/source-control-core/src/server/SourceControlProvider.ts +++ b/packages/source-control-core/src/server/SourceControlProvider.ts @@ -173,6 +173,18 @@ export class SourceControlProvider extends Context.Service< }) => Effect.Effect; /** True when `createChangeRequest` opens the change request as a draft when asked. */ readonly createsDraftChangeRequests?: boolean; + /** + * The private companion of the checkout's repository, made when it has none. The branch of + * a private change request is pushed to `url` and never to the repository itself, which + * everyone can read. Absent on a host without private change requests. + */ + readonly privateChangeRequestRemote?: (input: { + readonly cwd: string; + readonly context?: SourceControlProviderContext; + }) => Effect.Effect< + { readonly url: string; readonly repository: string }, + SourceControlProviderError + >; readonly listChangeRequests: (input: { readonly cwd: string; readonly context?: SourceControlProviderContext; @@ -202,6 +214,8 @@ export class SourceControlProvider extends Context.Service< readonly bodyFile: string; /** Honored only by a provider with `createsDraftChangeRequests`. */ readonly draft?: boolean; + /** Asked only of a provider with `privateChangeRequestRemote`, which holds the head. */ + readonly private?: boolean; }) => Effect.Effect; readonly getRepositoryCloneUrls: (input: { readonly cwd: string; diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts new file mode 100644 index 0000000000000..838309b037617 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts @@ -0,0 +1,138 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; + +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as Credentials from "./TanStackSourceCredentials.ts"; +import * as TanStackSourcePullRequestProvider from "./TanStackSourcePullRequestProvider.ts"; + +const HOST = "source.tanstack.com"; + +/** + * Shaped like `GET /pulls/{n}` of a private pull request: its head is `owner:branch` in the + * companion repository, and Source has stored no file or line counts for it. + */ +const PRIVATE_PULL = { + number: 42, + title: "Fix the thing", + state: "open", + visibility: "private", + draft: false, + author: "bob", + head: "acme:fix/thing", + createdAt: 1_000, + body: null, + base: "main", + headRepo: "acme/web.private", + headSha: "c".repeat(40), + baseSha: "b".repeat(40), + mergeCommitSha: null, + mergedAt: null, + mergedBy: null, + mergeable: null, + changedFiles: null, + changedLines: null, +}; + +const FILES = { + baseSha: "b".repeat(40), + headSha: "c".repeat(40), + mergeBaseSha: "b".repeat(40), + available: true, + truncated: false, + files: [ + { path: "a.ts", status: "modified", additions: 3, deletions: 1 }, + { path: "b.ts", status: "added", additions: 4, deletions: 0 }, + ], +}; + +const RESPONSES: Record = { + "/repos/acme/web/pulls/42": PRIVATE_PULL, + "/repos/acme/web/pulls/42/files": FILES, + "/repos/acme/web/pulls/42/checks": { checks: [], upToDate: null, mayMerge: true }, + "/repos/acme/web/pulls/42/stack": { members: [] }, + [`/repos/acme/web/check-runs?sha=${"c".repeat(40)}`]: [], + "/repos/acme/web/ci/runs?pull=42&limit=30": { items: [], next: null }, + "/repos/acme/web/issues/42": { + timeline: [ + { id: 1, comment: "Looks good", author: "alice", at: 2_000 }, + { event: "head_updated", actor: "bob", at: 3_000 }, + ], + next: null, + }, + "/repos/acme/web/pulls/42/comments": [], + "/repos/acme/web/pulls/42/commits": { + baseSha: null, + headSha: null, + mergeBaseSha: null, + available: true, + commits: [], + }, + "/user": { username: "alice" }, +}; + +const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => + input.path in RESPONSES + ? Effect.succeed(JSON.stringify(RESPONSES[input.path])) + : Effect.die(`unexpected ${input.path}`), + response: () => Effect.die("unexpected response read"), +}); + +const provider = TanStackSourcePullRequestProvider.make.pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provideService( + Credentials.TanStackSourceCredentials, + Credentials.TanStackSourceCredentials.of({ + get: () => Effect.die("unexpected credential read"), + invalidate: () => Effect.void, + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected http request")), + ), +); + +describe("TanStackSourcePullRequestProvider.getChangeRequest", () => { + // A client without this host's definition percent-encodes the owner's `@`; stored links + // keep the web's own spelling. + it.effect.each(["acme/web", "@acme/web", "%40acme/web"])( + "reads a private pull request of %s", + (repository) => + Effect.gen(function* () { + const detail = yield* (yield* provider).getChangeRequest({ + host: HOST, + repository, + number: 42, + cwd: "/repo", + }); + assert.strictEqual(detail.url, `https://${HOST}/@acme/web/pull/42`); + assert.strictEqual(detail.visibility, "private"); + assert.strictEqual(detail.headBranch, "fix/thing"); + assert.strictEqual(detail.headRepositoryNameWithOwner, "acme/web.private"); + // Source stores no counts for it, so they come from its files. + assert.deepStrictEqual( + [detail.changedFiles, detail.additions, detail.deletions], + [2, 7, 1], + ); + }), + ); +}); + +describe("TanStackSourcePullRequestProvider.getChangeRequestActivity", () => { + it.effect("reads the comments of a timeline that also holds events", () => + Effect.gen(function* () { + const activity = yield* (yield* provider).getChangeRequestActivity({ + host: HOST, + repository: "acme/web", + number: 42, + cwd: "/repo", + }); + assert.deepStrictEqual( + activity.comments.map((comment) => comment.body), + ["Looks good"], + ); + }), + ); +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts index 509e03e1f41f4..0529ce6df17c7 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts @@ -35,6 +35,8 @@ const PULL = { function checkout(options: { readonly recordedOwner: string | null; readonly isAncestor: boolean; + readonly pull?: Partial; + readonly force?: boolean; }) { const git: Array = []; const config = new Map( @@ -43,14 +45,28 @@ function checkout(options: { const api = TanStackSourceApi.TanStackSourceApi.of({ request: (input) => input.path === "/repos/acme/web/pulls/42" - ? Effect.succeed(JSON.stringify(PULL)) + ? Effect.succeed(JSON.stringify({ ...PULL, ...options.pull })) : Effect.die(`unexpected ${input.path}`), response: () => Effect.die("unexpected response read"), }); const host = TestSourceControlHost.layer({ git: { resolvePrimaryRemoteName: () => Effect.succeed("origin"), - ensureRemote: () => Effect.succeed("origin"), + ensureRemote: (input) => + Effect.sync(() => { + git.push(`remote ${input.preferredName} ${input.url}`); + return input.url === REMOTE ? "origin" : input.preferredName; + }), + fetchRemoteBranch: (input) => + Effect.sync( + () => + void git.push(`fetch ${input.remoteName} ${input.remoteBranch}:${input.localBranch}`), + ), + fetchRemoteTrackingBranch: () => Effect.void, + setBranchUpstream: (input) => + Effect.sync( + () => void git.push(`upstream ${input.branch} ${input.remoteName}/${input.remoteBranch}`), + ), readConfigValue: (_cwd, key) => Effect.succeed(key === "remote.origin.url" ? REMOTE : (config.get(key) ?? null)), writeConfigValue: (input) => Effect.sync(() => void config.set(input.key, input.value)), @@ -86,7 +102,13 @@ function checkout(options: { }, }); const run = TanStackSourceSourceControlProvider.make.pipe( - Effect.flatMap((provider) => provider.checkoutChangeRequest({ cwd: "/repo", reference: "42" })), + Effect.flatMap((provider) => + provider.checkoutChangeRequest({ + cwd: "/repo", + reference: "42", + ...(options.force === undefined ? {} : { force: options.force }), + }), + ), Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), Effect.provide(Layer.merge(host, FileSystem.layerNoop({}))), ); @@ -129,4 +151,83 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { assert.isFalse(git.some((command) => command.startsWith("checkout"))); }); }); + + // Source publishes no `refs/pull//head` for a private pull request, on either repository. + it.effect("takes a private pull request's branch from the companion repository", () => { + const pull = { head: "acme:fix-thing", headRepo: "acme/web.private" }; + const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true, pull }); + const forced = checkout({ recordedOwner: null, isAncestor: true, pull, force: true }); + return Effect.gen(function* () { + yield* forced.run; + assert.include(forced.git, "checkout --no-track -B fix-thing refs/remotes/acme/fix-thing --"); + yield* run; + assert.strictEqual(config.get("branch.fix-thing.pushRemote"), "acme"); + assert.deepStrictEqual(git, [ + `remote source ${REMOTE}`, + "remote acme https://source.tanstack.com/@acme/web.private.git", + "fetch acme fix-thing:fix-thing", + "upstream fix-thing acme/fix-thing", + "switch fix-thing", + ]); + }); + }); +}); + +describe("TanStackSourceSourceControlProvider private pull requests", () => { + it.effect("asks Source for the companion and opens the pull request as private", () => { + const requests: Array<{ method: string; path: string; body: unknown }> = []; + const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => { + requests.push({ method: input.method ?? "GET", path: input.path, body: input.body }); + return Effect.succeed( + JSON.stringify({ + owner: "acme", + name: "web.private", + defaultBranch: null, + cloneUrl: "https://source.tanstack.com/@acme/web.private.git", + }), + ); + }, + response: () => Effect.die("unexpected response read"), + }); + const files = FileSystem.layerNoop({ readFileString: () => Effect.succeed("Body") }); + return Effect.gen(function* () { + const provider = yield* TanStackSourceSourceControlProvider.make; + const companion = provider.privateChangeRequestRemote; + assert.isDefined(companion); + assert.deepStrictEqual(yield* companion({ cwd: "/repo" }), { + url: "https://source.tanstack.com/@acme/web.private.git", + repository: "acme/web.private", + }); + yield* provider.createChangeRequest({ + cwd: "/repo", + baseRefName: "main", + headSelector: "sec/fix", + title: "Fix", + bodyFile: "/tmp/body.md", + private: true, + }); + assert.deepStrictEqual(requests, [ + { method: "POST", path: "/repos/acme/web/private-remote", body: undefined }, + { + method: "POST", + path: "/repos/acme/web/pulls", + body: { title: "Fix", head: "sec/fix", base: "main", body: "Body", private: true }, + }, + ]); + }).pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provide( + Layer.merge( + TestSourceControlHost.layer({ + git: { + resolvePrimaryRemoteName: () => Effect.succeed("origin"), + readConfigValue: () => Effect.succeed(REMOTE), + }, + }), + files, + ), + ), + ); + }); }); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts index a1abb376b472d..f194848611361 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts @@ -395,6 +395,18 @@ export const make = Effect.gen(function* () { }, ), createsDraftChangeRequests: true, + privateChangeRequestRemote: Effect.fn( + "TanStackSourceSourceControlProvider.privateChangeRequestRemote", + )(function* (input) { + const target = yield* resolveTarget("privateChangeRequestRemote", input); + const companion = yield* read( + "privateChangeRequestRemote", + input.cwd, + { host: target.host, method: "POST", path: `/repos/${target.repository}/private-remote` }, + Repository, + ); + return { url: companion.cloneUrl, repository: `${companion.owner}/${companion.name}` }; + }), createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")( function* (input) { const target = yield* resolveTarget("createChangeRequest", { @@ -437,6 +449,7 @@ export const make = Effect.gen(function* () { base: input.target?.refName ?? input.baseRefName, ...(body.trim().length === 0 ? {} : { body }), ...(input.draft === true ? { draft: true } : {}), + ...(input.private === true ? { private: true } : {}), }, }) .pipe( @@ -494,7 +507,8 @@ export const make = Effect.gen(function* () { return repository.defaultBranch; }, ), - // Every pull request's head is published as `refs/pull//head`, forks and GitHub sync too. + // A pull request's head is published as `refs/pull//head`, forks and GitHub sync too. A + // private one has no such ref: its branch is read from the companion repository. checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")( function* (input) { const pull = yield* getPull(input); @@ -519,9 +533,26 @@ export const make = Effect.gen(function* () { }); const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest"; const branches = yield* git.listLocalBranchNames(input.cwd); - if (!pull.isCrossRepository) { + const companion = + pullRepository !== null && + pull.headRepositoryNameWithOwner?.toLowerCase() === + `${pullRepository}.private`.toLowerCase() + ? pull.headRepositoryNameWithOwner + : null; + if (!pull.isCrossRepository || companion !== null) { const localBranch = pull.headRefName; - const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: localBranch }; + const remoteBranch = { + cwd: input.cwd, + remoteName: + companion === null + ? remoteName + : yield* git.ensureRemote({ + cwd: input.cwd, + preferredName: companion.split("/")[0] ?? "private", + url: `${Hosts.webRepositoryUrl(HOST, companion)}.git`, + }), + remoteBranch: localBranch, + }; if (input.force !== true && !branches.includes(localBranch)) yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch }); else yield* git.fetchRemoteTrackingBranch(remoteBranch); @@ -535,11 +566,18 @@ export const make = Effect.gen(function* () { "--no-track", "-B", localBranch, - `refs/remotes/${remoteName}/${localBranch}`, + `refs/remotes/${remoteBranch.remoteName}/${localBranch}`, "--", ], }); yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch }); + // Whatever push defaults say, this branch must not be published to the public remote. + if (companion !== null) + yield* git.writeConfigValue({ + cwd: input.cwd, + key: `branch.${localBranch}.pushRemote`, + value: remoteBranch.remoteName, + }); yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch })); return; } diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts new file mode 100644 index 0000000000000..ac43a46ccdcad --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { tanStackSourceRepositoryPath } from "./tanStackSourceHosts.ts"; + +describe("tanStackSourceRepositoryPath", () => { + it.each([ + ["acme/web", "acme/web"], + ["@acme/web", "acme/web"], + // Clients without this host's definition percent-encode the owner's `@`. + ["%40acme/web", "acme/web"], + ["/@acme/web.git/", "acme/web"], + ["acme/web.private", "acme/web.private"], + ["acme", null], + ["acme/web/extra", null], + ["acme/..", null], + ])("reads %s as %s", (path, repository) => { + expect(tanStackSourceRepositoryPath(path)).toBe(repository); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts index 22923264629bf..dfa6d4e9031a0 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts @@ -1,4 +1,4 @@ -import { TANSTACK_SOURCE_HOST } from "../shared/definition.ts"; +import { TANSTACK_SOURCE_HOST, withoutOwnerMark } from "../shared/definition.ts"; export const TANSTACK_SOURCE_HOSTS = [TANSTACK_SOURCE_HOST] as const; export type TanStackSourceHost = (typeof TANSTACK_SOURCE_HOSTS)[number]; @@ -10,14 +10,14 @@ export function tanStackSourceHost(host: string): TanStackSourceHost | null { const SEGMENT = /^[A-Za-z0-9_.-]+$/u; -/** `owner/name` from the API spelling or the web spelling `@owner/name`, `.git` dropped. */ +/** `owner/name` from the API spelling or either web spelling of the owner, `.git` dropped. */ export function tanStackSourceRepositoryPath(path: string): string | null { - const [owner, name, ...rest] = path - .trim() - .replace(/^\/+|\/+$/gu, "") - .replace(/\.git$/u, "") - .replace(/^@/u, "") - .split("/"); + const [owner, name, ...rest] = withoutOwnerMark( + path + .trim() + .replace(/^\/+|\/+$/gu, "") + .replace(/\.git$/u, ""), + ).split("/"); return rest.length === 0 && owner !== undefined && name !== undefined && diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts index 4d698fb881dfb..24c93e6aac83d 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts @@ -146,6 +146,7 @@ describe("toActivity", () => { ["4", "review-comment", null], ]); expect(activity.comments[0]?.url).toBe(`https://${HOST}/@TanStack/ai/pull/9#comment-1`); + expect(Json.pullUrl(HOST, "%40TanStack/ai", 9)).toBe(`https://${HOST}/@TanStack/ai/pull/9`); expect(activity.reviewThreads).toMatchObject([ { id: "4", path: "a.ts", line: 2, side: "left", isResolved: true }, ]); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts index acf3c4158f95c..51537627ca3e7 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts @@ -16,6 +16,8 @@ import type { import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; +import { withoutOwnerMark } from "../shared/definition.ts"; + /** Source sends times as epoch milliseconds. */ const EpochMillis = Schema.Finite; const Login = Schema.String; @@ -29,6 +31,7 @@ export const SourcePull = Schema.Struct({ labels: Schema.optional(Schema.Array(Schema.String)), head: Schema.String, createdAt: EpochMillis, + visibility: Schema.optional(Schema.String), }); export type SourcePull = typeof SourcePull.Type; @@ -135,7 +138,8 @@ const TimelineEntry = Schema.Struct({ type TimelineEntry = typeof TimelineEntry.Type; export const SourceTimeline = Schema.Struct({ - timeline: Schema.Array(TimelineEntry), + // Events such as `head_updated` sit between the comments and carry no id. + timeline: Schema.Array(Schema.Union([TimelineEntry, Schema.Struct({ event: Schema.String })])), next: Schema.NullOr(Schema.String), }); @@ -239,10 +243,20 @@ export const SourceUser = Schema.Struct({ username: Schema.String }); export const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis)); export const pullUrl = (host: string, repository: string, number: number) => - `https://${host}/@${repository}/pull/${number}`; + `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`; -/** A GitHub-synced pull request from a fork names its head only by its pull ref. */ -export const headBranchName = (head: string) => head.replace(/^refs\/heads\//u, ""); +/** + * A GitHub-synced pull request from a fork names its head only by its pull ref, and a private + * one as `owner:branch`. A branch name holds no colon, so the owner is all that one can precede. + */ +export const headBranchName = (head: string) => + head.replace(/^refs\/heads\//u, "").replace(/^[^/:]+:/u, ""); + +/** Absent when Source names no visibility, so a reader tells unknown from public. */ +const visibilityOf = (pull: Pick) => + pull.visibility === "private" || pull.visibility === "public" + ? { visibility: pull.visibility } + : {}; export function toActor(login: string | null, host: string): PullRequestActor | null { if (login === null || login.trim() === "") return null; @@ -280,6 +294,7 @@ export function toChangeRequest( baseBranch: pull.base ?? "", state: pull.state, isDraft: pull.draft, + ...visibilityOf(pull), mergeability: "unknown", additions: 0, deletions: 0, @@ -380,7 +395,9 @@ export function toActivity(input: { }): ProviderChangeRequestActivity { const { host } = input; const page = pullUrl(host, input.repository, input.number); - const entries = input.timeline.timeline.filter(visible); + const entries = input.timeline.timeline.filter( + (entry): entry is TimelineEntry => "id" in entry && visible(entry), + ); const comments: Array = entries.map((entry: TimelineEntry) => ({ id: String(entry.id), kind: diff --git a/packages/source-control-tanstack-source/src/shared/definition.test.ts b/packages/source-control-tanstack-source/src/shared/definition.test.ts index e3ce5c867fa5c..6e09a89fa2cda 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.test.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.test.ts @@ -31,7 +31,23 @@ describe("TanStack Source definition", () => { number: 7, }), ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); + // A stored link or an older client may name the repository as the web spells it. + for (const repository of ["@TanStack/router", "%40TanStack/router"]) + expect( + definition.changeRequestUrl({ host: "source.tanstack.com", repository, number: 7 }), + repository, + ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); expect(definition.checkoutCommandArgument("src pr checkout 7")).toBe("7"); expect(definition.checkoutCommandArgument("gh pr checkout 7")).toBeNull(); }); + + it.each(["tanstack/router", "@tanstack/router", "%40tanstack/router"])( + "keys %s as the API's owner/name", + (repository) => { + expect(definition.canonicalRepositoryKey?.(`source.tanstack.com/${repository}`)).toBe( + "source.tanstack.com/tanstack/router", + ); + expect(definition.canonicalRepositoryKey?.(`github.com/${repository}`)).toBeNull(); + }, + ); }); diff --git a/packages/source-control-tanstack-source/src/shared/definition.ts b/packages/source-control-tanstack-source/src/shared/definition.ts index 1aee00c968dc6..032adc5a45cdd 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.ts @@ -37,6 +37,20 @@ function parseChangeRequestUrl(url: URL) { : { ...link, repositoryUrl: `${url.origin}/@${CHANGE_REQUEST_PATH.exec(url.pathname)![1]}` }; } +/** + * `owner/name` as the API names it. The web spells it `@owner/name`, and a client without this + * definition percent-encodes that as `%40owner/name`. + */ +export const withoutOwnerMark = (repository: string) => repository.replace(/^(?:@|%40)/iu, ""); + +/** Links stored with the web's spelling compare equal to the project's own key. */ +function canonicalRepositoryKey(key: string): string | null { + const slash = key.indexOf("/"); + return slash > 0 && isTanStackSourceHost(key.slice(0, slash)) + ? `${TANSTACK_SOURCE_HOST}/${withoutOwnerMark(key.slice(slash + 1))}` + : null; +} + /** Keys drop the owner's `@`, so a project's repository is `owner/name` as the API names it. */ function repositoryKeyFromRemote(key: string): string | null { // Remote parsing spells the `@` percent-encoded. @@ -80,13 +94,13 @@ export const definition = defineSourceControl({ ? null : webUrl ? changeRequestUrlBelow(webUrl, `pull/${number}`) - : `https://${host}/@${repository.replace(/^@/u, "")}/pull/${number}`, + : `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`, parseChangeRequestUrl, commitUrl: (input) => buildCommitUrl( input.webUrl ? input - : { ...input, webUrl: `https://${input.host}/@${input.repository.replace(/^@/u, "")}` }, + : { ...input, webUrl: `https://${input.host}/@${withoutOwnerMark(input.repository)}` }, "commit", ), parseIssueUrl: (url) => @@ -122,6 +136,7 @@ export const definition = defineSourceControl({ checkoutChangeRequestHost: () => null, changeRequestHeadRef: (number) => `refs/pull/${number}/head`, repositoryKeyFromRemote, + canonicalRepositoryKey, recognizeRemote: ({ hostname }) => isTanStackSourceHost(hostname) ? { kind: KIND, name: "TanStack Source", baseUrl: `https://${TANSTACK_SOURCE_HOST}` } From 976aca331aa15d41f4383def7afeafcfcab5575e Mon Sep 17 00:00:00 2001 From: Wu Shuwen Date: Sun, 22 Nov 2026 17:08:53 +0800 Subject: [PATCH 023/162] fix: include delegated threads in CLI listing (#40738) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 97 ++++++++++++++++++++++++++++++ apps/server/src/cli/thread.ts | 6 +- 2 files changed, 101 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 7231ea7f2b3e0..49887ee0bb7cc 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -53,6 +53,103 @@ vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => { const threadId = ThreadId.make("thread-1"); const runId = RunId.make("run-1"); +it.effect("list includes delegated threads across pages and still leaves out subagents", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-list-" }); + yield* persistServerRuntimeState({ + path: path.join(baseDir, "userdata", "server-runtime.json"), + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3_773, + }), + }); + const projectId = ProjectId.make("project-1"); + const item = (id: string) => ({ + threadId: id, + projectId, + title: id, + createdBy: "user", + creationSource: "web", + status: "idle", + latestRunId: null, + providerInstanceId: "codex", + model: "test", + runtimeMode: "full-access", + interactionMode: "default", + linkedPullRequest: null, + settled: false, + settledAt: null, + snoozed: false, + snoozedUntil: null, + parentThreadId: null, + relationshipToParent: null, + itemCount: 0, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + const root = item("root"); + const delegated = { + ...item("delegated"), + delegatedFrom: { environmentId: "env-1", threadId: "remote", title: "Remote" }, + }; + const subagent = { ...item("child"), parentThreadId: "root", relationshipToParent: "subagent" }; + using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue( + Effect.succeed({ + call: (tool, args) => { + if (tool === "t3_project_list") + return Effect.succeed({ + structuredContent: { + projects: [{ id: projectId, title: "Project", workspaceRoot: baseDir }], + nextCursor: null, + }, + }); + if (tool === "t3_thread_list") { + const all = args.includeSubagents ? [root, subagent, delegated] : [root]; + const cursor = Number(args.cursor); + return Effect.succeed({ + structuredContent: { + projectId, + currentThreadId: null, + threads: all.slice(cursor, cursor + 2), + nextCursor: cursor + 2 < all.length ? cursor + 2 : null, + total: all.length, + }, + }); + } + return Effect.die(`unexpected ${tool} call`); + }, + }), + ); + yield* Command.runWith(threadCommand, { version: "0.0.0" })([ + "list", + "--project", + projectId, + "--json", + "--base-dir", + baseDir, + ]); + const listed = JSON.parse(String((yield* TestConsole.logLines).at(-1))) as Array<{ + threadId: string; + }>; + assert.deepStrictEqual( + listed.map((entry) => entry.threadId), + ["root", "delegated"], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + NetService.layer, + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })), + ), + ), + ), +); + it.effect( "start resolves home-relative project paths while preserving ids and relative paths", () => diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 8849f10c6a5ec..e63e762237e85 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -850,10 +850,12 @@ const threadListCommand = Command.make("list", { while (cursor !== null) { const page: OrchestratorMcpThreadListResult = yield* tools.call( "t3_thread_list", - { projectId: project.id, includeSubagents: false, limit: 100, cursor }, + { projectId: project.id, includeSubagents: true, limit: 100, cursor }, OrchestratorMcpThreadListResult, ); - threads.push(...page.threads); + threads.push( + ...page.threads.filter((thread) => thread.relationshipToParent !== "subagent"), + ); cursor = page.nextCursor; } if (flags.json) { From bcace0787ee37f4e4dd9a1f68b7be8f871934926 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:23:15 -0800 Subject: [PATCH 024/162] fix(pi): turn token usage counts cached tokens as input and stays per turn (#40758) --- .../testkit/fixtures/simple/pi_output.ts | 55 +++++++++------ .../provider-pi/src/server/adapter.test.ts | 56 ++++++++++++++++ packages/provider-pi/src/server/adapter.ts | 67 ++++++++++++------- 3 files changed, 133 insertions(+), 45 deletions(-) diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts index c7579914964ee..bed80f2be65ef 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/pi_output.ts @@ -24,32 +24,45 @@ function lastPiResponseData(transcript: ProviderReplayTranscript, command: strin return field(frame, "data"); } -/** Settled Pi usage uses each recorded get_session_stats response in order, not the last streaming total. */ +/** + * Settled Pi usage takes the context size from each turn's get_session_stats response and the + * input breakdown from the turn's last streamed message usage, since stats tokens are session totals. + */ export function assertPiSettledTokenUsage( result: OrchestratorV2ScenarioResult, transcript: ProviderReplayTranscript, ) { - const stats = transcript.entries.flatMap((entry) => - entry.type === "emit_inbound" && - field(entry.frame, "type") === "response" && - field(entry.frame, "command") === "get_session_stats" - ? [field(entry.frame, "data")] - : [], - ); - const turns = projectionFor(result, transcript.scenario).providerTurns; - assert.lengthOf(turns, stats.length); - for (const [index, turn] of turns.entries()) { - const contextUsage = field(stats[index], "contextUsage"); - const tokens = field(stats[index], "tokens"); - const { updatedAt: _updatedAt, ...tokenUsage } = turn.tokenUsage ?? { updatedAt: "" }; - assert.deepEqual(tokenUsage, { - usedTokens: field(contextUsage, "tokens"), - maxTokens: field(contextUsage, "contextWindow"), - inputTokens: field(tokens, "input"), - cachedInputTokens: field(tokens, "cacheRead"), - outputTokens: field(tokens, "output"), - }); + const expected: Array> = []; + let messageUsage: unknown; + for (const entry of transcript.entries) { + if (entry.type !== "emit_inbound") continue; + const usage = field(entry.frame, "usage"); + if (field(entry.frame, "type") === "message_update" && field(usage, "totalTokens") !== 0) { + messageUsage = usage; + } + if ( + field(entry.frame, "type") === "response" && + field(entry.frame, "command") === "get_session_stats" + ) { + const contextUsage = field(field(entry.frame, "data"), "contextUsage"); + const count = (key: string) => Number(field(messageUsage, key)); + expected.push({ + usedTokens: field(contextUsage, "tokens"), + maxTokens: field(contextUsage, "contextWindow"), + inputTokens: count("input") + count("cacheRead") + count("cacheWrite"), + cachedInputTokens: count("cacheRead"), + outputTokens: count("output"), + }); + } } + const turns = projectionFor(result, transcript.scenario).providerTurns; + assert.deepEqual( + turns.map((turn) => { + const { updatedAt: _updatedAt, ...tokenUsage } = turn.tokenUsage ?? { updatedAt: "" }; + return tokenUsage; + }), + expected, + ); } export function assertPiSimpleOutput( diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 019af2a98783f..b3e54117f02ee 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4159,6 +4159,62 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("reports cached input as a share of input in live and completed token usage", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + fake.queueState({ + sessionFile: FAKE_SESSION_FILE, + model: { provider: "anthropic", id: "large", contextWindow: 1_000_000 }, + }); + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + // Pi's message usage counts uncached input, cache reads and cache writes separately. + const usage = { input: 6, cacheRead: 40_101, cacheWrite: 10_561, output: 123 }; + // Session stats total every message in the session, not this turn. + fake.queueStats({ + tokens: { + input: 1_206, + cacheRead: 90_202, + cacheWrite: 60_622, + output: 250, + total: 152_280, + }, + contextUsage: { tokens: 50_791, contextWindow: 1_000_000 }, + }); + yield* fake.emit({ type: "response", command: "prompt", success: true }); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "message_start", message: { role: "assistant" } }); + yield* fake.emit({ + type: "message_update", + usage: { ...usage, totalTokens: 50_791 }, + assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "ok" }, + }); + const live = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined, + ); + assert.deepInclude( + live.type === "provider_turn.updated" ? live.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + yield* fake.emit({ type: "agent_settled" }); + const completed = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.deepInclude( + completed.type === "provider_turn.updated" ? completed.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect.each(["turn window", "full tree"] as const)( "finishes a turn whose %s has a parentId cycle", (cycleIn) => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index eae7f3eb6c2fa..e7803bbe9c5ee 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -359,6 +359,11 @@ function compactionTitle(status: PiCompactionStatus): string { } } +type PiMessageTokenUsage = Pick< + OrchestrationV2ProviderTurnTokenUsage, + "inputTokens" | "cachedInputTokens" | "outputTokens" +>; + interface ActivePiTurn { readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput; readonly providerTurn: OrchestrationV2ProviderTurn; @@ -377,6 +382,7 @@ interface ActivePiTurn { promptMayBeCommandOnly: boolean; latestCompactionAfterTokens: number | null; lastLiveUsedTokens: number | null; + lastMessageUsage: PiMessageTokenUsage | undefined; settleProbeGeneration: number; /** An extension may start compaction immediately after Pi emits agent_settled. */ settleWhenIdle: boolean; @@ -904,6 +910,25 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return value === undefined ? undefined : Math.max(0, Math.trunc(value)); }; + // Pi counts uncached input, cache reads and cache writes separately; input includes all three. + const piMessageTokenUsage = (usage: unknown): PiMessageTokenUsage => { + const uncachedInputTokens = nonNegativeInteger(usage, "input"); + const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); + const outputTokens = nonNegativeInteger(usage, "output"); + return { + ...(uncachedInputTokens === undefined + ? {} + : { + inputTokens: + uncachedInputTokens + + (cachedInputTokens ?? 0) + + (nonNegativeInteger(usage, "cacheWrite") ?? 0), + }), + ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), + ...(outputTokens === undefined ? {} : { outputTokens }), + }; + }; + const rememberModelContextWindow = (model: unknown): number | null => { const provider = recordString(model, "provider"); const id = recordString(model, "id"); @@ -994,6 +1019,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const tokenUsageFromStats = ( stats: unknown, fallbackUsedTokens: number | null, + messageUsage: PiMessageTokenUsage | undefined, updatedAt: DateTime.Utc, ): OrchestrationV2ProviderTurnTokenUsage | undefined => { const contextUsage = recordField(stats, "contextUsage"); @@ -1002,24 +1028,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nonNegativeInteger(contextUsage, "tokens") ?? fallbackUsedTokens ?? undefined; if (usedTokens === undefined || maxTokens === undefined || maxTokens === 0) return undefined; - - const totals = recordField(stats, "tokens"); - const inputTokens = nonNegativeInteger(totals, "input"); - const cachedInputTokens = nonNegativeInteger(totals, "cacheRead"); - const outputTokens = nonNegativeInteger(totals, "output"); - return { - usedTokens, - maxTokens, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), - updatedAt: DateTime.formatIso(updatedAt), - }; + // Stats `tokens` are whole-session totals; the breakdown comes from the turn's last message. + return { usedTokens, maxTokens, ...messageUsage, updatedAt: DateTime.formatIso(updatedAt) }; }; - const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) => + const readTokenUsage = (turn: ActivePiTurn, updatedAt: DateTime.Utc) => request({ type: "get_session_stats" }, 2_000).pipe( - Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)), + Effect.map((stats) => + tokenUsageFromStats( + stats, + turn.latestCompactionAfterTokens, + turn.lastMessageUsage, + updatedAt, + ), + ), Effect.orElseSucceed(() => undefined), ); @@ -1030,6 +1052,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) { const usedTokens = nonNegativeInteger(usage, "totalTokens"); + if (usedTokens !== undefined && usedTokens > 0) { + turn.lastMessageUsage = piMessageTokenUsage(usage); + } if ( usedTokens === undefined || usedTokens === 0 || @@ -1040,9 +1065,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return; } turn.lastLiveUsedTokens = usedTokens; - const inputTokens = nonNegativeInteger(usage, "input"); - const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); - const outputTokens = nonNegativeInteger(usage, "output"); const updatedAt = yield* DateTime.now; yield* emit({ type: "provider_turn.updated", @@ -1053,9 +1075,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( tokenUsage: { usedTokens, maxTokens: contextWindow, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), + ...turn.lastMessageUsage, updatedAt: DateTime.formatIso(updatedAt), }, }, @@ -2075,9 +2095,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } const treeRefs = turn.stopTreeRefs !== undefined ? turn.stopTreeRefs : yield* captureTurnTreeRefs(); - const tokenUsage = readUsage - ? yield* readTokenUsage(turn.latestCompactionAfterTokens, completedAt) - : undefined; + const tokenUsage = readUsage ? yield* readTokenUsage(turn, completedAt) : undefined; const failure = interrupted ? null : (turn.rejectedPromptFailure ?? turn.failure); yield* emit({ type: "provider_turn.updated", @@ -3474,6 +3492,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( compactCommand !== null || (payload?.message.trimStart().startsWith("/") ?? false), latestCompactionAfterTokens: null, lastLiveUsedTokens: null, + lastMessageUsage: undefined, settleProbeGeneration: 0, settleWhenIdle: false, compactionCancelled: false, From 4c3d83ff24c7437582cfd37ebe4565314250630b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:25:30 -0800 Subject: [PATCH 025/162] fix(mobile): usage account detail keeps even pace current while open (#40759) --- apps/mobile/src/features/usage/UsageLimitsPooled.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 96d8f922340f7..4c290d68ac338 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -20,6 +20,7 @@ import { import { msg, T, useGT, useMessages, Var } from "gt-react-native"; import { Fragment, type ReactNode, useId, useState } from "react"; import { Pressable, View } from "react-native"; +import { useNowMinuteMs } from "../../lib/clock"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; import { Defs, Path, Pattern, Rect, Svg } from "react-native-svg"; @@ -201,7 +202,6 @@ function PoolWindowCard({ windowId: pool.id, windowKind: pool.kind, environmentIds, - now, }); const summary = ( <> @@ -590,13 +590,13 @@ type AccountScreenProps = StaticScreenProps<{ windowId: string; windowKind: LimitPoolWindow["kind"]; environmentIds: readonly string[] | null; - now: number; }>; export function UsageLimitAccountScreen({ route }: AccountScreenProps) { const insets = useSafeAreaInsets(); const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); - const { accountKey, windowId, windowKind, environmentIds, now } = route.params; + const { accountKey, windowId, windowKind, environmentIds } = route.params; + const now = useNowMinuteMs(); const selectedIds = environmentIds === null ? null : new Set(environmentIds.map((id) => EnvironmentId.make(id))); const selected = From 7f125d83d18b2b4e9e65debf8e4d1ae71c45af94 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 01:27:45 -0800 Subject: [PATCH 026/162] fix(server): Resume sends pending context to providers without native resume (#40764) --- .../ProviderTurnStartService.test.ts | 21 +++++++ .../ProviderTurnStartService.ts | 61 +++++++++++++------ 2 files changed, 63 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 4bf6e71397fe5..89e5a6930bafc 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2289,6 +2289,27 @@ effectIt.effect("refuses unsupported resume instead of manufacturing a user prom }), ); +effectIt.effect.each([ + { contextRun: "current" }, + { contextRun: "failed", switchedProvider: true }, +] as const)( + "a resume that carries pending context asks a provider without native resume to continue: %j", + (sideChat) => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "", + manualContinuation: true, + nativeResumeUnsupported: true, + sideChat, + }); + yield* harness.start; + expect(harness.settledRuns).toEqual([]); + expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([ + withInlineContext("SIDE_CHAT_CONTEXT", "Continue where you left off."), + ]); + }), +); + effectIt.effect.each([ { contextRun: "current", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, { contextRun: "failed", runtimeMode: "full-access", context: "SIDE_CHAT_CONTEXT" }, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 8e35271ce5aa9..c3890cab5f71b 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -408,12 +408,22 @@ export const layer: Layer.Layer< return { ...session, startTurn: (input: Parameters[0]) => start(input), - ...(session.resumeTurn === undefined - ? {} - : { - resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => - start(ProviderAdapter.resumeTurnInput(input)), - }), + // Pending context can prompt a resume, so even a session without native resume takes one. + resumeTurn: (input: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => + session.resumeTurn === undefined && deliver === undefined + ? Effect.fail( + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: session.driver, + threadId: input.threadId, + providerThreadId: input.providerThread.id, + runId: input.runId, + cause: new ProviderAdapter.ProviderResumeUnsupportedError({ + driver: session.driver, + providerThreadId: input.providerThread.id, + }), + }), + ) + : start(ProviderAdapter.resumeTurnInput(input)), ...(session.compactThread === undefined ? {} : { @@ -1859,7 +1869,21 @@ export const layer: Layer.Layer< legacyInputRunIds, budget, } = handoffContext; - if (manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined) { + const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); + const carriesPendingContext = + effectiveHandoffs.length > 0 || + retryHandoff.handoffs.length > 0 || + retryHandoff.attachments.length > 0 || + sideChatHandoff !== undefined || + restartNote !== "" || + noteContinuation; + // Pending context turns the resume into a prompted turn, which needs no native resume. + if ( + manualResume && + unsentResumeMessage === undefined && + session.resumeTurn === undefined && + !carriesPendingContext + ) { yield* settleStartFailure({ signal: "resume-unsupported", title: "Native resume is unavailable", @@ -1870,7 +1894,6 @@ export const layer: Layer.Layer< }); return; } - const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, contextUsage: handoffUsage, @@ -2100,8 +2123,14 @@ export const layer: Layer.Layer< turnInput.resume && prompted && userText === "" ? RESUME_PROMPT : userText; const text = goalCommand ? userText : withInlineContext(context, requestText); const operation = - turnInput.resume && !prompted && session.resumeTurn !== undefined - ? session.resumeTurn({ ...resumeInput, messageId: resumeMessage.messageId }) + turnInput.resume && !prompted + ? (session.resumeTurn?.({ ...resumeInput, messageId: resumeMessage.messageId }) ?? + Effect.fail( + new ProviderAdapter.ProviderResumeUnsupportedError({ + driver: session.driver, + providerThreadId: providerThread.id, + }), + )) : start({ ...(prompted ? contextInput : startInput), message: { @@ -2176,15 +2205,9 @@ export const layer: Layer.Layer< }), ), ); - const deliverySession = - effectiveHandoffs.length === 0 && - retryHandoff.handoffs.length === 0 && - retryHandoff.attachments.length === 0 && - sideChatHandoff === undefined && - restartNote === "" && - !noteContinuation - ? session - : makeDeliverySession(session, startWithHandoffs); + const deliverySession = carriesPendingContext + ? makeDeliverySession(session, startWithHandoffs) + : session; return runExecution.startRootRun({ commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`), appThread: projection.thread, From 90a8ac086435ac3503810f64da2fc3c930ef8ce1 Mon Sep 17 00:00:00 2001 From: Aman Thanvi <22306104+amanthanvi@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:39:13 -0500 Subject: [PATCH 027/162] fix(server): a failed or cancelled clone no longer blocks re-cloning its destination (#40739) Co-authored-by: Julius Marminge --- .../src/project/ProjectCloneTracker.test.ts | 62 +++++++++++++++++++ .../server/src/project/ProjectCloneTracker.ts | 17 +++-- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/apps/server/src/project/ProjectCloneTracker.test.ts b/apps/server/src/project/ProjectCloneTracker.test.ts index bdbb47b767c03..3b2e6f1179b86 100644 --- a/apps/server/src/project/ProjectCloneTracker.test.ts +++ b/apps/server/src/project/ProjectCloneTracker.test.ts @@ -312,6 +312,68 @@ describe("ProjectCloneTracker", () => { }).pipe(Effect.provide(harness.layer)); }); + it.effect("a fresh clone into a failed clone's destination supersedes it", () => { + let attempts = 0; + const harness = makeHarness({ + clone: (input) => + Effect.suspend(() => + ++attempts === 1 + ? Effect.fail( + new SourceControlRepositoryError({ + operation: "cloneRepository", + provider: SourceControlProviderKind.make("unknown"), + detail: "fatal: repository not found", + }), + ) + : Effect.succeed({ + cwd: input.destinationPath, + remoteUrl: input.remoteUrl ?? "", + repository: null, + }), + ), + }); + // The failed clone's project still owns the destination. + const conflictingHooks: ProjectCloneTracker.ProjectCloneHooks = { + ...harness.hooks, + createProject: (input) => + Effect.fail( + new ProjectConflictError({ + projectId: input.projectId, + workspaceRoot: input.workspaceRoot, + conflictingProjectId: projectId, + }), + ), + }; + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.phase).toBe("failed"); + + const second = ProjectId.make("project-2"); + const result = yield* tracker.start({ ...startInput, projectId: second }, conflictingHooks); + expect(result.projectId).toBe(projectId); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.phase).toBe("done"); + expect(yield* tracker.get(second)).toBeNull(); + expect(harness.cloned).toEqual([projectId]); + }).pipe(Effect.provide(harness.layer)); + }); + + it.effect("refuses a second clone into a destination that is still cloning", () => { + const harness = makeHarness({ clone: () => Effect.never }); + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + const error = yield* Effect.flip( + tracker.start({ ...startInput, projectId: ProjectId.make("project-2") }, harness.hooks), + ); + expect(error.message).toContain("already in progress"); + expect((yield* tracker.get(projectId))?.phase).toBe("running"); + }).pipe(Effect.provide(harness.layer)); + }); + it.effect("does not create a project when the clone cannot be prepared", () => { const harness = makeHarness(); const layer = ProjectCloneTracker.layer.pipe( diff --git a/apps/server/src/project/ProjectCloneTracker.ts b/apps/server/src/project/ProjectCloneTracker.ts index 0a24f11ffd89d..367b839cf2a6b 100644 --- a/apps/server/src/project/ProjectCloneTracker.ts +++ b/apps/server/src/project/ProjectCloneTracker.ts @@ -297,14 +297,19 @@ export const make = Effect.gen(function* () { endedAt: null, sequence: ++sequence, }; - const claimed = yield* Ref.modify(clones, (current) => { - const conflict = Array.from(current.values()).some( + const claim = yield* Ref.modify(clones, (current) => { + const overlapping = Array.from(current.values()).filter( (tracked) => tracked.snapshot.projectId === input.projectId || tracked.input.destinationPath === prepared.destinationPath, ); - if (conflict) return [false, current] as const; + // Only a running clone owns its destination; a failed or cancelled one + // left nothing behind, so a fresh start supersedes it. + if (overlapping.some((tracked) => tracked.snapshot.phase === "running")) { + return [null, current] as const; + } const next = new Map(current); + for (const stale of overlapping) next.delete(stale.snapshot.projectId); next.set(input.projectId, { snapshot, fiber: null, @@ -316,14 +321,16 @@ export const make = Effect.gen(function* () { protocol: input.protocol ?? "auto", }, }); - return [true, next] as const; + return [overlapping.map((stale) => stale.snapshot.projectId), next] as const; }); const alreadyInProgress = new SourceControlRepositoryError({ operation: "cloneRepository", provider: input.provider ?? SourceControlProviderKind.make("unknown"), detail: "A clone into this destination is already in progress.", }); - if (!claimed) return yield* alreadyInProgress; + if (claim === null) return yield* alreadyInProgress; + // A superseded done entry's pending removal would otherwise delete the new claim. + yield* Effect.forEach(claim, clearRetention, { discard: true }); // Finish or release the claim despite disconnects; a claim without a fiber cannot be cancelled or retried. const projectId = yield* Effect.uninterruptible( Effect.gen(function* () { From 70b5e489b91842243655cbc4307c614feb314ff0 Mon Sep 17 00:00:00 2001 From: Wu Shuwen Date: Sun, 22 Nov 2026 17:43:07 +0800 Subject: [PATCH 028/162] fix: retain pull request metadata in thread show (#40744) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 34 ++++++++++++++++++++++++++++++ apps/server/src/cli/thread.ts | 3 ++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 49887ee0bb7cc..bb0906a9c6919 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -558,6 +558,40 @@ const timelineTools = (types: ReadonlyArray) => { const tail = (tools: number) => [...Array(tools).fill("tool_call"), "assistant_message"]; +it.effect("show retains pull request metadata when reading a later message window", () => + Effect.gen(function* () { + const link = { + host: "github.com", + repository: "owner/repo", + number: 1, + url: "https://github.com/owner/repo/pull/1", + source: "manual", + state: "open", + watching: false, + watchStartedAt: null, + } as const; + const call = ((_tool: string, input: unknown) => { + const args = input as { afterPosition?: number; limit: number }; + const first = args.afterPosition === undefined && args.limit === 1; + return Effect.succeed({ + thread: { + itemCount: 200, + status: first ? "running" : "completed", + pullRequestCount: 1, + ...(first ? { pullRequests: [link], openPullRequestCount: 1 } : {}), + }, + items: first ? [] : [{ position: 199, itemId: "message", type: "assistant_message" }], + nextPosition: 199, + hasMore: false, + }); + }) as ThreadTools["call"]; + const { thread } = yield* readLatestMessages({ call }, threadId, 1); + assert.strictEqual(thread.status, "completed"); + assert.deepStrictEqual(thread.pullRequests, [link]); + assert.strictEqual(thread.openPullRequestCount, 1); + }), +); + it.effect("show reads the end of a long thread, not its whole history", () => Effect.gen(function* () { const { tools, served, latest } = timelineTools([ diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index e63e762237e85..09ee65c32172b 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -459,7 +459,8 @@ export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(fun ); afterPosition = page.nextPosition ?? Number.POSITIVE_INFINITY; } while (page.hasMore && afterPosition < (end ?? Number.POSITIVE_INFINITY) - 1); - thread = page.thread; + // Only the first read carries pull request previews; later pages omit them. + thread = Object.assign({}, thread, page.thread); // A window can hold the whole --messages count, too many to spread as arguments. messages = window.concat(messages); before = start; From c3a330d8342f0825293b56c0fd22b20c6ef3206c Mon Sep 17 00:00:00 2001 From: Jinhui Zheng Date: Sun, 22 Nov 2026 18:03:40 +0800 Subject: [PATCH 029/162] fix(web): show Queue for running sessions that cannot steer (#40767) Co-authored-by: Julius Marminge --- apps/web/src/components/ChatView.tsx | 11 ++---- .../src/state/threadWorkflows.test.ts | 34 ++++++++++++++++- .../src/state/threadWorkflows.ts | 37 ++++++++++++++++--- 3 files changed, 68 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 254bbd4eb9e42..d17af4f620755 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -106,10 +106,9 @@ import { } from "@t3tools/client-runtime/state/subagentRuntime"; import { getUserQueuedThreadRuns, - threadSteersDuringCompaction, + threadCanSteer, threadSupportsProviderHandoff, } from "@t3tools/client-runtime/state/thread-workflows"; -import { compactionBlocksSteering } from "@t3tools/client-runtime/state/composer-dispatch"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { HandoffRow } from "./chat/V2LifecycleRow"; import { @@ -1545,12 +1544,10 @@ export default function ChatView(props: ChatViewProps) { const isCompacting = (isSendBusy || phase === "connecting" || phase === "running") && (compactionRunning || compactCommandIsActive); - const compactionBlocksSteer = compactionBlocksSteering({ + const canSteer = threadCanSteer(serverProjection, { compactCommandIsActive, compactionRunning, - steersDuringCompaction: threadSteersDuringCompaction(serverProjection), - run: serverProjection?.runs.find((run) => run.id === activeRuntime?.activeRunId), - messages: serverProjection?.messages, + activeRunId: activeRuntime?.activeRunId, }); const isWorking = deriveTimelineWorking({ phase, @@ -3822,7 +3819,7 @@ export default function ChatView(props: ChatViewProps) { isLocalDraftThread && activeProject === null } phase={phase} - canSteer={!compactionBlocksSteer} + canSteer={canSteer} canInterrupt={canInterruptRunningThread} isSendBusy={ (isSendBusy && !sendQueuesBehindSetup) || diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index a4049c7169163..fd8092a996a66 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -6,6 +6,7 @@ import { deriveThreadQueueWorkflowState, getUserQueuedThreadRuns, resolveLatestMergeBackRun, + threadCanSteer, threadSupportsProviderHandoff, } from "./threadWorkflows.ts"; @@ -13,6 +14,7 @@ const capabilities = (input?: { readonly queued?: boolean; readonly steer?: boolean; readonly restartSteer?: boolean; + readonly interrupt?: boolean; readonly nativeFork?: boolean; readonly portableFork?: boolean; }) => @@ -21,6 +23,7 @@ const capabilities = (input?: { supportsQueuedMessages: input?.queued ?? false, supportsActiveSteering: input?.steer ?? false, supportsSteeringByInterruptRestart: input?.restartSteer ?? false, + supportsInterrupt: input?.interrupt ?? false, }, threads: { canForkThread: input?.nativeFork ?? false, @@ -31,6 +34,35 @@ const capabilities = (input?: { }) as never; describe("thread workflows", () => { + it.each([ + ["queue only", { queued: true }, false, false], + ["session still attaching", undefined, false, true], + ["native steering", { steer: true }, false, true], + ["interrupt and restart", { interrupt: true, restartSteer: true }, false, true], + ["restart without interrupt", { restartSteer: true }, false, false], + ["explicit compaction", { steer: true }, true, false], + ] as const)("gates composer steering for %s", (_, turns, compactCommandIsActive, expected) => { + const projection = { + thread: { id: "thread", activeProviderThreadId: "provider-thread" }, + runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }], + providerThreads: [{ id: "provider-thread", providerSessionId: "session" }], + providerSessions: [ + ...(turns === undefined + ? [] + : [{ id: "session", status: "running", capabilities: capabilities(turns) }]), + { id: "other", status: "ready", capabilities: capabilities({ steer: true }) }, + ], + messages: [], + } as unknown as OrchestrationV2ThreadProjection; + expect( + threadCanSteer(projection, { + compactCommandIsActive, + compactionRunning: false, + activeRunId: projection.runs[0]!.id, + }), + ).toBe(expected); + }); + it("skips message history classification when no runs are queued", () => { let metadataReads = 0; const message = { @@ -139,7 +171,7 @@ describe("thread workflows", () => { { id: "provider-session", status: "running", - capabilities: capabilities({ queued: true, restartSteer: true }), + capabilities: capabilities({ queued: true, interrupt: true, restartSteer: true }), }, ], } as never); diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index 7dbbcf1e80c57..9e3d1eb4512b2 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -8,6 +8,7 @@ import { copySorted } from "@t3tools/shared/Array"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; +import { compactionBlocksSteering } from "./composerDispatch.ts"; import type { ThreadStructure } from "./models.ts"; type Projection = ThreadStructure; @@ -102,6 +103,33 @@ export function threadSteersDuringCompaction(projection: Projection | null | und ); } +function supportsSteering(turns: OrchestrationV2ProviderCapabilities["turns"]): boolean { + return ( + turns.supportsActiveSteering || + (turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) + ); +} + +export function threadCanSteer( + projection: Projection | null, + input: { + readonly compactCommandIsActive: boolean; + readonly compactionRunning: boolean; + readonly activeRunId: Run["id"] | null | undefined; + }, +): boolean { + const turns = projection && resolveThreadProviderSession(projection)?.capabilities.turns; + // A steer submitted before the session attaches can wait for its provider turn. + if (turns && !supportsSteering(turns)) return false; + return !compactionBlocksSteering({ + compactCommandIsActive: input.compactCommandIsActive, + compactionRunning: input.compactionRunning, + steersDuringCompaction: turns?.activeSteeringDuringCompaction === true, + run: projection?.runs.find((run) => run.id === input.activeRunId), + messages: projection?.messages, + }); +} + export function threadSupportsProviderHandoff(projection: Projection | null | undefined): boolean { if (projection == null) return false; const session = resolveThreadProviderSession(projection); @@ -147,6 +175,7 @@ export function deriveThreadQueueWorkflowState( const activeRun = resolveActiveThreadRun(projection); const session = resolveThreadProviderSession(projection); const capabilities = session?.capabilities.turns; + const canSteer = capabilities !== undefined && supportsSteering(capabilities); const activeMessage = projection.messages.find( (message) => message.id === activeRun?.userMessageId, ); @@ -187,12 +216,8 @@ export function deriveThreadQueueWorkflowState( canPromoteToSteer: promoteSkipsCompaction || ((activeRun?.status === "preparing" || activeRun?.status === "starting") && - (capabilities === undefined || - capabilities.supportsActiveSteering || - capabilities.supportsSteeringByInterruptRestart)) || - (hasSteerableProviderTurn && - (capabilities?.supportsActiveSteering === true || - capabilities?.supportsSteeringByInterruptRestart === true)), + (capabilities === undefined || canSteer)) || + (hasSteerableProviderTurn && canSteer), promoteSkipsCompaction, }; } From c198f73b3766090e02cace1a8b14f439f9fc63b6 Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Sun, 22 Nov 2026 15:54:47 +0530 Subject: [PATCH 030/162] fix(web): a click outside the project action editor no longer discards the draft (#40776) --- .../projectScriptEditor.browser.test.tsx | 14 ++++++++++++++ apps/web/src/components/projectScriptEditor.tsx | 2 ++ 2 files changed, 16 insertions(+) diff --git a/apps/web/src/components/projectScriptEditor.browser.test.tsx b/apps/web/src/components/projectScriptEditor.browser.test.tsx index a9ea6f03ad185..0f37c32b23a9e 100644 --- a/apps/web/src/components/projectScriptEditor.browser.test.tsx +++ b/apps/web/src/components/projectScriptEditor.browser.test.tsx @@ -3,6 +3,7 @@ import { EnvironmentId } from "@t3tools/contracts"; import { AsyncResult } from "effect/reactivity"; import { StrictMode } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; vi.mock(import("~/state/session"), async (original) => ({ ...(await original()), @@ -86,3 +87,16 @@ describe("project action editor save lifecycle", () => { expect(onSubmit.mock.calls.map(([scriptId]) => scriptId)).toEqual(["build", "test"]); }); }); + +describe("project action editor dismissal", () => { + it("stays open when the user clicks outside the editor", async () => { + setup(); + await using screen = await render(null); + await open(screen, { scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT }); + await expect.element(page.getByRole("dialog")).toBeVisible(); + + await userEvent.click(document.body, { position: { x: 1, y: 1 } }); + + expect(onClose).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/components/projectScriptEditor.tsx b/apps/web/src/components/projectScriptEditor.tsx index 504e0afc69ca0..ea9b5ca1f2245 100644 --- a/apps/web/src/components/projectScriptEditor.tsx +++ b/apps/web/src/components/projectScriptEditor.tsx @@ -188,6 +188,8 @@ export function ProjectScriptEditorDialog({ <> { if (!open) onClose(); }} From 379a98ac227d9c0b4185e133facfa6d3114c7427 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 02:55:08 -0800 Subject: [PATCH 031/162] fix(server): t3 pair skips Windows VirtualBox and VMware host-only adapters (#33441) --- apps/server/src/environment/DirectEndpoints.ts | 10 ++++++---- apps/server/src/startupAccess.test.ts | 14 ++++++++++++++ apps/server/src/startupAccess.ts | 7 ++++++- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/apps/server/src/environment/DirectEndpoints.ts b/apps/server/src/environment/DirectEndpoints.ts index 4508d208e75e6..c39ca1d85484e 100644 --- a/apps/server/src/environment/DirectEndpoints.ts +++ b/apps/server/src/environment/DirectEndpoints.ts @@ -24,7 +24,12 @@ import { import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "./ServerEnvironment.ts"; -import { isLoopbackHost, isPrivateNetworkAddress, isVirtualInterface } from "../startupAccess.ts"; +import { + isLoopbackHost, + isPrivateNetworkAddress, + isVirtualInterface, + WINDOWS_HOST_ADAPTER_MAC, +} from "../startupAccess.ts"; type NetworkInterfacesMap = ReturnType; @@ -52,9 +57,6 @@ const isTailscaleInterface = ( /^tailscale/i.test(name) || entries.some((entry) => entry.family === "IPv6" && isTailnetHost(entry.address)); -// Windows adapter names are mutable; Linux bridges can inherit these MACs. -const WINDOWS_HOST_ADAPTER_MAC = /^(0a:00:27|00:50:56:c0:00):/i; - export function resolveBoundEndpoints(input: { readonly platform: NodeJS.Platform; readonly host: string | undefined; diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts index 7290d6063db9b..c36c29e5f1278 100644 --- a/apps/server/src/startupAccess.test.ts +++ b/apps/server/src/startupAccess.test.ts @@ -71,6 +71,20 @@ it("prefers a LAN address over a tailnet one for a private-network pairing URL", ).toBe("http://192.168.1.42:3773"); }); +it("skips Windows VirtualBox and VMware host-only adapters for a private-network listener", () => { + expect( + resolveHeadlessConnectionString("0.0.0.0", 3773, { + interfaces: { + "VirtualBox Host-Only Network": [{ ...ipv4("192.168.56.1"), mac: "0a:00:27:00:00:0a" }], + "VMware Network Adapter VMnet8": [{ ...ipv4("192.168.159.1"), mac: "00:50:56:c0:00:08" }], + "Wi-Fi": [{ ...ipv4("192.168.1.20"), mac: "3c:22:fb:12:34:56" }], + }, + privateNetworkOnly: true, + platform: "win32", + }), + ).toBe("http://192.168.1.20:3773"); +}); + it("skips NixOS container and systemd-nspawn veths for a private-network pairing URL", () => { expect( resolveHeadlessConnectionString("0.0.0.0", 3773, { diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts index b065a3fc88172..ce1b8be41938f 100644 --- a/apps/server/src/startupAccess.ts +++ b/apps/server/src/startupAccess.ts @@ -51,6 +51,9 @@ export const isLoopbackHost = (host: string | undefined): boolean => { const VIRTUAL_INTERFACE = /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge[1-9]\d\d)/; +// VirtualBox and VMware host-only adapters on Windows. Their names are mutable; Linux bridges can inherit these MACs. +export const WINDOWS_HOST_ADAPTER_MAC = /^(0a:00:27|00:50:56:c0:00):/i; + /** * systemd-nspawn's `ve-*`/`vz-*` and NixOS containers' `vb-*` name host-side * veths after the machine. Windows aliases are user-renameable, so these @@ -155,7 +158,9 @@ const resolveHeadlessConnectionHost = ( (entry) => !entry.internal && isIpv4Family(entry.family) && - (!privateNetworkOnly || isPrivateNetworkAddress(entry.address)), + (!privateNetworkOnly || + (isPrivateNetworkAddress(entry.address) && + !(platform === "win32" && WINDOWS_HOST_ADAPTER_MAC.test(entry.mac)))), ); // A tailnet or other CGNAT address reaches fewer devices than the LAN one. const externalIpv4 = privateNetworkOnly From 418e1ace0fc6edeb729cb094efb939603b958049 Mon Sep 17 00:00:00 2001 From: Kyros Abas Date: Sun, 22 Nov 2026 18:57:28 +0800 Subject: [PATCH 032/162] fix(server): Word text boxes keep their paragraph breaks for agents (#40782) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 6 ++++-- apps/server/src/provider/userInputAttachments.test.ts | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index 3dd649811f330..70f16961843d3 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -170,9 +170,11 @@ function* all(node: XmlNode, name: string | readonly string[]): Generator { +function* text(node: XmlNode): Generator { if (HIDDEN.has(node.name)) return; - if (["tab", "ptab", "cell"].includes(node.name)) yield "\t"; + // Word text boxes hold their own paragraphs inside the anchoring paragraph. + if (node.name === "txbxContent") yield* paragraphs(node); + else if (["tab", "ptab", "cell"].includes(node.name)) yield "\t"; else if (["br", "line-break", "cr"].includes(node.name)) yield "\n"; else if (node.name === "noBreakHyphen") yield "\u2011"; else if (node.spaceCount !== undefined) { diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 72f7e52a3cd41..dd6c70cfcc00b 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -767,9 +767,9 @@ describe("question answer paths", () => { bounded: true, parts: { "word/document.xml": - 'BodyCallout boxCallout box', + 'BodyCallout boxSecond lineCallout boxSecond line', }, - expected: ["Body\nCallout box"], + expected: ["Body\nCallout box\nSecond line"], occurrences: { text: "Callout box", count: 1 }, }, { From 356dff3352f1014194c6c5861fead3bebc4c15ab Mon Sep 17 00:00:00 2001 From: TheGuyWithHAT Date: Sun, 22 Nov 2026 12:03:54 +0100 Subject: [PATCH 033/162] fix(web): RTF previews respect hidden character formatting (#40783) Co-authored-by: geezoria <25051260+geezoria@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/web/src/components/files/FilePreviewPanel.test.ts | 8 ++++++++ apps/web/src/components/files/extendedDocumentPreview.ts | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 4b736d8b6622e..c2b6aa0b306d7 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -158,6 +158,11 @@ describe("document preview contents", () => { "A\tB\u2003C\u2002D\u2005E\u200dF\u200cG\u200bH\u200eI\u200fJ", ], ["a Unicode fallback", String.raw`{\rtf1 Jean\u8209\_Luc}`, "Jean\u2011Luc"], + [ + "visible text around hidden character formatting", + String.raw`{\rtf1 A{\v hidden{\v0 B}hidden}C\v hidden\v0 D\v hidden\plain E}`, + "ABCDE", + ], ["a tracked replacement", String.raw`{\rtf1 aaa{\deleted bbb}{\revised BBB}ccc}`, "aaaBBBccc"], [ "text after a deletion reset", @@ -232,6 +237,9 @@ Third}`; expect(html(textEdit.replaceAll("\n", "\r\n"))).toEqual(expected); const lineBreak = html(String.raw`{\rtf1\ansi First line\line Second line}`); expect(lineBreak).toEqual(["

    First line
    Second line

    "]); + expect(html(String.raw`{\rtf1\ansi{\v\line\line\line}First line\line Second line}`)).toEqual( + lineBreak, + ); expect(html(String.raw`{\rtf1\ansi First line\uc0\u8232 Second line}`)).toEqual(lineBreak); expect(html(String.raw`{\rtf1\ansi First line\u8232?Second line{\deleted\u8232?}}`)).toEqual( lineBreak, diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 7d6021de6f811..f107ea0266043 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -538,6 +538,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { let state = { skip: false, deleted: false, + hiddenText: false, bold: false, italic: false, underline: false, @@ -560,7 +561,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { }; let run = ""; let fallback = 0; - const hidden = () => state.skip || state.deleted; + const hidden = () => state.skip || state.deleted || state.hiddenText; const encoded = new Uint8Array(bytes.byteLength); let encodedLength = 0; const flush = () => { @@ -722,10 +723,12 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { else if (word === "ul") state.underline = arg !== 0; else if (word === "ulnone") state.underline = false; else if (word === "deleted") state.deleted = arg !== 0; + else if (word === "v") state.hiddenText = arg !== 0; else if (word === "plain") state = { ...state, deleted: false, + hiddenText: false, bold: false, italic: false, underline: false, From 5fc2eb2f4750230304c2a3c083f425854a16627a Mon Sep 17 00:00:00 2001 From: Arun Krishnamurthy Date: Sun, 22 Nov 2026 05:10:03 -0600 Subject: [PATCH 034/162] fix(mobile): the iOS composer keeps its keyboard and caret after dictation (#33916) Co-authored-by: Julius Marminge --- apps/mobile/src/features/issues/IssueCommentComposer.tsx | 6 +++++- apps/mobile/src/features/threads/ThreadComposer.tsx | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/issues/IssueCommentComposer.tsx b/apps/mobile/src/features/issues/IssueCommentComposer.tsx index 75ff1199595a3..901dee46152a4 100644 --- a/apps/mobile/src/features/issues/IssueCommentComposer.tsx +++ b/apps/mobile/src/features/issues/IssueCommentComposer.tsx @@ -170,7 +170,11 @@ export function IssueCommentComposer(props: { /> {/* TalkBack orders siblings by position; outside this row the editor reads after Send. */} Date: Sun, 22 Nov 2026 11:16:00 +0000 Subject: [PATCH 035/162] fix(shared): find file links whose labels contain brackets (#40781) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- packages/shared/src/markdownLinks.test.ts | 3 ++ packages/shared/src/markdownLinks.ts | 49 ++++++++++------------- 2 files changed, 25 insertions(+), 27 deletions(-) diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index a1f0af927636d..80204d903892b 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -174,6 +174,9 @@ describe("extractMarkdownLinkHrefs", () => { ["[".repeat(32_000), []], ["[a]( invalid [b](ok)", [" { expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 50450a1e787de..e3458f04f3484 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -519,41 +519,36 @@ function markdownLinkDestinationScanner(markdown: string) { } } const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart); - if (hrefEnd === null || hrefEnd === hrefStart) return null; + if (hrefEnd === null) return null; const end = bareTail(hrefEnd); return end === null ? null : { hrefStart, hrefEnd, end }; }; } -// The composer escapes brackets in labels (`[\[id\].tsx](...)`), and `\]` does not close one. -function unescapedLabelEnd(markdown: string, start: number): number { - let end = markdown.indexOf("]", start); - while (end !== -1) { - let backslashes = 0; - while (end - backslashes > start && markdown[end - backslashes - 1] === "\\") backslashes += 1; - if (backslashes % 2 === 0) return end; - end = markdown.indexOf("]", end + 1); - } - return -1; -} - +// Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them +// (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels. export function extractMarkdownLinkHrefs(markdown: string): string[] { const hrefs: string[] = []; const scanDestination = markdownLinkDestinationScanner(markdown); - let cursor = 0; - while (cursor < markdown.length) { - const labelStart = markdown.indexOf("[", cursor); - if (labelStart === -1) break; - const labelEnd = unescapedLabelEnd(markdown, labelStart + 1); - if (labelEnd === -1) break; - - // Skip a failed label once; nested openings share its closing bracket. - cursor = labelEnd + 1; - const destination = scanDestination(cursor); - if (!destination) continue; - cursor = destination.end; - const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); - if (href) hrefs.push(href); + const bracket = /[[\]\\]|\n[ \t\r]*\n/g; + let openBrackets = 0; + for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) { + if (match[0] === "\\") { + bracket.lastIndex = match.index + 2; + } else if (match[0].startsWith("\n")) { + openBrackets = 0; + } else if (match[0] === "[") { + openBrackets += 1; + } else if (openBrackets > 0) { + openBrackets -= 1; + const destination = scanDestination(match.index + 1); + if (!destination) continue; + // A link cannot contain a link, so the brackets still open around it become text. + openBrackets = 0; + bracket.lastIndex = destination.end; + const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); + if (href) hrefs.push(href); + } } return hrefs; } From 1acfd37c17ea49340705092d8ee3d41c210a0a99 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:19:46 -0800 Subject: [PATCH 036/162] fix(web): restore effort picker keyboard typeahead (#40798) Co-authored-by: shadowfeind --- .../chat/ComposerModelEffort.browser.test.tsx | 24 +++++++++++++++++++ .../components/chat/ComposerModelEffort.tsx | 23 ++++++++++++++---- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx index ab7d560d5c676..1678552dd0ab2 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx @@ -122,3 +122,27 @@ it("draws an agent's reasoning as bars and keeps its mode out of the levels", as .toBeInTheDocument(); await expect.element(page.getByRole("menuitemradio")).not.toBeInTheDocument(); }); + +it("focuses a reasoning level by its first letter without selecting it", async () => { + await using screen = await render(, { router: false }); // no routes involved + await userEvent.tab(); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("l"); + await expect.element(screen.getByRole("radio", { name: "Low" })).toHaveFocus(); + await expect + .element(screen.getByRole("radio", { name: "Medium" })) + .toHaveAttribute("aria-checked", "true"); + for (const key of ["{Control>}h{/Control}", "{Meta>}h{/Meta}", "{Alt>}h{/Alt}", "{Delete}"]) { + await userEvent.keyboard(key); + await expect.element(screen.getByRole("radio", { name: "Low" })).toHaveFocus(); + } + await userEvent.keyboard("H"); + await expect.element(screen.getByRole("radio", { name: "High" })).toHaveFocus(); + // Wraps past the last level back to the first match. + await userEvent.keyboard("m"); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("h{Enter}"); + await expect + .element(screen.getByRole("radio", { name: "High" })) + .toHaveAttribute("aria-checked", "true"); +}); diff --git a/apps/web/src/components/chat/ComposerModelEffort.tsx b/apps/web/src/components/chat/ComposerModelEffort.tsx index 1d0227c0f6482..b5d5a519a3410 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.tsx @@ -206,8 +206,8 @@ function ColumnRow(props: { "aria-checked": props.selected, disabled: props.disabled, "data-effort-row": true, - // Focus lands on a level after a model pick. - "data-effort-level": true, + // Focus lands on a level after a model pick, and a typed letter finds one by its label. + "data-effort-level": props.label, // Up and Down move between rows. tabIndex: props.tabStop ? 0 : -1, className: COLUMN_ROW, @@ -244,15 +244,28 @@ function ColumnRow(props: { } function moveBetweenRows(event: KeyboardEvent) { - if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return; + const arrow = event.key === "ArrowDown" || event.key === "ArrowUp"; + if ( + !arrow && + (event.key.length !== 1 || + event.key.trim() === "" || + event.ctrlKey || + event.altKey || + event.metaKey || + event.nativeEvent.isComposing) + ) + return; // An option's side menu is a React child here, but it moves through its own items. if (!event.currentTarget.contains(event.target as Node)) return; const rows = Array.from( event.currentTarget.querySelectorAll("[data-effort-row]:not(:disabled)"), ); const index = rows.findIndex((row) => row === document.activeElement); - const next = - rows[Math.min(rows.length - 1, Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)))]; + const next = arrow + ? rows[Math.min(rows.length - 1, Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)))] + : [...rows.slice(index + 1), ...rows.slice(0, index + 1)].find((row) => + row.dataset.effortLevel?.toLowerCase().startsWith(event.key.toLowerCase()), + ); if (!next) return; event.preventDefault(); event.stopPropagation(); From 0ae3154695e5b6808a8fb9955f69d78d9c1274fa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:19:58 -0800 Subject: [PATCH 037/162] fix(server): migration 75 no longer fails on an unreadable subagent payload (#30783) --- .../075_SubagentDeliveryState.test.ts | 48 +++++++++++++++++++ .../Migrations/075_SubagentDeliveryState.ts | 4 +- 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts diff --git a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts new file mode 100644 index 0000000000000..c652d1f9bc851 --- /dev/null +++ b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.test.ts @@ -0,0 +1,48 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; + +const layer = it.layer(NodeSqliteClient.layer({ filename: ":memory:" })); +const updatedAt = "2026-09-01T00:00:00.000Z"; +const deliveredPayload = JSON.stringify({ completionDelivery: { state: "delivered" } }); + +layer("075_SubagentDeliveryState", (it) => { + it.effect("backfills delivery state without failing on an unreadable payload", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 74 }); + const payloads = [ + ["delivered", deliveredPayload], + ["unreadable", ""], + ]; + for (const [id, payload] of payloads) { + yield* sql` + INSERT INTO orchestration_v2_projection_subagents ( + subagent_id, thread_id, parent_node_id, provider, origin, status, updated_at, + payload_json + ) VALUES ( + ${id}, 'thread-1', 'node-1', 'codex', 'delegated', 'cancelled', ${updatedAt}, + ${payload} + ) + `; + } + + yield* runMigrations({ toMigrationInclusive: 75 }); + const rows = yield* sql` + SELECT subagent_id, completion_delivery_state, payload_json + FROM orchestration_v2_projection_subagents ORDER BY subagent_id + `; + assert.deepStrictEqual(rows, [ + { + subagent_id: "delivered", + completion_delivery_state: "delivered", + payload_json: deliveredPayload, + }, + { subagent_id: "unreadable", completion_delivery_state: null, payload_json: "" }, + ]); + }), + ); +}); diff --git a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts index 4406911cc8a8c..0288c89ceed05 100644 --- a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts +++ b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts @@ -11,7 +11,9 @@ export default Effect.gen(function* () { yield* sql` UPDATE orchestration_v2_projection_subagents SET completion_delivery_state = json_extract(payload_json, '$.completionDelivery.state') - WHERE json_type(payload_json, '$.completionDelivery') IS NOT NULL + WHERE CASE WHEN json_valid(payload_json) + THEN json_type(payload_json, '$.completionDelivery') IS NOT NULL + ELSE 0 END `; yield* sql` CREATE INDEX orchestration_v2_projection_subagents_settled_idx From 671e05bc8cdd83c90673a0e254e43f6042263547 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:20:57 -0800 Subject: [PATCH 038/162] fix(issues): an Activity cross-reference opens the issue or pull request it came from (#40768) --- .../src/features/issues/IssueRouteScreen.tsx | 60 ++++++++++++++++- .../chat/RightPanelSurfaceContent.tsx | 19 +++++- .../src/components/issue/IssueDetailPanel.tsx | 65 ++++++++++++++++++- apps/web/src/components/issue/IssuesPage.tsx | 9 ++- packages/contracts/src/issue.ts | 10 +++ .../src/server/GitHubIssueTracker.test.ts | 9 +++ .../src/server/gitHubIssueJson.ts | 30 ++++++--- .../src/server/issues.graphql | 1 + .../src/server/issues.graphql.ts | 4 +- .../src/server/GitLabIssueTracker.test.ts | 14 ++++ .../src/server/GitLabIssueTracker.ts | 10 ++- .../src/server/gitLabIssueJson.ts | 35 ++++++++++ 12 files changed, 247 insertions(+), 19 deletions(-) diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx index 2e5354b23f50f..8312bb703894b 100644 --- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx +++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx @@ -7,6 +7,7 @@ import { visibleLinkedThreads } from "@t3tools/client-runtime/state/threads"; import type { IssueComment, IssueEvent, + IssueEventReference, IssueLinkedPullRequest, IssueReaction, IssueState, @@ -404,9 +405,48 @@ function IssueCommentCard(props: { ); } -function IssueEventRow({ event }: { readonly event: IssueEvent }) { +function IssueEventRow({ + params, + event, +}: { + readonly params: IssueParams; + readonly event: IssueEvent; +}) { const gt = useGT(); const messages = useMessages(); + const navigation = useNavigation(); + const sentence = issueEventSentence(event, messages); + const source = event.reference; + const at = event.detail === null ? -1 : sentence.indexOf(event.detail); + // Only a git host's tracker shares its host with the change request it links. + const sameHost = sourceControlClients.find(params.tracker) !== undefined; + const openSource = (target: IssueEventReference) => { + const host = params.host ? { host: params.host } : {}; + if (target.kind === "issue") { + navigation.dispatch( + StackActions.push("Issue", { + environmentId: params.environmentId, + projectId: params.projectId, + tracker: params.tracker, + ...host, + scope: target.repository, + issueKey: String(target.number), + }), + ); + } else if (sameHost) { + navigation.dispatch( + StackActions.push("PullRequest", { + environmentId: params.environmentId, + projectId: params.projectId, + repository: target.repository, + number: target.number, + ...host, + }), + ); + } else { + void tryOpenExternalUrl(target.url); + } + }; return ( @@ -414,7 +454,21 @@ function IssueEventRow({ event }: { readonly event: IssueEvent }) { {event.actor?.login ?? gt("Someone", { $context: "an unknown person" })} {" "} - {issueEventSentence(event, messages)} + {source === undefined || event.detail === null || at < 0 ? ( + sentence + ) : ( + <> + {sentence.slice(0, at)} + openSource(source)} + > + {event.detail} + + {sentence.slice(at + event.detail.length)} + + )} {relativeTime(event.createdAt, undefined, messages)} @@ -505,7 +559,7 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { ...detail.events.map((event) => ({ key: `e:${event.id}`, at: event.createdAt, - content: , + content: , })), ].sort((left, right) => Date.parse(left.at) - Date.parse(right.at)) : []; diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 076c78d88d468..8b4bb6232287b 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -141,9 +141,14 @@ export function RightPanelSurfaceContent(props: { getShortcutContext={props.getShortcutContext} shortcutsEnabled={visible && props.activeSurfaceId === surface.id} key={`${scopedThreadKey(threadRef)}:${surface.id}`} - environmentId={props.environmentId} + environmentId={ + (surface.environmentId as EnvironmentId | undefined) ?? props.environmentId + } onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, @@ -205,12 +210,24 @@ export function RightPanelSurfaceContent(props: { threadRef={threadRef} onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, ...(reference.host ? { host: reference.host } : {}), }); }} + onSelectIssue={({ host, ...reference }) => { + useRightPanelStore.getState().openIssue(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), + ...reference, + ...(host ? { host } : {}), + }); + }} /> ); case "pull-requests": diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx index bdee83563a330..30a55dd1d9e48 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.tsx @@ -18,6 +18,7 @@ import type { IssueComment, IssueDetail, IssueEvent, + IssueEventReference, IssueLabelCandidate, IssueLinkedPullRequest, IssueListEntry, @@ -376,12 +377,44 @@ function LinkedPullRequestRow({ ); } +/** The sentence for an event, its source shown as a link where the tracker named one. */ +function IssueEventText({ + event, + sentence, + onOpen, +}: { + event: IssueEvent; + sentence: string; + /** Opens the source beside this issue, and says whether it did; if not, the link goes to the host. */ + onOpen: (source: IssueEventReference) => boolean; +}) { + const source = event.reference; + const at = event.detail === null ? -1 : sentence.indexOf(event.detail); + if (source === undefined || event.detail === null || at < 0) return {sentence}; + return ( + + {sentence.slice(0, at)} + } + onClick={(click) => { + if (!click.metaKey && !click.ctrlKey && onOpen(source)) click.preventDefault(); + }} + > + {event.detail} + + {sentence.slice(at + event.detail.length)} + + ); +} + export function IssueDetailPanel({ environmentId, reference, threadRef = null, listEntry = null, onSelectPullRequest, + onSelectIssue, }: { environmentId: EnvironmentId; reference: IssueRef; @@ -390,6 +423,8 @@ export function IssueDetailPanel({ threadRef?: ScopedThreadRef | null; /** Opens a linked change request beside this one; absent, the link goes to the host. */ onSelectPullRequest?: ((reference: PullRequestRef) => void) | undefined; + /** Opens a referenced issue beside this one; absent, the link goes to the host. */ + onSelectIssue?: ((reference: IssueRef & { readonly url: string }) => void) | undefined; }) { const gt = useGT(); const messages = useMessages(); @@ -442,6 +477,30 @@ export function IssueDetailPanel({ const tracker = issueTrackerPresentation(detail.tracker); const currentState = issueStatePresentation(detail.state); + const host = reference.host === undefined ? {} : { host: reference.host }; + const openEventSource = (source: IssueEventReference) => { + if (source.kind === "pull-request") { + if (!onSelectPullRequest) return false; + onSelectPullRequest({ + projectId: reference.projectId, + ...host, + repository: source.repository, + number: source.number, + }); + return true; + } + if (!onSelectIssue) return false; + onSelectIssue({ + projectId: reference.projectId, + tracker: reference.tracker, + ...host, + scope: source.repository, + key: String(source.number), + url: source.url, + }); + return true; + }; + const loadOlder = async () => { const failure = await pager.loadOlder(registry, (cursor) => loadComments({ environmentId, input: { ...reference, cursor } }), @@ -869,7 +928,11 @@ export function IssueDetailPanel({ className="px-1 text-xs text-muted-foreground" > - {issueEventSentence(item.event, messages)} + {formatRelativeTimeLabel(item.event.createdAt, undefined, messages)} ), diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index e29e3aa3c8123..d1c9f77aa2917 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -419,7 +419,7 @@ export function IssuesPage() { : clearedSelection, ); - const selectEntry = (entry: IssueRowTarget) => { + const selectEntry = (entry: Omit & { readonly host?: string }) => { if (rightPanelRef === null) return; useRightPanelStore.getState().openIssue(rightPanelRef, entry); updateSearch({ @@ -864,6 +864,13 @@ export function IssuesPage() { environmentId: panelEnvironmentId, }); }} + onSelectIssue={({ host, ...reference }) => + selectEntry({ + ...reference, + ...(host === undefined ? {} : { host }), + environmentId: panelEnvironmentId, + }) + } /> ) : ( event.kind === "referenced")).toMatchObject({ + reference: { + repository: "acme/web", + number: 50, + kind: "pull-request", + url: "https://github.com/acme/web/pull/50", + }, + }); }), ); }); diff --git a/packages/source-control-github/src/server/gitHubIssueJson.ts b/packages/source-control-github/src/server/gitHubIssueJson.ts index e46ad7ec9e515..59e9b9efd118e 100644 --- a/packages/source-control-github/src/server/gitHubIssueJson.ts +++ b/packages/source-control-github/src/server/gitHubIssueJson.ts @@ -5,7 +5,6 @@ import type { IssueActor, IssueComment, IssueEvent, - IssueEventKind, IssueLabel, IssueLinkedPullRequest, IssueState, @@ -137,7 +136,7 @@ function toLinkedPullRequest( /** The change GitHub recorded, or null for a kind this page has no vocabulary for. */ function toEventFields( raw: TimelineItem, -): { readonly kind: IssueEventKind; readonly detail: string | null } | null { +): Pick | null { switch (raw.__typename) { case "ClosedEvent": return { kind: "closed", detail: null }; @@ -164,15 +163,28 @@ function toEventFields( case "RenamedTitleEvent": return { kind: "renamed", detail: trimmed(raw.currentTitle) }; case "CrossReferencedEvent": { - const repository = trimmed( - raw.source != null && "repository" in raw.source - ? raw.source.repository.nameWithOwner - : null, - ); - const number = raw.source != null && "number" in raw.source ? raw.source.number : 0; + const source = + raw.source.__typename === "PullRequest" || raw.source.__typename === "Issue" + ? raw.source + : null; + const repository = trimmed(source?.repository.nameWithOwner); + const url = trimmed(source?.url); + if (source === null || repository === null || source.number <= 0) { + return { kind: "referenced", detail: null }; + } return { kind: "referenced", - detail: repository === null || number <= 0 ? null : `${repository}#${number}`, + detail: `${repository}#${source.number}`, + ...(url === null + ? {} + : { + reference: { + repository, + number: source.number, + kind: source.__typename === "PullRequest" ? "pull-request" : "issue", + url, + }, + }), }; } default: diff --git a/packages/source-control-github/src/server/issues.graphql b/packages/source-control-github/src/server/issues.graphql index 18c8cee3536a2..d8b28a08c7078 100644 --- a/packages/source-control-github/src/server/issues.graphql +++ b/packages/source-control-github/src/server/issues.graphql @@ -231,6 +231,7 @@ query IssueDetail($owner: String!, $name: String!, $number: Int!) { } ... on Issue { number + url repository { nameWithOwner } diff --git a/packages/source-control-github/src/server/issues.graphql.ts b/packages/source-control-github/src/server/issues.graphql.ts index 9d059396d26a0..fb393ef5ca4c6 100644 --- a/packages/source-control-github/src/server/issues.graphql.ts +++ b/packages/source-control-github/src/server/issues.graphql.ts @@ -487,6 +487,8 @@ export const SourceIssue = Schema.Struct({ __typename: Schema.Literal("Issue"), /** Identifies the issue number. */ number: Shared.Int, + /** The HTTP URL for this issue */ + url: Shared.URI, /** The repository associated with this node. */ repository: NodesRepositoryRepository }) @@ -584,7 +586,7 @@ export const IssueDetail = GraphQL.query("IssueDetail", { ], selections: [ { name: "viewer", body: ["{login}"] }, - { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number repository{nameWithOwner}}}}}}}}"] } + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number url repository{nameWithOwner}}}}}}}}"] } ], fragments: [ { name: "IssueRow", body: ["on Issue{number title url state stateReason createdAt updatedAt closedAt author{__typename login avatarUrl...on User{name}}}"] }, diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts index 7c794de8b456e..d3bd6e01366bd 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts @@ -59,6 +59,13 @@ function answer(path: string): string { created_at: "2026-07-03T00:00:00Z", system: true, }, + { + id: 10, + body: "mentioned in merge request api!51", + author: { username: "theo" }, + created_at: "2026-07-04T00:00:00Z", + system: true, + }, ]); } if (path.startsWith("projects/acme%2Fweb/issues/42/resource_label_events")) { @@ -206,7 +213,14 @@ describe("GitLabIssueTracker", () => { expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([ ["labeled", "bug"], ["closed", null], + ["referenced", "merge request api!51"], ]); + expect(issue.events.at(-1)?.reference).toEqual({ + repository: "acme/api", + number: 51, + kind: "pull-request", + url: "https://gitlab.com/acme/api/-/merge_requests/51", + }); // A closing merge request is not repeated as a related one. expect( issue.linkedPullRequests.map((link) => [link.number, link.closesIssue, link.isDraft]), diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts index f8b1f80c18b0e..4f4aeb3135034 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts @@ -25,6 +25,7 @@ import { decodeIssueDetailListJson, decodeIssueListJson, decodeIssueNotesJson, + withMentionReference, decodeLabelEventsJson, decodeLinkedMergeRequestsJson, decodeProjectLabelsJson, @@ -576,9 +577,12 @@ export const make: Effect.Effect = reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [], })), commentsCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null), - events: [...systemEvents, ...labelEvents].sort((left, right) => - left.createdAt.localeCompare(right.createdAt), - ), + events: [ + ...systemEvents.map((event) => + withMentionReference(event, issue.url, input.scope), + ), + ...labelEvents, + ].sort((left, right) => left.createdAt.localeCompare(right.createdAt)), // A merge request that closes the issue outranks its sighting as a mere mention. linkedPullRequests: [ ...closing, diff --git a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts index 5458ed4f859ef..7a52667a4a425 100644 --- a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts @@ -250,6 +250,41 @@ function toSystemEvent( return null; } +// The path class excludes the sigil, so matching is linear on any input. +const MENTION = /^(?:merge request ([\w.\-/]*)!|issue ([\w.\-/]*)#)([1-9]\d*)$/; + +/** + * Where a "mentioned in merge request !12" note came from, addressed from the issue's own web URL + * so a self-managed host under a subpath resolves. A commit, epic or snippet mention gets none. + */ +export function withMentionReference( + event: IssueEvent, + issueUrl: string, + scope: string, +): IssueEvent { + const match = event.kind === "referenced" ? MENTION.exec(event.detail ?? "") : null; + const projectUrl = issueUrl.split("/-/")[0]!; + if (match === null || !projectUrl.toLowerCase().endsWith(`/${scope.toLowerCase()}`)) { + return event; + } + const [, mergeRequestPath, issuePath, digits] = match; + const isMergeRequest = mergeRequestPath !== undefined; + const path = mergeRequestPath ?? issuePath ?? ""; + // A project in the same namespace is named by its path alone. + const repository = + path === "" ? scope : path.includes("/") ? path : `${scope.replace(/[^/]*$/, "")}${path}`; + const base = projectUrl.slice(0, projectUrl.length - scope.length); + return { + ...event, + reference: { + repository, + number: Number(digits), + kind: isMergeRequest ? "pull-request" : "issue", + url: `${base}${repository}/-/${isMergeRequest ? "merge_requests" : "issues"}/${digits}`, + }, + }; +} + interface GitLabIssueNotes { readonly comments: ReadonlyArray; readonly events: ReadonlyArray; From 8435a8cd418f6d46bbb00e812be1f53932c2aac8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:25:22 -0800 Subject: [PATCH 039/162] fix(server): tell a stopped parent which delegated tasks its Stop interrupted (#34499) --- .../DelegatedCompletionDelivery.test.ts | 133 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 17 ++- .../ProviderTurnStartService.ts | 56 ++++++-- .../RestartBackgroundNote.test.ts | 52 +++++++ .../orchestration-v2/RestartBackgroundNote.ts | 72 ++++++++++ 5 files changed, 315 insertions(+), 15 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 441c9992e73cc..3d6575bd6a405 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -19,6 +19,7 @@ import { ProviderInstanceId, ProviderSessionId, ProviderThreadId, + ProviderTurnId, RunId, RuntimeRequestId, ThreadId, @@ -5063,6 +5064,138 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { }), ); + // regression: #34401 a parent's Stop killed a child's background build but its task read completed + it.effect("reports a child its parent's Stop reached as interrupted", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const stoppedAt = DateTime.add(now, { seconds: 10 }); + const threadId = ThreadId.make("thread:stop-background-parent"); + const projectId = ProjectId.make("project:stop-background-parent"); + const runId = RunId.make("run:stop-background-parent"); + const rootNodeId = NodeId.make("node:stop-background-parent-root"); + yield* seedParentWithTerminalTask({ + threadId, + projectId, + runId, + rootNodeId, + taskId: NodeId.make("node:stop-background-parent-settled"), + deliveryState: "delivered", + now, + }); + // Background launches report their command finished at once; only the roster tracks the work. + const seedStoppedChild = (name: string, parentStopped: boolean, reachedTurn: boolean) => + Effect.gen(function* () { + const child = yield* seedRestartCancelledChild({ + parentThreadId: threadId, + projectId, + parentRunId: runId, + rootNodeId, + name, + completionWake: "always", + continuationPending: false, + runStatus: "completed", + now, + }); + const item = { + threadId: child.childThreadId, + runId: child.childRunId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + }; + const scope = { + type: "turn-item.updated" as const, + threadId: child.childThreadId, + runId: child.childRunId, + providerInstanceId: modelSelection.instanceId, + }; + yield* eventSink.write({ + commandId: CommandId.make(`command:${name}:stop`), + events: [ + { + ...scope, + id: EventId.make(`event:${name}:command`), + occurredAt: now, + payload: { + ...item, + id: TurnItemId.make(`turn-item:${name}:command`), + type: "command_execution", + ordinal: 1, + status: "completed", + title: "Run build", + input: "./build.sh", + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }, + { + ...scope, + id: EventId.make(`event:${name}:interrupt-request`), + occurredAt: stoppedAt, + payload: { + ...item, + id: TurnItemId.make(`turn-item:${name}:interrupt-request`), + // Stop interrupting background work names its provider turn; an idle run's marker does not. + providerTurnId: reachedTurn ? ProviderTurnId.make(`provider-turn:${name}`) : null, + type: "run_interrupt_request", + ordinal: 2, + status: "completed", + title: "Interrupt requested", + startedAt: stoppedAt, + completedAt: stoppedAt, + updatedAt: stoppedAt, + message: "Stopped by user", + }, + }, + ], + }); + if (parentStopped) { + const task = (yield* orchestrator.getThreadProjection(threadId)).subagents.find( + (row) => row.id === child.taskId, + )!; + yield* eventSink.write({ + commandId: CommandId.make(`command:${name}:parent-stop`), + events: [ + { + id: EventId.make(`event:${name}:disposed`), + type: "subagent.updated", + threadId, + runId, + nodeId: task.id, + driver, + providerInstanceId: modelSelection.instanceId, + occurredAt: stoppedAt, + payload: { + ...task, + completionDelivery: { state: "disposed", observedByRunId: null }, + updatedAt: stoppedAt, + }, + }, + ], + }); + } + return child; + }); + const cut = yield* seedStoppedChild("stop-background-cut", true, true); + const idle = yield* seedStoppedChild("stop-background-idle", true, false); + const finished = yield* seedStoppedChild("stop-background-finished", false, true); + + yield* orchestrator.recoverDelegatedTasks; + + const settled = yield* orchestrator.getThreadProjection(threadId); + const statusOf = (taskId: NodeId) => + settled.subagents.find((row) => row.id === taskId)?.status; + assert.equal(statusOf(cut.taskId), "interrupted"); + assert.equal(statusOf(idle.taskId), "completed"); + assert.equal(statusOf(finished.taskId), "completed"); + }), + ); + it.effect("cancelling a task whose child already finished keeps its completed result", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 61f5027793569..5936f57ad5014 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -15132,7 +15132,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageRoles: ["assistant"], messageRunIds: resultRunIds, turnItemRunIds: resultRunIds, - turnItemTypes: SUBAGENT_RESULT_TURN_ITEM_TYPES, + turnItemTypes: [...SUBAGENT_RESULT_TURN_ITEM_TYPES, "run_interrupt_request"], providerTurnAttemptIds: [childRun, ...reportRuns].flatMap( (run) => run.activeAttemptId ?? [], ), @@ -15177,9 +15177,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (task === undefined) { return; } - // A cancelled task's completed run ends it interrupted. + // A cancelled task's completed run ends it interrupted, as does one whose provider turn its + // parent's Stop interrupted to kill background work. Stop's marker on an idle run names no + // provider turn and interrupted nothing. const cancelled = task.cancelledRunId === childRun.id; - if (cancelled && terminalStatus === "completed") outcome = terminalStatus = "interrupted"; + const stopped = + task.completionDelivery?.state === "disposed" && + childResult.turnItems.some( + (item) => + item.runId === childRun.id && + item.type === "run_interrupt_request" && + item.providerTurnId !== null, + ); + if ((cancelled || stopped) && terminalStatus === "completed") + outcome = terminalStatus = "interrupted"; // Every result the child sent is among its own transfers, far fewer than the parent's. const childTransfers = yield* projectionStore.getThreadRecords(childThreadId, [ "contextTransfers", diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index c3890cab5f71b..752b13568a111 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -80,7 +80,9 @@ import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; import { isRestartNoteContinuation, pendingRestartCancelledBackgroundWork, + pendingStoppedDelegatedTasks, restartCancelledBackgroundWorkNote, + stoppedDelegatedTasksNote, } from "./RestartBackgroundNote.ts"; export class ProviderTurnStartError extends Schema.TaggedError()( @@ -1029,26 +1031,56 @@ export const layer: Layer.Layer< projection.providerTurns, projection.attempts, ); + let compactionMessageIdSet: ReadonlySet | undefined; + const compactionMessageIds = () => + (compactionMessageIdSet ??= new Set( + projection.messages + .filter( + (candidate) => + isCompactionCommandMessage(candidate) || + (goalDriver && parseGoalCommand(candidate) !== null), + ) + .map((candidate) => candidate.id), + )); const restartCancelledWork = pendingRestartCancelledBackgroundWork({ runs: projection.runs, providerTurns: projection.providerTurns, - compactionMessageIds: () => - new Set( - projection.messages - .filter( - (candidate) => - isCompactionCommandMessage(candidate) || - (goalDriver && parseGoalCommand(candidate) !== null), - ) - .map((candidate) => candidate.id), - ), + compactionMessageIds, run, attempts: projection.attempts, }); - const restartNote = + // The turn start context omits settled tasks, so read them only after a Stop disposed some. + // A failed read fails the start: a turn that ran without the note would count as telling it. + const stoppedRunIds = projection.runs + .filter( + (source) => + source.providerThreadId === run.providerThreadId && + source.delegatedCompletion?.disposition === "stopped", + ) + .map((source) => source.id); + const stoppedTasks = + stoppedRunIds.length === 0 || compactionMessageIds().has(run.userMessageId) + ? [] + : pendingStoppedDelegatedTasks({ + providerThreadId: run.providerThreadId, + runs: projection.runs, + providerTurns: projection.providerTurns, + attempts: projection.attempts, + compactionMessageIds: compactionMessageIds(), + subagents: (yield* projectionStore.getThreadRecords( + projection.thread.id, + ["subagents"], + { subagentRunIds: stoppedRunIds }, + )).subagents, + }); + const restartNote = [ restartCancelledWork.length === 0 ? "" - : restartCancelledBackgroundWorkNote(restartCancelledWork); + : restartCancelledBackgroundWorkNote(restartCancelledWork), + stoppedTasks.length === 0 ? "" : stoppedDelegatedTasksNote(stoppedTasks), + ] + .filter((part) => part !== "") + .join("\n\n"); const tokenCap = yield* handoffTokenCapConfig.pipe( Effect.orElseSucceed(() => DEFAULT_HANDOFF_TOKEN_CAP), ); diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts index b5b3a033789dd..bd5b016fdc673 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts @@ -1,10 +1,12 @@ import { assert, it } from "@effect/vitest"; import { MessageId, + NodeId, ProviderThreadId, RunAttemptId, RunId, type OrchestrationV2Run, + type OrchestrationV2Subagent, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -14,7 +16,9 @@ import { isAwaitedWork, isRestartNoteContinuation, pendingRestartCancelledBackgroundWork, + pendingStoppedDelegatedTasks, restartContinuationNote, + stoppedDelegatedTasksNote, mergeRestartCancelledBackgroundWork, } from "./RestartBackgroundNote.ts"; @@ -277,3 +281,51 @@ it("counts a prompted mid-turn or chained continuation as delivering the note", [], ); }); + +// regression: #34401 Stop interrupted a parent's delegated tasks without telling its agent +it("tells the next completed turn about delegated tasks its Stop interrupted, once", () => { + const at = (minute: number) => DateTime.makeUnsafe(`2026-10-03T10:0${minute}:00.000Z`); + const spawning = run(1, claudeThread, { + requestedAt: at(0), + delegatedCompletion: { disposition: "stopped", nextGeneration: 1, delivery: null }, + }); + const task = (id: string, extra: Partial = {}) => + ({ + id: NodeId.make(id), + runId: spawning.id, + origin: "app_owned", + prompt: `Run ${id}.`, + title: null, + status: "interrupted", + completionDelivery: { state: "disposed", observedByRunId: null }, + completedAt: at(1), + ...extra, + }) as OrchestrationV2Subagent; + const stopped = task("stopped", { title: "Build A" }); + const subagents = [ + stopped, + task("cancelled", { cancelledRunId: RunId.make("run:child") }), + task("finished", { status: "completed" }), + task("delivered", { completionDelivery: { state: "delivered", observedByRunId: null } }), + ]; + const pending = (runs: ReadonlyArray, providerThreadId = claudeThread) => + pendingStoppedDelegatedTasks({ + providerThreadId, + runs, + providerTurns: runs.map(turnFor), + attempts: runs.map((source) => ({ id: source.activeAttemptId!, runId: source.id })), + subagents, + compactionMessageIds: new Set(), + }); + + assert.deepEqual(pending([spawning]), [stopped]); + // A /clear turn starts a fresh provider thread that never saw the stopped tasks. + assert.deepEqual(pending([spawning], codexThread), []); + assert.equal(stoppedDelegatedTasksNote([stopped]).split("\n")[1], "- Build A (task stopped)"); + // Requested while the task was still settling, so its turn start could not see it. + const racing = run(2, claudeThread, { requestedAt: at(0), startedAt: at(2) }); + assert.deepEqual(pending([spawning, racing]), [stopped]); + assert.deepEqual(pending([spawning, racing, run(3, claudeThread, { requestedAt: at(2) })]), []); + // A fresh-context turn on another provider thread never carried the note. + assert.deepEqual(pending([spawning, run(3, codexThread, { requestedAt: at(2) })]), [stopped]); +}); diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index 58918bdef612d..878392b8377c6 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -13,6 +13,7 @@ import { } from "@t3tools/contracts"; import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import * as DateTime from "effect/DateTime"; import { latestRootProviderFailure, runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; type Work = OrchestrationV2RestartCancelledBackgroundWork; @@ -150,6 +151,77 @@ export function restartCancelledBackgroundWorkNote( ].join("\n"); } +/** + * Delegated tasks a Stop on this provider thread interrupted, until a turn requested after they + * ended completes. A run's turn start reads tasks after its request, but can record startedAt + * later. A fresh context starts a new provider thread, so it never inherits the note. + */ +export function pendingStoppedDelegatedTasks(input: { + readonly providerThreadId: OrchestrationV2Run["providerThreadId"]; + readonly runs: ReadonlyArray; + readonly providerTurns: ReadonlyArray>; + readonly attempts: ReadonlyArray; + readonly subagents: ReadonlyArray; + readonly compactionMessageIds: ReadonlySet; +}): ReadonlyArray { + const stoppedRunIds = new Set( + input.runs + .filter( + (run) => + run.providerThreadId === input.providerThreadId && + run.delegatedCompletion?.disposition === "stopped", + ) + .map((run) => run.id), + ); + if (stoppedRunIds.size === 0) return []; + const completedAttemptIds = new Set( + input.providerTurns + .filter((turn) => turn.status === "completed") + .map((turn) => turn.runAttemptId), + ); + const toldRunRequests = input.runs + .filter( + (run) => + run.providerThreadId === input.providerThreadId && + !input.compactionMessageIds.has(run.userMessageId) && + input.attempts.some( + (attempt) => attempt.runId === run.id && completedAttemptIds.has(attempt.id), + ), + ) + .map((run) => DateTime.toEpochMillis(run.requestedAt)); + return input.subagents.filter( + (task) => + task.origin === "app_owned" && + task.runId !== null && + stoppedRunIds.has(task.runId) && + task.status === "interrupted" && + task.cancelledRunId === undefined && + task.completionDelivery?.state === "disposed" && + task.completedAt !== null && + !toldRunRequests.some( + (requestedAt) => requestedAt > DateTime.toEpochMillis(task.completedAt!), + ), + ); +} + +export function stoppedDelegatedTasksNote(tasks: ReadonlyArray): string { + const omitted = tasks.length - MAX_NOTE_ENTRIES; + return [ + "Note: Stop on this thread also stopped these delegated tasks before they finished. They will not report back on their own, so check them with task_status and start again what you still need:", + ...tasks + .slice(0, MAX_NOTE_ENTRIES) + .map( + (task) => + `- ${labelWithId( + compactLabel(task.title) === undefined ? task.prompt : task.title, + "delegated task", + ` (task ${task.id})`, + )}`, + ), + ...(omitted > 0 ? [`- and ${omitted} more`] : []), + ].join("\n"); +} + type ProviderTurnState = Pick< OrchestrationV2ProviderTurn, "runAttemptId" | "providerThreadId" | "status" | "promptDropped" From f931f03d6115bbe7f2dde6817c43620f6df20528 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:26:17 -0800 Subject: [PATCH 040/162] fix(server): worktree thread lookups match any spelling of the path (#36802) Co-authored-by: Alex Southwell <4596216+saphid@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- .../orchestration-v2/ProjectionStore.test.ts | 41 ++++++++++++++----- .../src/orchestration-v2/ProjectionStore.ts | 22 ++++++++-- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/106_WorktreePathKeyIndex.ts | 16 ++++++++ .../reconcileV2PreviewMigration.test.ts | 2 + 5 files changed, 70 insertions(+), 13 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index b6539e46344f1..1667a176a54a0 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -3197,6 +3197,14 @@ it.effect("SQL shells read a subagent family and a worktree's threads", () => yield* createThread({ name: "archived-child", parent: "root", root: "root", archived: true }); yield* createThread({ name: "other", worktreePath: "/repo" }); yield* createThread({ name: "other-child", parent: "other", root: "other", worktreePath }); + yield* createThread({ + name: "aliased-child", + parent: "other", + root: "other", + worktreePath: `${worktreePath}/`, + }); + yield* createThread({ name: "cased", worktreePath: worktreePath.toUpperCase() }); + yield* createThread({ name: "windows", worktreePath: "C:\\Répo\\WT" }); const family = (threadId: ThreadId) => store @@ -3208,26 +3216,39 @@ it.effect("SQL shells read a subagent family and a worktree's threads", () => assert.sameMembers([...(yield* family(id("grandchild")))], tree); assert.deepEqual([...(yield* family(id("missing")))], []); - // Includes another root's idle child on the same path, which a shell may leave out. + // Includes another root's idle child on the same path, which a shell may leave out, under any + // spelling of that path. POSIX paths keep their case. const { statements, tracer } = traceSqlStatements(); const onWorktree = yield* store .getShellSnapshot({ location: "active", worktreePath }) .pipe(Effect.withTracer(tracer)); assert.sameMembers( onWorktree.threads.map((thread) => thread.id), - [id("root"), id("child"), id("other-child")], + [id("root"), id("child"), id("other-child"), id("aliased-child")], + ); + const onWindowsWorktree = yield* store + .getShellSnapshot({ location: "active", worktreePath: "c:/Répo/wt/" }) + .pipe(Effect.withTracer(tracer)); + assert.deepEqual( + onWindowsWorktree.threads.map((thread) => thread.id), + [id("windows")], ); - // A path names a few threads; scanning every thread parses every payload. + // A path, ASCII or not, names a few threads; scanning every thread parses every payload. const sql = yield* SqlClient.SqlClient; - const threadQuery = statements.find((statement) => + const threadQueries = statements.filter((statement) => statement.includes("AS latest_run_stop_requested"), ); - assert.isDefined(threadQuery); - const threadPlan = (yield* sql.unsafe<{ readonly detail: string }>( - `EXPLAIN QUERY PLAN ${threadQuery}`, - [], - )).map((row) => row.detail); - assert.notInclude(threadPlan, "SCAN t", threadPlan.join("\n")); + assert.lengthOf(threadQueries, 2); + for (const threadQuery of threadQueries) { + const threadPlan = (yield* sql.unsafe<{ readonly detail: string }>( + `EXPLAIN QUERY PLAN ${threadQuery}`, + [], + )).map((row) => row.detail); + assert.isFalse( + threadPlan.some((detail) => detail.startsWith("SCAN t ")), + threadPlan.join("\n"), + ); + } // A fork keeps its deleted source's root, so the deleted root still names the live tree. yield* store.apply({ id: EventId.make("event:family:root-deleted"), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index a42679d304765..36cab7ab167c7 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -102,6 +102,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import type * as Statement from "effect/sql/Statement"; import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; +import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; import { DELEGATED_TASK_MESSAGE_CONDITION } from "./delegatedTaskMessage.ts"; import { @@ -1258,6 +1259,7 @@ type ShellThreadRow = { readonly thread_id: string; readonly payload_json: string; readonly forked_from_run_source_thread_id: string | null; + readonly worktree_path: string | null; readonly latest_run_id: string | null; readonly latest_run_status: string | null; readonly latest_run_requested_at: string | null; @@ -8397,6 +8399,7 @@ export const layer: Layer.Layer = THEN json_extract(t.payload_json, '$.forkedFrom.threadId') ELSE NULL END AS forked_from_run_source_thread_id, + json_extract(t.payload_json, '$.worktreePath') AS worktree_path, presented.run_id AS latest_run_id, presented.status AS latest_run_status, presented.requested_at AS latest_run_requested_at, @@ -8593,8 +8596,12 @@ export const layer: Layer.Layer = }${ worktreePath === undefined ? sql`` - : sql` AND CASE WHEN json_valid(t.payload_json) - THEN json_extract(t.payload_json, '$.worktreePath') END = ${worktreePath}` + : // Matches orchestration_v2_projection_threads_worktree_path_key_idx, so this never + // scans. SQLite lower() folds only ASCII: Windows paths differing only in the case + // of another letter are not found. readShellSnapshotRows keeps the exact comparison. + sql` AND CASE WHEN json_valid(t.payload_json) + THEN lower(rtrim(replace(trim(json_extract(t.payload_json, '$.worktreePath')), '\\', '/'), '/')) + END = lower(rtrim(replace(trim(${worktreePath}), '\\', '/'), '/'))` }${threadIds === undefined ? sql`` : sql` AND t.thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)}))`} ORDER BY t.updated_at ASC, t.thread_id ASC `; @@ -9213,7 +9220,16 @@ export const layer: Layer.Layer = const readShellSnapshotRows = Effect.fn("ProjectionStore.readShellSnapshotRows")(function* ( options: ShellSnapshotOptions | undefined, ) { - const targetThreadRows = yield* selectShellThreadRows(undefined, options); + const worktreeKey = + options?.worktreePath === undefined + ? undefined + : normalizeProjectPathForComparison(options.worktreePath); + const targetThreadRows = (yield* selectShellThreadRows(undefined, options)).filter( + (row) => + worktreeKey === undefined || + (row.worktree_path !== null && + normalizeProjectPathForComparison(row.worktree_path) === worktreeKey), + ); const targetThreadIds = new Set(targetThreadRows.map((row) => ThreadId.make(row.thread_id))); const rowsByThreadId = new Map( targetThreadRows.map((row) => [ThreadId.make(row.thread_id), row] as const), diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 91b521fdb6036..1b4dd6cc66ccd 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -113,6 +113,7 @@ import Migration0102 from "./Migrations/102_ThreadItemCounts.ts"; import Migration0103 from "./Migrations/103_IssueTrackerAdditionalScopes.ts"; import Migration0104 from "./Migrations/104_ProjectionProjectsTrackedFolders.ts"; import Migration0105 from "./Migrations/105_TaskFolders.ts"; +import Migration0106 from "./Migrations/106_WorktreePathKeyIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -221,6 +222,7 @@ const migrationEntries = [ [103, "IssueTrackerAdditionalScopes", Migration0103], [104, "ProjectionProjectsTrackedFolders", Migration0104], [105, "TaskFolders", Migration0105], + [106, "WorktreePathKeyIndex", Migration0106], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts b/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts new file mode 100644 index 0000000000000..9b1b42647d60a --- /dev/null +++ b/apps/server/src/persistence/Migrations/106_WorktreePathKeyIndex.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Keep this expression identical to ProjectionStore's loose worktree filter. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_threads_worktree_path_key_idx + ON orchestration_v2_projection_threads( + CASE WHEN json_valid(payload_json) + THEN lower(rtrim(replace(trim(json_extract(payload_json, '$.worktreePath')), '\\', '/'), '/')) + END + ) + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index d2b0dafab8731..42fbb26edaa82 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -85,6 +85,7 @@ describe("V2 preview upgrade", () => { [103, "IssueTrackerAdditionalScopes"], [104, "ProjectionProjectsTrackedFolders"], [105, "TaskFolders"], + [106, "WorktreePathKeyIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -213,6 +214,7 @@ describe("V2 preview upgrade", () => { [103, "IssueTrackerAdditionalScopes"], [104, "ProjectionProjectsTrackedFolders"], [105, "TaskFolders"], + [106, "WorktreePathKeyIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From c585a58598d594255e6e550702cc982925aa6e3f Mon Sep 17 00:00:00 2001 From: xiemin Date: Sun, 22 Nov 2026 19:28:33 +0800 Subject: [PATCH 041/162] fix(mobile): prevent clipped percentages in usage limit cards (#40778) Co-authored-by: Julius Marminge --- apps/mobile/src/features/usage/UsageLimitsPooled.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 4c290d68ac338..50a987787b4e4 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -211,7 +211,7 @@ function PoolWindowCard({ {label ?? pool.label} ) : null} - + {pool.remainingPercent}% From 989247488db978c1bf5fb519726a0677568e3c7f Mon Sep 17 00:00:00 2001 From: Rodrigo Brechard Date: Sun, 22 Nov 2026 12:33:02 +0100 Subject: [PATCH 042/162] test(web): browser tests no longer fail when a stale optimizer cache reloads them mid-run (#31999) Co-authored-by: Rodrigo Brechard Co-authored-by: Julius Marminge --- apps/web/vite.config.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 005e828202bda..e107c9a7e7491 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -111,6 +111,9 @@ const browserTestProject = { include: [ "vite-plus/test/browser", "@base-ui/react/autocomplete", + "@effect/vitest", + "@pierre/diffs/ssr", + "effect/testing", "saxes", "@betteroffice/docx/editor", "@betteroffice/docx/layout", From 62a7108904c37f225c09864f6f857f7b7474dbc1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 03:33:14 -0800 Subject: [PATCH 043/162] fix(github): superseded runs' cancelled checks no longer block PR watches (#30434) --- .../src/server/GitHubPullRequestApi.test.ts | 16 +- .../src/server/gitHubPullRequestJson.test.ts | 145 +++++++++++++++++- .../src/server/gitHubPullRequestJson.ts | 43 +++++- .../src/server/pullRequestReads.graphql | 3 + .../src/server/pullRequestReads.graphql.ts | 10 +- 5 files changed, 209 insertions(+), 8 deletions(-) diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index c3cc15097dfd5..9d155cab2b794 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -3949,13 +3949,25 @@ layer("GitHubPullRequestApi.layer", (it) => { name: "build", status: "COMPLETED", conclusion: "SUCCESS", - checkSuite: { workflowRun: { workflow: { name: "linux" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_linux", name: "linux" }, + }, + }, }), checkRun({ name: "build", status: "COMPLETED", conclusion: "FAILURE", - checkSuite: { workflowRun: { workflow: { name: "windows" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_windows", name: "windows" }, + }, + }, }), ], pageInfo: { hasNextPage: false, endCursor: null }, diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts index 37db822d34386..e049943a3978f 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts @@ -359,10 +359,18 @@ describe("pull request detail decoding", () => { checkSuite: { workflowRun: null }, ...fields, }; - const inWorkflow = ({ workflowName, ...fields }: Record) => + const inWorkflow = ({ + workflowName, + workflowId = `W_kwDORLtfbc4${String(workflowName)}`, + event = "pull_request", + runNumber = 95380, + ...fields + }: Record) => check({ ...fields, - checkSuite: { workflowRun: { workflow: { name: workflowName } } }, + checkSuite: { + workflowRun: { event, runNumber, workflow: { id: workflowId, name: workflowName } }, + }, }); const coreJson = ( @@ -655,6 +663,139 @@ describe("pull request detail decoding", () => { } }); + it("drops a cancelled check whose workflow run was superseded by a newer run on the head", () => { + const superseded = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + status: "COMPLETED", + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:00:05Z", + }; + const replacement = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95380, + status: "COMPLETED", + conclusion: "SUCCESS", + startedAt: "2026-10-30T10:00:10Z", + completedAt: "2026-10-30T10:05:00Z", + }; + const rollup = [ + inWorkflow({ ...superseded, name: "check", conclusion: "CANCELLED" }), + inWorkflow({ + ...superseded, + name: "web browser tests (runner ${{ matrix.slice }} of 6)", + conclusion: "CANCELLED", + }), + inWorkflow({ ...replacement, name: "check" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 1 of 6)" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 2 of 6)" }), + ]; + const detail = detailOf(rollup); + + expect([detail.checks.map((check) => [check.name, check.status]), detail.checksState]).toEqual([ + [ + ["check", "success"], + ["web browser tests (runner 1 of 6)", "success"], + ["web browser tests (runner 2 of 6)", "success"], + ], + "passing", + ]); + }); + + it("keeps a cancelled check when the newer run is another workflow with the same name", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + conclusion: "CANCELLED", + }), + inWorkflow({ + name: "lint", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4ToKTh", + runNumber: 95380, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test", + "cancelled", + ]); + expect(detail.checksState).toBe("failing"); + }); + + it("drops a required cancelled check once a newer run reports it, whenever it finished", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 41, + conclusion: "CANCELLED", + isRequired: true, + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:09:00Z", + }), + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 42, + conclusion: "SUCCESS", + isRequired: true, + startedAt: "2026-10-30T10:01:00Z", + completedAt: "2026-10-30T10:05:00Z", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toEqual([["test", "success"]]); + expect(detail.checksState).toBe("passing"); + }); + + it.each([ + ["a push", "push", "push", "CANCELLED", false, "cancelled"], + ["another event", "pull_request", "pull_request_target", "CANCELLED", false, "cancelled"], + ["a pull request run", "pull_request", "pull_request", "FAILURE", false, "failure"], + [ + "a pull request run, if required", + "pull_request", + "pull_request", + "CANCELLED", + true, + "cancelled", + ], + ])( + "keeps an older run's check when the newer run is %s", + (_label, olderEvent, newerEvent, conclusion, isRequired, status) => { + const detail = detailOf([ + inWorkflow({ + name: "test (packages/shared)", + workflowName: "CI", + event: olderEvent, + runNumber: 41, + conclusion, + isRequired, + }), + inWorkflow({ + name: "test (apps/server)", + workflowName: "CI", + event: newerEvent, + runNumber: 42, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test (packages/shared)", + status, + ]); + expect(detail.checksState).toBe("failing"); + }, + ); + it("merges reviews with comments in time order and keeps a bodyless approval", () => { const detail = expectSuccess(activity(JSON.parse(detailJson) as Record)); expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]); diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 7fbe86839d495..9eed567a6a4da 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -131,6 +131,13 @@ interface LatestReviewFields { readonly isMinimized?: boolean | undefined; } +/** Run numbers count up per workflow file, whatever its name; database ids exceed int32. */ +interface WorkflowRunFields { + readonly event: string; + readonly runNumber: number; + readonly workflow: { readonly id: string }; +} + /** Check runs use status/conclusion; commit statuses use a single state. */ interface CheckFields { readonly name?: string | null | undefined; @@ -143,6 +150,8 @@ interface CheckFields { readonly targetUrl?: string | null | undefined; /** Empty for app-owned runs; absent for commit statuses. */ readonly workflowName?: string | null | undefined; + /** Absent for commit statuses and app-owned runs. */ + readonly workflowRun?: WorkflowRunFields | null | undefined; readonly startedAt?: string | null | undefined; readonly completedAt?: string | null | undefined; /** Branch protection requires this check; asked for on github.com only. */ @@ -617,16 +626,42 @@ function isNamelessCheck(raw: CheckFields): boolean { return trimmed(raw.name) === null && trimmed(raw.context) === null; } -/** Unfinished runs outrank finished runs of the same check across push/PR workflows. */ +const PULL_REQUEST_EVENTS = new Set(["pull_request", "pull_request_target"]); + +/** + * Unfinished runs outrank finished runs of the same check across push/PR workflows. A newer pull + * request run of a workflow supersedes the older one's cancelled checks, whose names can differ + * (an unexpanded matrix). Other events can run one commit in different scopes (a branch and a + * tag, dispatch inputs), so their runs replace nothing. + */ function toCheckEntries(raw: ReadonlyArray | null | undefined): ReadonlyArray<{ readonly check: PullRequestCheck; readonly workflowName: string | null; readonly at: string | null; }> { + const lineageOf = (run: WorkflowRunFields) => `${run.workflow.id} ${run.event}`; + const newestRunNumber = new Map(); + const note = (key: string, runNumber: number) => { + if (runNumber > (newestRunNumber.get(key) ?? Number.NEGATIVE_INFINITY)) { + newestRunNumber.set(key, runNumber); + } + }; + for (const check of raw ?? []) { + const run = check.workflowRun; + if (run == null || !PULL_REQUEST_EVENTS.has(run.event)) continue; + note(lineageOf(run), run.runNumber); + note(`${lineageOf(run)} ${trimmed(check.name) ?? ""}`, run.runNumber); + } return (raw ?? []).flatMap((check) => { const name = trimmed(check.name) ?? trimmed(check.context); if (name === null) return []; const status = toCheckStatus(check); + const run = check.workflowRun; + if (status === "cancelled" && run != null) { + // Branch protection names required checks, so only a newer same-name check replaces one. + const replacedBy = check.isRequired === true ? `${lineageOf(run)} ${name}` : lineageOf(run); + if (run.runNumber < (newestRunNumber.get(replacedBy) ?? run.runNumber)) return []; + } return [ { check: { @@ -1246,7 +1281,11 @@ export type GitHubCheckContext = CheckFields; function toCheckContexts(nodes: ReadonlyArray): ReadonlyArray { return nodes.map((check) => check.__typename === "CheckRun" - ? { ...check, workflowName: check.checkSuite.workflowRun?.workflow.name ?? null } + ? { + ...check, + workflowName: check.checkSuite.workflowRun?.workflow.name ?? null, + workflowRun: check.checkSuite.workflowRun, + } : check, ); } diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql index 2799b67525a27..0b8c5350c1408 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql +++ b/packages/source-control-github/src/server/pullRequestReads.graphql @@ -42,7 +42,10 @@ fragment CheckContext on StatusCheckRollupContext { isRequired(pullRequestNumber: $number) @include(if: $required) checkSuite { workflowRun { + event + runNumber workflow { + id name } } diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts index ab5e211a4dec2..d26912d6aee7b 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts @@ -23,6 +23,8 @@ export interface StatusContext extends Schema.Struct.Type {} /** A workflow run. */ export const WorkflowRun = Schema.Struct({ + /** The event that triggered the workflow run */ + event: Schema.String, + /** A number that uniquely identifies this workflow run in its parent workflow. */ + runNumber: Shared.Int, /** The workflow executed in this workflow run. */ workflow: Workflow }) @@ -565,7 +571,7 @@ export const PullRequestCore = GraphQL.query("PullRequestCore", { { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt mergeCommit{oid}mergedBy{__typename login avatarUrl...on User{name}}closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}mergeQueueRemovals:timelineItems(last:1 itemTypes:[REMOVED_FROM_MERGE_QUEUE_EVENT])@include(if:$", "mergeQueue", "){nodes{__typename...on RemovedFromMergeQueueEvent{id createdAt reason}}}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color description}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { @@ -617,7 +623,7 @@ export const PullRequestCheckContexts = GraphQL.query("PullRequestCheckContexts" { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){headRefOid commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100 after:$", "after", "){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { From a8363dad7fa72f7f313dbcae5f7576a6383381c5 Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Sun, 22 Nov 2026 17:12:14 +0530 Subject: [PATCH 044/162] fix(web): keybindings using '+' show a plus keycap instead of empty pills (#40808) Co-authored-by: Julius Marminge --- .../KeybindingsSettings.logic.test.ts | 10 ++++++ .../settings/KeybindingsSettings.logic.ts | 8 +++-- .../settings/KeybindingsSettings.tsx | 33 ++++++++++--------- 3 files changed, 33 insertions(+), 18 deletions(-) diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts index 4468d0ee66a14..64984a238c251 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts @@ -14,6 +14,7 @@ import { keybindingFromKeyboardEvent, parseWhenExpressionDraft, shortcutToKeybindingInput, + shortcutToKeybindingParts, unknownWhenVariables, whenAstToExpression, } from "./KeybindingsSettings.logic"; @@ -250,6 +251,15 @@ describe("KeybindingsSettings.logic", () => { ).toBe("mod+m"); }); + it("keeps a literal plus key as its own part", () => { + expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod++")!)).toEqual(["mod", "+"]); + expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod+shift++")!)).toEqual([ + "mod", + "shift", + "+", + ]); + }); + it("serializes shortcuts and when expressions for upserts", () => { expect( shortcutToKeybindingInput({ diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 99ff61182d626..55d4278b0fe16 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -88,7 +88,7 @@ export const DEFAULT_WHEN_VARIABLE = ) ?? "terminalFocus"; const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES); -export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string { +export function shortcutToKeybindingParts(shortcut: KeybindingShortcut): ReadonlyArray { const parts: string[] = []; if (shortcut.modKey) parts.push("mod"); if (shortcut.metaKey) parts.push("meta"); @@ -96,7 +96,11 @@ export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string if (shortcut.altKey) parts.push("alt"); if (shortcut.shiftKey) parts.push("shift"); parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key); - return parts.join("+"); + return parts; +} + +export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string { + return shortcutToKeybindingParts(shortcut).join("+"); } export function whenAstToExpression(node: KeybindingWhenNode | undefined): string { diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 6e78c7c1935a6..0b6cc7ed41f81 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -28,6 +28,7 @@ import { AuthOrchestrationOperateScope, AuthSettingsWriteScope, type KeybindingCommand, + type KeybindingShortcut, type KeybindingWhenNode, type ServerRemoveKeybindingInput, type ServerUpsertKeybindingInput, @@ -86,6 +87,7 @@ import { keybindingFromKeyboardEvent, parseWhenExpressionDraft, groupKeybindingRows, + shortcutToKeybindingParts, type KeybindingCommandOption, type KeybindingGroup, type KeybindingRow, @@ -100,35 +102,34 @@ import { keybindingSearchAnchorId, useSearchableSetting } from "./settingsSearch import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { useAtomCommand } from "../../state/use-atom-command"; -function KeybindingPill({ value }: { value: string }) { - // Keys dedupe repeated parts; a literal "+" in a shortcut splits into empty strings. - const seenParts = new Map(); - const parts = value.split("+").map((part) => { - const seen = seenParts.get(part) ?? 0; - seenParts.set(part, seen + 1); - return { part, key: seen === 0 ? part : `${part}-${seen}` }; - }); +function KeybindingPill({ shortcut }: { shortcut: KeybindingShortcut }) { + const isMac = navigator.platform.toLowerCase().includes("mac"); + const parts = shortcutToKeybindingParts(shortcut); + const modifierParts = parts.slice(0, -1); + const keyPart = parts.at(-1); + return ( - {parts.map(({ part, key }) => ( - + {modifierParts.map((part) => ( + {part === "mod" - ? navigator.platform.toLowerCase().includes("mac") + ? isMac ? "⌘" : "Ctrl" : part === "shift" ? "⇧" : part === "alt" - ? navigator.platform.toLowerCase().includes("mac") + ? isMac ? "⌥" : "Alt" : part === "ctrl" ? "⌃" - : part.length === 1 - ? part.toUpperCase() - : part} + : part} ))} + {keyPart !== undefined ? ( + {keyPart.length === 1 ? keyPart.toUpperCase() : keyPart} + ) : null} ); } @@ -915,7 +916,7 @@ function KeybindingKeyControl({ Unassigned ) : ( - + )} ) : ( From d27d29fe2d31fa260a7653f54401917940e1b578 Mon Sep 17 00:00:00 2001 From: Justin Jacob <159104807+justsrc@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:20:38 +0530 Subject: [PATCH 045/162] fix(web): lineage show-more no longer clips the last row or drops focus (#31295) Co-authored-by: Justin <159104807+Justin24506@users.noreply.github.com> Co-authored-by: Julius Marminge --- ...hreadRelationshipsControl.browser.test.tsx | 42 +++++++++++++++++++ .../chat/ThreadRelationshipsControl.tsx | 13 +++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 052a5742b7aab..666ce784b3afc 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -236,6 +236,48 @@ it("opens an idle child beside the thread, and in its place with the modifier", expect(panel().surfaces).toHaveLength(1); }); +it("keeps focus on the list when Show more pages reveal the last rows", async () => { + setup(); + const projection = makeThreadProjectionFixture(); + const environmentId = EnvironmentId.make("local"); + const { updatedAt } = projection.thread; + state.projection = { + ...projection, + subagents: Array.from({ length: 7 }, (_, index) => ({ + id: NodeId.make(`agent-${index}`), + threadId: projection.thread.id, + runId: null, + parentNodeId: NodeId.make("parent"), + origin: "app_owned", + createdBy: "agent", + driver: "codex", + providerInstanceId: projection.thread.providerInstanceId, + providerThreadId: null, + childThreadId: ThreadId.make(`omitted-child-${index}`), + nativeTaskRef: null, + prompt: `Inspect the change part ${index}`, + title: `Agent ${index}`, + model: null, + status: "completed", + result: null, + startedAt: null, + completedAt: updatedAt, + updatedAt, + })), + }; + await using screen = await render( + , + ); + await screen.getByRole("button", { name: /Previous agents/ }).click(); + await screen.getByRole("button", { name: "Show 1 more" }).click(); + await expect.element(screen.getByRole("list", { name: "Related threads" })).toHaveFocus(); +}); + it("shows a lineage thread's full title in its tooltip", async () => { setup(); const longTitle = "Compare the lineage tooltip against a title that the row truncates"; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 9675a21620d32..b005fa877b745 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -121,19 +121,28 @@ function ThreadLineageRowList(props: { readonly children: ReactNode; }) { const gt = useGT(); + const listRef = useRef(null); + const showMore = () => { + const exhausting = props.hiddenCount <= THREAD_LINEAGE_PAGE_COUNT; + props.onShowMore(); + // The button unmounts on the final page; focus the list so focus isn't dropped. + if (exhausting) listRef.current?.focus({ preventScroll: true }); + }; return ( <> {/* ScrollArea's max-height viewport measures badly inside this scrolling panel. */}
      {props.children}
    {props.hiddenCount > 0 ? ( + } + />, + ); + const editor = editorIn(screen.container); + await userEvent.click(editor.view.dom, { position: { x: 12, y: 12 } }); + await vi.waitFor(() => expect(editor.view.hasFocus()).toBe(true)); + await userEvent.click(screen.getByRole("button", { name: "Tab" })); + expect(onClick).toHaveBeenCalledOnce(); +}); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index c3fb7fad73ff8..402156b001286 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -1975,7 +1975,7 @@ function ComposerPromptEditorTiptapInner( {isEmpty && contextRecords.size === 0 && placeholder ? (
    From 1e78f37618f087f8606a0bc5a4e49f546c9e2781 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:06:56 -0800 Subject: [PATCH 068/162] fix(web): keep script-only drafts reachable in the sidebar (#25272) --- apps/web/src/components/Sidebar.tsx | 20 +++++- .../SidebarDraftBlock.browser.test.tsx | 53 +++++++++++++++- .../components/sidebar/SidebarDraftBlock.tsx | 62 ++++++++++++++++--- apps/web/src/lib/discardComposerDraft.test.ts | 17 +++++ apps/web/src/lib/discardComposerDraft.ts | 32 +++++----- apps/web/src/state/terminalSessions.ts | 48 +++++++++++++- 6 files changed, 202 insertions(+), 30 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 0c14aea9056b1..f8527d0d75a1f 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -271,7 +271,12 @@ import { type SidebarProviderEntry, type SidebarSweepAction, } from "./sidebar/SidebarThreadRow"; -import { SidebarDraftBlock, useSidebarDrafts } from "./sidebar/SidebarDraftBlock"; +import { + draftTerminalLabel, + SidebarDraftBlock, + useDraftTerminalLabels, + useSidebarDrafts, +} from "./sidebar/SidebarDraftBlock"; import { SidebarProjectFolderHeader, sidebarFolderRowId, @@ -1199,13 +1204,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : { projectIds: scopedProjectRefs.map((projectRef) => projectRef.projectId) }, ); const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null; + const draftTerminalLabels = useDraftTerminalLabels(); const visibleDraftSessionCount = useComposerDraftStore((store) => { let count = 0; for (const [draftKey, session] of Object.entries(store.draftThreadsByThreadKey)) { if (session.promotedTo != null) { continue; } - if (!composerDraftHasUserContent(store.draftsByThreadKey[draftKey])) { + if ( + draftTerminalLabel(session, draftTerminalLabels) === null && + !composerDraftHasUserContent(store.draftsByThreadKey[draftKey]) + ) { continue; } if ( @@ -1440,7 +1449,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const settledThreadKeysRef = useRef(settledThreadKeys); const snoozedThreadKeysRef = useRef(snoozedThreadKeys); - const { draftIds, routeDraftComposer } = useSidebarDrafts(scopedProjectKeys, routeDraftIdForRows); + const { draftIds, routeDraftComposer } = useSidebarDrafts( + scopedProjectKeys, + routeDraftIdForRows, + draftTerminalLabels, + ); // Draft rows sit above the threads, so jumps and traversal reach them first. // Search hides them, so they drop out while it is open. const listedDraftIds = isSearchingThreads ? EMPTY_DRAFT_IDS : draftIds; @@ -3576,6 +3589,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve key="draft-sessions" draftIds={draftIds} routeDraftComposer={routeDraftComposer} + terminalLabels={draftTerminalLabels} jumpLabelByDraftId={draftJumpLabelById} projectByKey={projectByKey} projectDisplayNameByKey={projectDisplayNameByKey} diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx index 7b7adf7a31ea5..9e2e6a058f220 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx @@ -8,16 +8,24 @@ import { formatAssistantCitationForComposer } from "../../composer-logic"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { SidebarDraftBlock, useSidebarDrafts } from "./SidebarDraftBlock"; -function DraftBlock() { - const { draftIds, routeDraftComposer } = useSidebarDrafts(null, null); +const NO_TERMINAL_LABELS: ReadonlyMap = new Map(); + +function DraftBlock(props: { + routeDraftId?: string | null; + terminalLabels?: ReadonlyMap; +}) { + const routeDraftId = props.routeDraftId ?? null; + const terminalLabels = props.terminalLabels ?? NO_TERMINAL_LABELS; + const { draftIds, routeDraftComposer } = useSidebarDrafts(null, routeDraftId, terminalLabels); return ( @@ -91,3 +99,42 @@ it("keeps draft previews current through edits, promotion and removal", async () await act(() => initial.clearDraftThread(nextDraftId)); await expect.element(row).not.toBeInTheDocument(); }); + +it("lists empty drafts by terminal label while their terminal exists, active or not", async () => { + const initial = useComposerDraftStore.getState(); + using _store = { + [Symbol.dispose]: () => useComposerDraftStore.setState(initial, true), + }; + useComposerDraftStore.setState({ + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, + }); + const environmentId = EnvironmentId.make("draft-terminal-environment"); + const terminalDraftId = DraftId.make("draft-with-terminal"); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("terminal-project")), + terminalDraftId, + { threadId: ThreadId.make("terminal-thread") }, + ); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("idle-project")), + DraftId.make("draft-without-terminal"), + { threadId: ThreadId.make("idle-thread") }, + ); + + const terminalLabels = new Map([[`${environmentId}:terminal-thread`, "dev"]]); + const block = (routeDraftId: string | null) => ( +
      + +
    + ); + await using screen = await render(block(terminalDraftId)); + const rows = screen.getByTestId("sidebar-draft-row"); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); + + await screen.rerender(block(null)); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); +}); diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 3a4a74bb64f18..4cb082a1f7ddd 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -12,8 +12,10 @@ import { type MouseEvent as ReactMouseEvent, } from "react"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId } from "@t3tools/contracts"; import { useShallow } from "zustand/react/shallow"; import { cn } from "~/lib/utils"; +import { useTerminalLabelsByThreadKey } from "~/state/terminalSessions"; import { resolveSidebarRowAccessibility } from "../Sidebar.logic"; import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -31,9 +33,41 @@ import { JumpHintBadge, } from "./SidebarThreadRow"; +const EMPTY_COMPOSER_PARTS = { + prompt: "", + images: [], + persistedAttachments: [], + files: [], + terminalContexts: [], + previewAnnotations: [], + reviewComments: [], +} as const; + +/** Terminal labels for draft threads; an unsent draft stays listed while it has a terminal. */ +export function useDraftTerminalLabels(): ReadonlyMap { + const environmentIds = useComposerDraftStore((store) => { + const ids = new Set(); + for (const session of Object.values(store.draftThreadsByThreadKey)) { + if (session.promotedTo == null) ids.add(session.environmentId); + } + return [...ids].toSorted().join("\n"); + }); + return useTerminalLabelsByThreadKey( + environmentIds === "" ? [] : (environmentIds.split("\n") as EnvironmentId[]), + ); +} + +export function draftTerminalLabel( + session: DraftSessionState, + terminalLabels: ReadonlyMap, +): string | null { + return terminalLabels.get(`${session.environmentId}:${session.threadId}`) ?? null; +} + const SidebarDraftRow = memo(function SidebarDraftRow(props: { draftId: DraftId; - composer: ComposerThreadDraftState; + composer: ComposerThreadDraftState | null; + terminalLabel: string | null; project: ProjectFaviconProject | null; projectDisplayName: string | null; isActive: boolean; @@ -46,7 +80,8 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { source: ContextMenuSource, ) => void; }) { - const { composer, draftId, onContextMenu, onDiscard, onNavigate } = props; + const { draftId, onContextMenu, onDiscard, onNavigate } = props; + const composer = props.composer ?? EMPTY_COMPOSER_PARTS; const gt = useGT(); const promptPreview = assistantCitationsToPlainText( @@ -65,9 +100,11 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { const preview = promptPreview.length > 0 ? promptPreview - : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { - count: attachmentCount, - }); + : attachmentCount === 0 && props.terminalLabel !== null + ? props.terminalLabel + : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { + count: attachmentCount, + }); const accessibility = resolveSidebarRowAccessibility({ title: preview, statusLabel: gt("Unsent draft"), @@ -174,6 +211,7 @@ function listedDraftComposer(draftId: string | null): ComposerThreadDraftState | export function useSidebarDrafts( scopedProjectKeys: ReadonlySet | null, routeDraftId: string | null, + terminalLabels: ReadonlyMap, ): { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null } { const [frozenRoute, setFrozenRoute] = useState<{ routeDraftId: string | null; @@ -195,10 +233,12 @@ export function useSidebarDrafts( ) { continue; } + // Composer edits stay frozen while open; terminals come and go live. const isListed = - draftKey === routeDraftId + draftTerminalLabel(session, terminalLabels) !== null || + (draftKey === routeDraftId ? routeDraftComposer !== null - : composerDraftHasUserContent(store.draftsByThreadKey[draftKey]); + : composerDraftHasUserContent(store.draftsByThreadKey[draftKey])); if (isListed) listed.push([draftKey, session]); } listed.sort(([, left], [, right]) => right.createdAt.localeCompare(left.createdAt)); @@ -211,6 +251,7 @@ export function useSidebarDrafts( export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null; + terminalLabels: ReadonlyMap; jumpLabelByDraftId: ReadonlyMap | null; projectByKey: ReadonlyMap; projectDisplayNameByKey: ReadonlyMap; @@ -233,8 +274,10 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { const drafts = props.draftIds.flatMap((draftId) => { const session = draftThreadsByThreadKey[draftId]; const composer = - draftId === props.routeDraftId ? props.routeDraftComposer : draftsByThreadKey[draftId]; - return session && composer ? [{ draftId, session, composer }] : []; + (draftId === props.routeDraftId ? props.routeDraftComposer : null) ?? + draftsByThreadKey[draftId] ?? + null; + return session ? [{ draftId, session, composer }] : []; }); if (drafts.length === 0) { return null; @@ -248,6 +291,7 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { key={draftId} draftId={draftId} composer={composer} + terminalLabel={draftTerminalLabel(session, props.terminalLabels)} project={props.projectByKey.get(projectKey) ?? null} projectDisplayName={props.projectDisplayNameByKey.get(projectKey) ?? null} isActive={draftId === props.routeDraftId} diff --git a/apps/web/src/lib/discardComposerDraft.test.ts b/apps/web/src/lib/discardComposerDraft.test.ts index 6c63482dfe52b..340ed6b2606e3 100644 --- a/apps/web/src/lib/discardComposerDraft.test.ts +++ b/apps/web/src/lib/discardComposerDraft.test.ts @@ -80,6 +80,23 @@ describe("discardComposerDraft", () => { } }); + it("discards and restores a draft session that has no composer record", async () => { + useComposerDraftStore.getState().setProjectDraftThreadId(projectRef, draftId); + const before = useComposerDraftStore.getState(); + expect(before.draftsByThreadKey).toEqual({}); + + discardComposerDraft(draftId); + expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull(); + + await undoNotice().undo(); + const after = useComposerDraftStore.getState(); + expect(after.getDraftSession(draftId)).toEqual(before.getDraftSession(draftId)); + expect(after.draftsByThreadKey).toEqual({}); + expect(after.logicalProjectDraftThreadKeyByLogicalProjectKey).toEqual( + before.logicalProjectDraftThreadKeyByLogicalProjectKey, + ); + }); + it("releases a discarded existing-thread preview when Undo is committed", async () => { using preview = imagePreview(); useComposerDraftStore.getState().addImage(threadRef, preview.image); diff --git a/apps/web/src/lib/discardComposerDraft.ts b/apps/web/src/lib/discardComposerDraft.ts index bd52b0a02879f..f1847a737dc0a 100644 --- a/apps/web/src/lib/discardComposerDraft.ts +++ b/apps/web/src/lib/discardComposerDraft.ts @@ -19,8 +19,9 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { const store = useComposerDraftStore.getState(); const key = resolveComposerDraftKey(store, target); const draft = key === null ? undefined : store.draftsByThreadKey[key]; - if (key === null || !draft) return; + if (key === null) return; const session = store.draftThreadsByThreadKey[key]; + if (!draft && !session) return; const logicalProjectKeys = Object.entries(store.logicalProjectDraftThreadKeyByLogicalProjectKey) .filter(([, draftKey]) => draftKey === key) .map(([logicalProjectKey]) => logicalProjectKey); @@ -38,6 +39,7 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { } const releaseDiscardedDraft = () => { + if (!draft) return; releaseDraftAttachments([...draft.images, ...draft.files]); // Draft-session removal already revoked these previews. if (!discardsSession) { @@ -65,19 +67,21 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { logicalProjectDraftThreadKeyByLogicalProjectKey[logicalProjectKey] ??= key; } return { - draftsByThreadKey: { - ...state.draftsByThreadKey, - [key]: discardsSession - ? { - ...draft, - images: draft.images.map((image) => - image.previewUrl.startsWith("blob:") - ? { ...image, previewUrl: URL.createObjectURL(image.file) } - : image, - ), - } - : draft, - }, + draftsByThreadKey: draft + ? { + ...state.draftsByThreadKey, + [key]: discardsSession + ? { + ...draft, + images: draft.images.map((image) => + image.previewUrl.startsWith("blob:") + ? { ...image, previewUrl: URL.createObjectURL(image.file) } + : image, + ), + } + : draft, + } + : state.draftsByThreadKey, draftThreadsByThreadKey: session ? { ...state.draftThreadsByThreadKey, [key]: session } : state.draftThreadsByThreadKey, diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index 8eaca1b774c85..0915810b47fed 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -22,7 +22,13 @@ import { AsyncResult, Atom } from "effect/reactivity"; import { formatEnvironmentQueryError } from "./query"; import { terminalEnvironment } from "./terminal"; -import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session"; +import { environmentAtomList, environmentIdsKey } from "./environmentAtomList"; +import { + environmentSession, + sessionHasScope, + useEnvironmentScope, + useEnvironmentsWithScope, +} from "./session"; import { msg } from "gt-react"; import { m } from "../i18n/messages"; @@ -274,3 +280,43 @@ export function useThreadRunningTerminalIds(input: { const sessions = useKnownTerminalSessions(input); return selectRunningSubprocessTerminalIds(sessions ?? []); } + +// A string so status updates that keep every label notify no one. +const terminalLabelsFamily = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + const metadata = get(terminalEnvironment.metadata({ environmentId, input: null })); + if (metadata._tag !== "Success") return "[]"; + return JSON.stringify( + Array.from(terminalMetadataIndex(metadata.value).byThreadId, ([threadId, summaries]) => [ + threadId, + summaries[0]!.label, + ]), + ); + }).pipe(Atom.withLabel(`web-terminal-labels:${environmentId}`)), +); +const terminalLabelsListAtom = environmentAtomList("web-terminal-labels", terminalLabelsFamily); +const terminalLabelsByResults = new WeakMap, ReadonlyMap>(); + +/** First terminal label of each thread that has one, keyed `${environmentId}:${threadId}`. */ +export function useTerminalLabelsByThreadKey( + environmentIds: ReadonlyArray, +): ReadonlyMap { + const readable = useEnvironmentsWithScope( + environmentIds.map((environmentId) => ({ environmentId })), + AuthTerminalReadScope, + ); + const readableIds = environmentIds.filter((environmentId) => readable.has(environmentId)); + const results = useAtomValue(terminalLabelsListAtom(environmentIdsKey(readableIds))); + let labels = terminalLabelsByResults.get(results); + if (!labels) { + const next = new Map(); + results.forEach((encoded, index) => { + for (const [threadId, label] of JSON.parse(encoded) as Array<[string, string]>) { + next.set(`${readableIds[index]}:${threadId}`, label); + } + }); + labels = next; + terminalLabelsByResults.set(results, labels); + } + return labels; +} From b23f1e8af9b13af2c4aa1ba8e0d6987550688645 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:21:55 -0800 Subject: [PATCH 069/162] fix(server): retire unresponsive shared Codex app-servers (#25123) --- .../Adapters/CodexAdapterV2.test.ts | 174 ++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 82 +++++++-- .../ProviderTurnStartService.test.ts | 34 ++++ .../ProviderTurnStartService.ts | 18 +- .../provider-core/src/server/failure.test.ts | 10 + packages/provider-core/src/server/failure.ts | 2 + 6 files changed, 299 insertions(+), 21 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index cd5e51a32f616..ef4ffcf35c11b 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1235,6 +1235,7 @@ describe("CodexAdapterV2 session initialize", () => { runtimePolicy: CODEX_TEST_RUNTIME_POLICY, }), initializeRequests: () => initializeRequests, + runtime, events: runtime.events, }; }); @@ -1531,6 +1532,179 @@ describe("CodexAdapterV2 session initialize", () => { ), ), ); + + // The no-op notification lands right after the request is written, so the + // test advances the clock only once the app-server is known to be silent. + const requestWritten: CodexReplay.CodexAppServerReplayEntry = { + type: "emit_inbound", + label: "request-written", + frame: { method: "t3/test/requestWritten", params: {} }, + }; + const awaitRequestWritten = + (written: Deferred.Deferred) => + ( + entry: Parameters< + NonNullable + >[0], + ) => + entry.label === "request-written" ? Deferred.succeed(written, undefined) : Effect.void; + const UNANSWERED_REQUEST_BUDGET = "5 minutes"; + // ProviderTurnStartService skips retries and fresh-thread fallback on this tag. + const failedOnDeadline = (exit: Exit.Exit): boolean => { + if (!Exit.isFailure(exit)) return false; + let error: unknown = Cause.squash(exit.cause); + while (Predicate.hasProperty(error, "cause")) { + if (Predicate.isTagged(error, "CodexAppServerUnresponsiveError")) return true; + error = error.cause; + } + return Predicate.isTagged(error, "CodexAppServerUnresponsiveError"); + }; + + // regression: #24300 a wedged shared app-server left thread/start pending and stayed ready + it.effect("fails and retires a shared app-server that never answers thread/start", () => + Effect.gen(function* () { + const written = yield* Deferred.make(); + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: "thread-start-unanswered", + entries: [...replayPreamble("thread-start-unanswered").slice(0, 4), requestWritten], + }), + awaitRequestWritten(written), + ); + const events = yield* session.runtime.events.pipe( + Stream.runDrain, + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + const ensured = yield* session + .ensureThread("thread-start-unanswered") + .pipe( + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.await(written); + yield* TestClock.adjust(UNANSWERED_REQUEST_BUDGET); + + const settled = yield* Fiber.join(ensured); + assert.isTrue( + Option.isSome(settled) && failedOnDeadline(settled.value), + `ensureThread did not fail on the deadline within ${UNANSWERED_REQUEST_BUDGET} of an unanswered thread/start`, + ); + const retired = yield* Fiber.join(events); + assert.isTrue( + Option.isSome(retired) && Exit.isFailure(retired.value), + "session events did not fail after thread/start passed its deadline", + ); + const refused = yield* Effect.exit(session.ensureThread("thread-start-after-retire")); + const refusal = Exit.isFailure(refused) ? Cause.squash(refused.cause) : undefined; + assert.isTrue( + Predicate.hasProperty(refusal, "cause") && + Predicate.isTagged(refusal.cause, "CodexAppServerRetiredError"), + "a retired app-server accepted a new thread", + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + const turnPreamble = codexReplayPreamble({ + nativeThreadId: "turn-start-unanswered", + nativeTurnId: "turn-unanswered", + prompt: "Hello", + }); + // regression: #24300 a stopped shared app-server left a loaded thread's next turn pending forever + it.effect.each([ + { + method: "config/read", + entries: [ + ...turnPreamble.slice(0, 5), + { + type: "expect_outbound", + label: "thread/name/set", + frame: { + id: 3, + method: "thread/name/set", + params: { threadId: "turn-start-unanswered", name: CODEX_TEST_THREAD_TITLE }, + }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + { + type: "emit_inbound", + label: "thread/name/set", + frame: { id: 3, result: {} }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + { + type: "expect_outbound", + label: "config/read", + frame: { + id: 4, + method: "config/read", + params: { cwd: "/workspace", includeLayers: false }, + }, + } satisfies CodexReplay.CodexAppServerReplayEntry, + ], + }, + { method: "turn/start", entries: turnPreamble.slice(0, 6) }, + ])("fails a turn whose $method the shared app-server never answers", ({ entries }) => + Effect.gen(function* () { + const written = yield* Deferred.make(); + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: "turn-start-unanswered", + entries: [...entries, requestWritten], + }), + awaitRequestWritten(written), + ); + const threadId = ThreadId.make("thread-turn-start-unanswered"); + const providerThread = yield* session.ensureThread(threadId); + + const outcome = yield* session.runtime + .startTurn( + makeCodexTestTurnInput({ + threadId, + providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("turn-start-unanswered-attempt"), + text: "Hello", + }), + ) + .pipe( + Effect.exit, + Effect.timeoutOption(UNANSWERED_REQUEST_BUDGET), + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.await(written); + yield* TestClock.adjust(UNANSWERED_REQUEST_BUDGET); + const settled = yield* Fiber.join(outcome); + + assert.isTrue( + Option.isSome(settled), + `startTurn was still waiting after ${UNANSWERED_REQUEST_BUDGET}`, + ); + if (Option.isSome(settled)) { + assert.isTrue(failedOnDeadline(settled.value), "startTurn did not fail on the deadline"); + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); }); describe("CodexAdapterV2 post-settle continuation", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 09036b09e3f77..e5dfd83559292 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -541,6 +541,26 @@ function codexMcpToolOutput( // A hung MCP resource read must not hold run ingestion open. const MCP_APP_CAPTURE_TIMEOUT = "20 seconds"; +// Session setup and turn start requests answer promptly; silence this long means a wedged app-server. +const CODEX_APP_SERVER_REQUEST_DEADLINE = "2 minutes"; + +class CodexAppServerUnresponsiveError extends Schema.TaggedError()( + "CodexAppServerUnresponsiveError", + { method: Schema.String }, +) { + override get message() { + return `Codex app-server did not answer ${this.method} within ${CODEX_APP_SERVER_REQUEST_DEADLINE}.`; + } +} + +class CodexAppServerRetiredError extends Schema.TaggedError()( + "CodexAppServerRetiredError", + {}, +) { + override get message() { + return "Codex app-server was retired and accepts no new work."; + } +} function codexMcpAppResourceUri(item: CodexDynamicToolItem): string | undefined { if (item.type !== "mcpToolCall") return undefined; @@ -2140,6 +2160,39 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); // A failed open is discarded, so the next turn spawns the updated binary. if (adapterOptions.compatibility !== undefined) yield* ensureInitialized; + // Failing the event stream makes the session manager release this app-server. + // Queue.fail lets readers take items already buffered before they see the failure. + // Buffered events drain before the session manager drops this runtime; refuse work meanwhile. + let retired = false; + const retireAppServer = (cause: unknown) => + Effect.suspend(() => { + retired = true; + return Queue.fail( + events, + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: CODEX_PROVIDER, + providerSessionId: input.providerSessionId, + cause, + }), + ); + }); + const rejectIfRetired = Effect.suspend(() => + retired ? Effect.fail(new CodexAppServerRetiredError()) : Effect.void, + ); + yield* client.awaitTermination.pipe(Effect.catch(retireAppServer), Effect.forkScoped); + // The outcome of an unanswered request is unknown, so it fails rather than retries. + const withAppServerDeadline = + (method: string) => + (effect: Effect.Effect) => + effect.pipe( + Effect.timeoutOrElse({ + duration: CODEX_APP_SERVER_REQUEST_DEADLINE, + orElse: () => { + const error = new CodexAppServerUnresponsiveError({ method }); + return retireAppServer(error).pipe(Effect.andThen(Effect.fail(error))); + }, + }), + ); // Read per thread: a workspace's project config can add its own servers. const readStdioMcpServers = (cwd: string | null | undefined) => ensureInitialized.pipe( @@ -2155,6 +2208,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.as>([]), ), ), + withAppServerDeadline("config/read"), ); const now = yield* DateTime.now; const session = providerSession({ @@ -2164,21 +2218,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( model: input.modelSelection.model, now, }); - // Drain final notifications before the session manager retires the dead process. - // Queue.fail lets readers take items already buffered before they see the failure. - yield* client.awaitTermination.pipe( - Effect.catch((cause) => - Queue.fail( - events, - new ProviderAdapter.ProviderAdapterEventStreamError({ - driver: CODEX_PROVIDER, - providerSessionId: input.providerSessionId, - cause, - }), - ), - ), - Effect.forkScoped, - ); const rateLimitSnapshot = yield* Ref.make(undefined); const limitedTurnItems = yield* Ref.make( new Map>(), @@ -7677,6 +7716,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.catch(() => Effect.logDebug("Codex config read failed.").pipe(Effect.as(undefined)), ), + withAppServerDeadline("config/read"), ); const turnStartParams = yield* buildCodexTurnStartParams({ cyberAccess: codexCyberAccess(models, turnInput.modelSelection.model), @@ -7708,7 +7748,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(yield* Ref.get(settledTurns)), ...(yield* Ref.get(activeTurns)), ]); - const started = yield* client.request("turn/start", turnStartParams); + const started = yield* client + .request("turn/start", turnStartParams) + .pipe(withAppServerDeadline("turn/start")); const previousTurn = previousTurns.get(started.turn.id) ?? (yield* Ref.get(activeTurns)).get(started.turn.id); @@ -7798,6 +7840,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, command: OrchestrationV2GoalCommand, ) { + yield* rejectIfRetired; if (command.type === "set") yield* validateCodexGoalObjective(command.objective); const threadId = yield* getNativeThreadId(turnInput.providerThread); rootProviderThreads.set(threadId, turnInput.providerThread); @@ -8075,7 +8118,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( return false; }), ensureThread: (threadInput) => - ensureInitialized.pipe( + rejectIfRetired.pipe( + Effect.andThen(ensureInitialized), Effect.andThen( Effect.all([ mcpSessions.read(threadInput.threadId), @@ -8107,6 +8151,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( thread: response.thread, }), ), + withAppServerDeadline("thread/start"), Effect.mapError( (cause) => new ProviderAdapter.ProviderAdapterEnsureThreadError({ @@ -8118,6 +8163,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), resumeThread: Effect.fn("CodexAdapterV2.resumeThread")( function* (threadInput) { + yield* rejectIfRetired; const nativeThreadId = yield* getNativeThreadId(threadInput.providerThread); const appThreadId = threadInput.threadId ?? threadInput.providerThread.appThreadId; const resume = resumeNativeThread(nativeThreadId, { @@ -8140,6 +8186,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( goalUpdatesHeld.add(nativeThreadId); const response = yield* ensureInitialized.pipe( Effect.andThen(resume), + withAppServerDeadline("thread/resume"), Effect.flatMap(decodeCodexResumeMetadata), // Stay registered: a lost or undecodable response may still have resumed the thread. Effect.onError(() => @@ -8252,6 +8299,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (goalCommand !== null) return runGoalCommand(turnInput, goalCommand); const nativeThreadId = turnInput.providerThread.nativeThreadRef?.nativeId; return Effect.gen(function* () { + yield* rejectIfRetired; if ( !continuation && nativeThreadId != null && diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 864d6f253ad41..ef9bd2bb32712 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -3163,6 +3163,40 @@ effectIt.effect("leaves the run starting when a session-open failure will be ret }), ); +effectIt.effect("fails rather than retries a provider thread request with an unknown outcome", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + ensureThreadFailure: { _tag: "CodexAppServerUnresponsiveError", method: "thread/start" }, + }); + + yield* harness.startWithRetry; + + expect(harness.startRootRun).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("failed"); + }), +); + +effectIt.effect("fails rather than starts a fresh thread when a resume outcome is unknown", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + resumeFailure: new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: ProviderDriverKind.make("codex"), + providerSessionId: ProviderSessionId.make("resume-provider-session"), + cause: { _tag: "CodexAppServerUnresponsiveError", method: "thread/resume" }, + }), + }); + + const exit = yield* Effect.exit(harness.startWithRetry); + + expect(exit._tag).toBe("Success"); + expect(harness.fallbackEnsureThread).not.toHaveBeenCalled(); + expect(harness.startRootRun).not.toHaveBeenCalled(); + expect(harness.projection().runs.at(-1)?.status).toBe("failed"); + }), +); + effectIt.effect("fails the run without a retry when the provider needs sign-in", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 317dff4b395b6..1cb77e387f950 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -165,6 +165,13 @@ const refusedBeforePrompt = (error: unknown): boolean => error.detail === CLAUDE_QUERY_ENDED_BEFORE_TURN_DETAIL) || (Predicate.hasProperty(error, "cause") && refusedBeforePrompt(error.cause)); +// The provider may have acted on a request it never answered, so a retry could duplicate it. +const OUTCOME_UNKNOWN_TAGS = ["CodexAppServerUnresponsiveError"] as const; + +const outcomeUnknown = (error: unknown): boolean => + OUTCOME_UNKNOWN_TAGS.some((tag) => Predicate.isTagged(error, tag)) || + (Predicate.hasProperty(error, "cause") && outcomeUnknown(error.cause)); + /** * Whether a non-truncating provider's native session lost the conversation kept before `run`. * Rollback resets it: the newest accepted turn was rolled back (works without legacy-missing @@ -998,7 +1005,9 @@ export const layer: Layer.Layer< ) { const loaded = yield* Effect.result(load); if (loaded._tag === "Success") return loaded.success; - if (input.willRetry === true) return yield* loaded.failure; + if (input.willRetry === true && !outcomeUnknown(loaded.failure)) { + return yield* loaded.failure; + } yield* settleStartFailure({ signal: "provider-thread-load-failure", title: "Provider turn failed to start", @@ -1718,11 +1727,12 @@ export const layer: Layer.Layer< resumedHandoffContext = undefined; resumedRetryHandoff = undefined; if (!(yield* isCurrentAttemptInStatus("starting"))) return undefined; - // Another client is still writing to the native thread. A fresh - // session here would silently split the conversation from it. + // Another client is still writing to the native thread, or the provider may have + // resumed it without answering. A fresh session would split the conversation. if ( resumed._tag === "Failure" && - resumed.failure._tag === "ProviderAdapterThreadInUseError" + (resumed.failure._tag === "ProviderAdapterThreadInUseError" || + outcomeUnknown(resumed.failure)) ) { return yield* loadFromProvider(Effect.fail(resumed.failure)); } diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index a29b60d4d25ae..7f4b790927488 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -132,6 +132,16 @@ it("preserves actionable T3 errors wrapped by turn startup", () => { }); assert.equal(makeProviderFailure({ cause: Cause.fail(cause) }).message, error.message); } + const unanswered = { + _tag: "CodexAppServerUnresponsiveError", + message: "Codex app-server did not answer turn/start within 2 minutes.", + }; + assert.equal( + makeProviderFailure({ + cause: Cause.fail({ _tag: "ProviderAdapterEventStreamError", cause: unanswered }), + }).message, + unanswered.message, + ); }); it("names how the provider process exited and the stage it failed in, without its output", () => { diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index cfdb0eb3df9a6..e7d47cdb2175e 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -139,6 +139,8 @@ function curatedCauseMessages(cause: unknown): { case "ClaudeConversationNotFoundError": case "CursorModelUnavailableError": case "CodexGoalObjectiveTooLongError": + case "CodexAppServerUnresponsiveError": + case "CodexAppServerRetiredError": case "ProviderSetupError": case "ProviderAdapterThreadInUseError": case "ProviderCompactionUnsupportedError": From a985332c447173750394c0875fb961f88c306730 Mon Sep 17 00:00:00 2001 From: maria Date: Sun, 22 Nov 2026 10:28:38 -0300 Subject: [PATCH 070/162] fix(shared): Windows command discovery no longer blocks the event loop (#27391) Co-authored-by: Enmani <43571965+Enmani@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.testkit.ts | 4 +- .../provider/Drivers/ClaudeExecutable.test.ts | 2 +- .../src/provider/Drivers/ClaudeExecutable.ts | 4 +- apps/server/src/terminal/Manager.ts | 11 +-- .../src/server/AcpRegistrySupport.test.ts | 11 ++- .../src/server/AcpRegistrySupport.ts | 57 ++++++++----- .../src/server/clientTerminals.ts | 2 +- .../provider-muse/src/server/MuseUsageHome.ts | 6 +- packages/provider-muse/src/server/sdk.test.ts | 2 +- packages/provider-muse/src/server/sdk.ts | 3 +- .../provider-muse/src/server/usage.test.ts | 2 +- packages/shared/src/shell.test.ts | 85 +++++++++++++++++-- packages/shared/src/shell.ts | 77 +++++++++-------- .../src/server/AzureDevOpsCli.test.ts | 2 +- .../src/server/AzureDevOpsCli.ts | 3 +- .../src/server/discovery.ts | 3 +- 16 files changed, 190 insertions(+), 84 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index bed26e69ae008..5d08adab93042 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -1496,7 +1496,9 @@ const resolveClaudeRecordingExecutablePath = Effect.fn("resolveClaudeRecordingEx function* (environment: NodeJS.ProcessEnv) { const resolveExecutable = yield* SpawnExecutableResolution; const platform = yield* HostProcess.Platform; - const resolved = resolveExecutable("claude", platform, environment); + const resolved = yield* Effect.promise(async () => + resolveExecutable("claude", platform, environment), + ); if (resolved === undefined) { return undefined; } diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts index b6dc61470e497..36d7e3f3313fc 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts @@ -21,7 +21,7 @@ function withWindowsResolution(input: { return (effect: Effect.Effect) => effect.pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => input.resolvedCommand), + Effect.provideService(SpawnExecutableResolution, async () => input.resolvedCommand), Effect.provideService(ClaudeExecutableFileCheck, (filePath) => existing.has(filePath)), ); } diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.ts index 5797066446b99..6f4e85812f0cc 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.ts @@ -50,7 +50,9 @@ export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecuta const resolveExecutable = yield* SpawnExecutableResolution; const isFile = yield* ClaudeExecutableFileCheck; - const resolved = resolveExecutable(binaryPath, platform, environment) ?? binaryPath; + const resolved = + (yield* Effect.promise(async () => resolveExecutable(binaryPath, platform, environment))) ?? + binaryPath; const extension = NodePath.win32.extname(resolved).toLowerCase(); if (!WINDOWS_SHIM_EXTENSIONS.has(extension)) { return resolved; diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index fb19b6c7ad1d6..e87ba67cf5837 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -2791,15 +2791,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func .join(":"), }; // POSIX node-pty can return a PTY before exec fails, so validate before accepting a candidate. + const shellCommand = candidate.shell.includes("/") + ? path.resolve(session.cwd, candidate.shell) + : candidate.shell; const executable = platform !== "win32" - ? resolveExecutable( - candidate.shell.includes("/") - ? path.resolve(session.cwd, candidate.shell) - : candidate.shell, - platform, - lookupEnv, - ) + ? yield* Effect.promise(async () => resolveExecutable(shellCommand, platform, lookupEnv)) : candidate.shell; if (executable === undefined) { return yield* trySpawn( diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 398c48be3f68c..75311d6598b7e 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -318,7 +318,7 @@ describe("AcpRegistrySupport", () => { registryUrl, }).pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => `C:\\bin\\dsh${extension}`), + Effect.provideService(SpawnExecutableResolution, async () => `C:\\bin\\dsh${extension}`), ); const localSettings = decodeAcpRegistrySettings({ source: "local", commandPath: "dsh" }); for (const failure of [ @@ -1206,6 +1206,7 @@ describe("AcpRegistrySupport", () => { name: "Codex Darwin", } satisfies AcpRegistrySupport.AcpRegistryAgent; + const lookups: string[] = []; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ @@ -1215,9 +1216,15 @@ describe("AcpRegistrySupport", () => { cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, - }); + }).pipe( + Effect.provideService(SpawnExecutableResolution, async (command) => { + lookups.push(command); + return "/bin/npm"; + }), + ); const result = yield* resolver.search({ query: "codex" }); + expect(lookups).toEqual(["npm"]); expect(result.agents.map((agent) => agent.id)).toEqual(["codex-acp", "other-agent"]); expect(result.agents[0]).toMatchObject({ authors: ["OpenAI", "Zed Industries"], diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index d3ab397d7aaeb..26d58fb4ea9ad 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -673,7 +673,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; const hostEnvironment = yield* HostProcess.Environment; - const resolveExecutable = yield* SpawnExecutableResolution; + const executableResolver = yield* SpawnExecutableResolution; + const resolveExecutable = Effect.fn("AcpRegistryCatalog.resolveExecutable")(function* ( + command: string, + environment: NodeJS.ProcessEnv, + ) { + return yield* Effect.promise(async () => executableResolver(command, platform, environment)); + }); const platformTarget = resolveAcpRegistryPlatformTarget(platform, architecture); const registryUrl = input.registryUrl ?? ACP_REGISTRY_URL; const registryDirectory = path.join(input.cacheDir, "acp-registry"); @@ -1240,9 +1246,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const commandName = npmCommandName(agent, packageIdentity.name, manifest.value); if (commandName === undefined) return Option.none(); const binDirectory = platform === "win32" ? globalPrefix : path.join(globalPrefix, "bin"); - const executablePath = resolveExecutable( + const executablePath = yield* resolveExecutable( path.join(binDirectory, commandName), - platform, environment, ); return executablePath === undefined @@ -1289,9 +1294,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct truncatedOutputReason: "install_failed", }).pipe(Effect.flatMap((output) => parsePackageManagerPath(managerPath, output))); const managedBinEnvironment = { ...environment, PATH: binDirectory }; - const executablePath = packageCommandCandidates(agent, packageIdentity.name) - .map((candidate) => resolveExecutable(candidate, platform, managedBinEnvironment)) - .find((candidate): candidate is string => candidate !== undefined); + let executablePath: string | undefined; + for (const candidate of packageCommandCandidates(agent, packageIdentity.name)) { + executablePath = yield* resolveExecutable(candidate, managedBinEnvironment); + if (executablePath !== undefined) break; + } return executablePath === undefined ? Option.none() : Option.some({ @@ -1314,7 +1321,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct environment: NodeJS.ProcessEnv, ) { const managerName = packageManagerFor(distribution)!; - const managerPath = resolveExecutable(managerName, platform, environment); + const managerPath = yield* resolveExecutable(managerName, environment); if (managerPath === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", @@ -1740,22 +1747,27 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const search: AcpRegistryCatalog["Service"]["search"] = Effect.fn("AcpRegistryCatalog.search")( function* (input) { const registry = yield* recentRegistry(); - const ranked = registry.agents.flatMap((agent) => { + const ranked = []; + const managerAvailability = new Map(); + for (const agent of registry.agents) { const distribution = resolveAcpRegistryDistribution({ agent, preference: "auto", platformTarget, }); const rank = searchRank(agent, input.query); - const packageManager = - distribution === undefined ? undefined : packageManagerFor(distribution.kind); - const packageManagerAvailable = - packageManager === undefined || - resolveExecutable(packageManager, platform, hostEnvironment) !== undefined; - return distribution === undefined || rank === undefined || !packageManagerAvailable - ? [] - : [{ agent, distribution, rank }]; - }); + if (distribution === undefined || rank === undefined) continue; + const packageManager = packageManagerFor(distribution.kind); + if (packageManager !== undefined) { + let available = managerAvailability.get(packageManager); + if (available === undefined) { + available = (yield* resolveExecutable(packageManager, hostEnvironment)) !== undefined; + managerAvailability.set(packageManager, available); + } + if (!available) continue; + } + ranked.push({ agent, distribution, rank }); + } ranked.sort( (left, right) => left.rank - right.rank || @@ -1826,7 +1838,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (settings.source === "local") { const command = settings.commandPath.trim(); if (!command) return { status: "unconfigured" } as const; - const executable = resolveExecutable(command, platform, environment ?? hostEnvironment); + const executable = yield* resolveExecutable(command, environment ?? hostEnvironment); if (executable !== undefined) yield* validateLocalExecutable(executable); return executable === undefined ? ({ @@ -1854,8 +1866,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const commandOverride = settings.commandPath.trim(); if (commandOverride.length > 0) { const available = - resolveExecutable(commandOverride, platform, environment ?? hostEnvironment) !== - undefined; + (yield* resolveExecutable(commandOverride, environment ?? hostEnvironment)) !== undefined; return available ? ({ status: "ready", @@ -1919,7 +1930,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const runner = packageManagerFor(distribution.kind)!; const available = - resolveExecutable(runner, platform, environment ?? hostEnvironment) !== undefined; + (yield* resolveExecutable(runner, environment ?? hostEnvironment)) !== undefined; return available ? ({ status: "ready", @@ -1960,7 +1971,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const effectiveEnvironment = environment ?? hostEnvironment; const commandOverride = settings.commandPath.trim(); if (commandOverride.length > 0) { - const resolvedOverride = resolveExecutable(commandOverride, platform, effectiveEnvironment); + const resolvedOverride = yield* resolveExecutable(commandOverride, effectiveEnvironment); if (resolvedOverride === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", @@ -2028,7 +2039,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } const env = environment ?? hostEnvironment; - const command = resolveExecutable(executable, platform, env); + const command = yield* resolveExecutable(executable, env); if (command === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index c8371fb7020e8..592bf47553494 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -263,7 +263,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi // Agents that send shell source write bash; Node's shell on Windows is cmd.exe. const gitExecutable = isWindows && options.shellCommands === true - ? resolveExecutable("git", "win32", environment) + ? yield* Effect.promise(async () => resolveExecutable("git", "win32", environment)) : undefined; const posixShell = gitExecutable === undefined ? undefined : gitForWindowsBash(gitExecutable); diff --git a/packages/provider-muse/src/server/MuseUsageHome.ts b/packages/provider-muse/src/server/MuseUsageHome.ts index 1ced0d2578b01..329dce90c0e7b 100644 --- a/packages/provider-muse/src/server/MuseUsageHome.ts +++ b/packages/provider-muse/src/server/MuseUsageHome.ts @@ -66,7 +66,11 @@ const make = Effect.gen(function* () { if (Option.isSome(settled)) return settled; // Spawn failures surface asynchronously; without this a missing CLI would report as pending. const resolveExecutable = yield* SpawnExecutableResolution; - if (resolveExecutable(binaryPath, yield* HostProcess.Platform, environment) === undefined) { + const platform = yield* HostProcess.Platform; + const resolved = yield* Effect.promise(async () => + resolveExecutable(binaryPath, platform, environment), + ); + if (resolved === undefined) { return Option.some(undefined); } if (awaitRefresh) return Option.some(yield* Cache.get(cache, key)); diff --git a/packages/provider-muse/src/server/sdk.test.ts b/packages/provider-muse/src/server/sdk.test.ts index 45ef56cb63458..6607640751092 100644 --- a/packages/provider-muse/src/server/sdk.test.ts +++ b/packages/provider-muse/src/server/sdk.test.ts @@ -263,7 +263,7 @@ describe("Muse launch", () => { const onWindows = (resolved: string | undefined, env: NodeJS.ProcessEnv = { ComSpec: CMD }) => museLaunch("muse", env).pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => resolved), + Effect.provideService(SpawnExecutableResolution, async () => resolved), ); it.effect("runs an exe directly and a launcher script under cmd.exe on Windows", () => diff --git a/packages/provider-muse/src/server/sdk.ts b/packages/provider-muse/src/server/sdk.ts index 6d6b4d5d51050..aece589b1e188 100644 --- a/packages/provider-muse/src/server/sdk.ts +++ b/packages/provider-muse/src/server/sdk.ts @@ -117,7 +117,8 @@ export const museLaunch = Effect.fn("museLaunch")(function* ( if ((yield* HostProcess.Platform) !== "win32") return { command: binaryPath, args: [] }; const env = environment ?? (yield* HostProcess.Environment); const resolveExecutable = yield* SpawnExecutableResolution; - const resolved = resolveExecutable(binaryPath, "win32", env) ?? binaryPath; + const resolved = + (yield* Effect.promise(async () => resolveExecutable(binaryPath, "win32", env))) ?? binaryPath; if (!/\.(?:cmd|bat)$/i.test(resolved)) return { command: resolved, args: [] }; const systemRoot = windowsEnvironmentValue(env, "SystemRoot"); return { diff --git a/packages/provider-muse/src/server/usage.test.ts b/packages/provider-muse/src/server/usage.test.ts index 3815cfce44321..d02271f44ff04 100644 --- a/packages/provider-muse/src/server/usage.test.ts +++ b/packages/provider-muse/src/server/usage.test.ts @@ -260,7 +260,7 @@ describe("Muse history discovery", () => { expect(create).not.toHaveBeenCalled(); }).pipe( Effect.provide([NodeServices.layer, MuseUsageHome.layer]), - Effect.provideService(SpawnExecutableResolution, () => undefined), + Effect.provideService(SpawnExecutableResolution, async () => undefined), ), ); diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 08731a41c19ef..8f81723486f55 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -577,7 +577,9 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ), ).toBe(path.join(directory, "audit-command")); const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("audit-command", "linux", env)).toBe(executable); + expect( + yield* Effect.promise(async () => resolveExecutable("audit-command", "linux", env)), + ).toBe(executable); }), ); @@ -736,7 +738,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { // A POSIX directory joined with win32 separators names nothing, so this needs a Windows host. it.effect.skipIf(HostProcess.Platform.defaultValue() !== "win32")( - "relists a changed PATH directory in the synchronous spawn resolver", + "relists a changed PATH directory in the spawn resolver", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -746,11 +748,17 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { yield* fs.utimes(directory, 946_684_800, 946_684_800); const env = { PATH: directory, PATHEXT: ".EXE;.CMD" }; const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("cursor", "win32", env)).toBe(path.join(directory, "cursor.CMD")); - expect(resolveExecutable("late", "win32", env)).toBeUndefined(); + expect(yield* Effect.promise(async () => resolveExecutable("cursor", "win32", env))).toBe( + path.join(directory, "cursor.CMD"), + ); + expect( + yield* Effect.promise(async () => resolveExecutable("late", "win32", env)), + ).toBeUndefined(); yield* fs.writeFileString(path.join(directory, "late.EXE"), ""); yield* fs.utimes(directory, 946_684_830, 946_684_830); - expect(resolveExecutable("late", "win32", env)).toBe(path.join(directory, "late.EXE")); + expect(yield* Effect.promise(async () => resolveExecutable("late", "win32", env))).toBe( + path.join(directory, "late.EXE"), + ); }), ); }); @@ -975,6 +983,73 @@ describe("npmShimExecutable", () => { }); effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { + it.effect("yields while discovering a Windows executable", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const executable = path.join(directory, "tool.EXE"); + yield* fs.writeFileString(executable, ""); + let settled = false; + const pending = Promise.resolve( + SpawnExecutableResolution.defaultValue()(executable, "win32", { PATHEXT: ".EXE;.CMD" }), + ).then((value) => { + settled = true; + return value; + }); + try { + yield* Effect.promise(() => Promise.resolve()); + expect(settled).toBe(false); + } finally { + expect(yield* Effect.promise(() => pending)).toBe(executable); + } + }), + ), + ); + + it.effect("preserves PATH and PATHEXT order and discovers executables after a miss", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const fixture = NodePath.join(directory, "tool.EXE"); + yield* fs.writeFileString(fixture, ""); + const stat = yield* Effect.promise(() => NodeFS.promises.stat(fixture)); + const files = new Set(); + using _stat = vi.spyOn(NodeFS.promises, "stat").mockImplementation(async (candidate) => { + if (!files.has(String(candidate))) throw new Error("not found"); + return stat; + }); + const lookup = resolveSpawnCommand("tool", ["status"], { + env: { PATH: "C:\\first;C:\\later", PATHEXT: ".EXE;.CMD" }, + }); + expect((yield* lookup).command).toBe("tool"); + files.add("C:\\first\\tool.CMD"); + files.add("C:\\first\\tool.EXE"); + files.add("C:\\later\\tool.EXE"); + expect(yield* lookup).toEqual({ + command: "C:\\first\\tool.EXE", + args: ["status"], + shell: false, + }); + files.delete("C:\\first\\tool.EXE"); + expect((yield* lookup).command).toBe("C:\\first\\tool.EXE"); + expect( + yield* Effect.promise(async () => + SpawnExecutableResolution.defaultValue()("tool", "win32", { + PATH: "C:\\first;C:\\later", + PATHEXT: ".EXE;.CMD", + }), + ), + ).toBe("C:\\first\\tool.CMD"); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(CommandResolutionCache, new Map()), + ), + ), + ); + it.effect("runs Windows executables directly without a shell", () => Effect.gen(function* () { const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index ffcc1110fe381..0ba42dc3078d6 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -75,13 +75,13 @@ export type SpawnExecutableResolver = ( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -) => string | undefined; +) => string | undefined | Promise; -function resolveSpawnExecutableWithNode( +async function resolveSpawnExecutableWithNode( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -): string | undefined { +): Promise { const path = platform === "win32" ? NodePath.win32 : NodePath.posix; const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : []; const candidates = resolveCommandCandidates( @@ -90,20 +90,24 @@ function resolveSpawnExecutableWithNode( windowsPathExtensions, path.extname, ); - const isExecutable = (candidate: string) => { + const isExecutable = async (candidate: string) => { try { - if (!NodeFS.statSync(candidate).isFile()) return false; + if (!(await NodeFS.promises.stat(candidate)).isFile()) return false; if (platform === "win32") { return windowsPathExtensions.includes(path.extname(candidate).toUpperCase()); } - return canExecuteFile(candidate); + await NodeFS.promises.access(candidate, NodeFS.constants.X_OK); + return true; } catch { return false; } }; if (command.includes("/") || command.includes("\\")) { - return candidates.find(isExecutable); + for (const candidate of candidates) { + if (await isExecutable(candidate)) return candidate; + } + return undefined; } for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { @@ -111,12 +115,12 @@ function resolveSpawnExecutableWithNode( if (normalizedPathEntry.length === 0) continue; const names = platform === "win32" - ? listPathDirectorySync(normalizedPathEntry, path.isAbsolute) + ? await listResolverPathDirectory(normalizedPathEntry, path.isAbsolute) : undefined; for (const candidate of candidates) { if (isAbsentFromListing(names, candidate)) continue; const candidatePath = path.join(normalizedPathEntry, candidate); - if (isExecutable(candidatePath)) return candidatePath; + if (await isExecutable(candidatePath)) return candidatePath; } } return undefined; @@ -661,42 +665,42 @@ export const PathDirectoryListings = Context.Reference( { defaultValue: () => Effect.runSync(makePathDirectoryListings) }, ); -const syncPathDirectoryListings = new Map< +const resolverPathDirectoryListings = new Map< string, { readonly modified: number; readonly names: ReadonlySet } >(); -// The synchronous resolver's counterpart of `PathDirectoryListings`, under the same rules. -function listPathDirectorySync( +// The spawn resolver's counterpart of `PathDirectoryListings`, under the same rules. +async function listResolverPathDirectory( directory: string, isAbsolute: (path: string) => boolean, -): ReadonlySet | undefined { +): Promise | undefined> { let modified: number; try { - const stats = NodeFS.statSync(directory); + const stats = await NodeFS.promises.stat(directory); if (!stats.isDirectory()) return undefined; modified = stats.mtimeMs; } catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined; } - const cached = syncPathDirectoryListings.get(directory); + const cached = resolverPathDirectoryListings.get(directory); if (cached?.modified === modified) return cached.names; - syncPathDirectoryListings.delete(directory); + resolverPathDirectoryListings.delete(directory); // This resolver runs outside Effect, so it has no Clock to read. // @effect-diagnostics-next-line globalDate:off const listedAtMs = Date.now(); let names: ReadonlySet; try { - names = new Set(NodeFS.readdirSync(directory).map((entry) => entry.toLowerCase())); + names = new Set((await NodeFS.promises.readdir(directory)).map((entry) => entry.toLowerCase())); } catch { return undefined; } if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) { - if (syncPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { - const oldest = syncPathDirectoryListings.keys().next().value; - if (oldest !== undefined) syncPathDirectoryListings.delete(oldest); + if (resolverPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { + const oldest = resolverPathDirectoryListings.keys().next().value; + if (oldest !== undefined) resolverPathDirectoryListings.delete(oldest); } - syncPathDirectoryListings.set(directory, { modified, names }); + resolverPathDirectoryListings.set(directory, { modified, names }); } return names; } @@ -1002,18 +1006,21 @@ const resolveMacosGit = Effect.fnUntraced(function* ( const nowNanos = yield* Clock.currentTimeNanos; const cached = cache.get(cacheKey); // An Xcode update or removal deletes the binary; look again instead of failing the spawn. - if ( - cached !== undefined && - cached.expiresAtNanos > nowNanos && - (cached.resolvedPath === null || - resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined) - ) { - return cached.resolvedPath ?? "git"; + if (cached !== undefined && cached.expiresAtNanos > nowNanos) { + const cachedPath = cached.resolvedPath; + if ( + cachedPath === null || + (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !== + undefined + ) { + return cachedPath ?? "git"; + } } - const located = - resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; + const onPath = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); + const located = onPath === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; const realGit = - located !== undefined && resolveExecutable(located, "darwin", env) !== undefined + located !== undefined && + (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined ? located : null; cacheCommandResolution(cache, cacheKey, realGit, nowNanos); @@ -1093,10 +1100,8 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( shell: false, }; } - // The scan is synchronous and runs before every child process, so it shares - // the PATH scan cache above. Explicit paths stay uncached for the same reason, - // and so do misses: a failed spawn is how providers report "not installed", - // and that has to clear the moment the binary appears. + // Cache successful PATH lookups. Explicit paths and misses stay uncached so + // newly installed executables are discoverable immediately. const explicitPath = command.includes("/") || command.includes("\\"); const cache = yield* CommandResolutionCache; const cacheKey = [ @@ -1114,7 +1119,7 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( if (cached !== undefined && cached.expiresAtNanos > nowNanos) { resolvedExecutable = cached.resolvedPath; } else { - const found = resolveExecutable(command, platform, env); + const found = yield* Effect.promise(async () => resolveExecutable(command, platform, env)); resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env); if (!explicitPath && resolvedExecutable !== null) { cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts index 6e4600fe5a338..c71f1f36df2fb 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts @@ -414,7 +414,7 @@ describe("azureCliInvocation", () => { AzureDevOpsCli.azureCliInvocation().pipe( Effect.provideService(HostProcess.Platform, "win32"), Effect.provideService(HostProcess.Environment, { PATH: "C:\\tools" }), - Effect.provideService(SpawnExecutableResolution, () => launcher), + Effect.provideService(SpawnExecutableResolution, async () => launcher), Effect.provideService(AzureCliInstallLocation, () => install), ); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts index 6cffe9ab0b3ab..f289e7406950f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts @@ -495,7 +495,8 @@ export const azureCliInvocation = Effect.fn("AzureDevOpsCli.invocation")(functio return { command: "az", args: [] } satisfies AzureCliInvocation; } const resolveExecutable = yield* SpawnExecutableResolution; - const launcher = resolveExecutable("az", "win32", yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const launcher = yield* Effect.promise(async () => resolveExecutable("az", "win32", env)); const installFor = yield* AzureCliInstallLocation; const install = launcher === undefined ? undefined : installFor(launcher); // Unrecognized installs (pipx's Scripts\az.exe) keep the launcher and today's decode. diff --git a/packages/source-control-core/src/server/discovery.ts b/packages/source-control-core/src/server/discovery.ts index 62ec94d7d67fe..0cc6654adf021 100644 --- a/packages/source-control-core/src/server/discovery.ts +++ b/packages/source-control-core/src/server/discovery.ts @@ -357,7 +357,8 @@ const unavailableInstallHint = Effect.fn("discovery.unavailableInstallHint")(fun return installHint; } const resolveExecutable = yield* SpawnExecutableResolution; - const path = resolveExecutable(executable, platform, yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const path = yield* Effect.promise(async () => resolveExecutable(executable, platform, env)); const architecture = yield* HostProcess.Architecture; return `\`${path ?? executable}\` is built for another CPU architecture, so this ${architecture} machine cannot run it. Remove or replace it. ${installHint}`; }); From b479ce21edae40ed1bcd02d117e54bb7243e5897 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:34:59 -0800 Subject: [PATCH 071/162] fix(client-runtime): stop sessions on incompatible server configuration (#21667) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/i18n/translations/de.json | 3 + apps/mobile/src/i18n/translations/en.json | 3 + apps/mobile/src/i18n/translations/es.json | 3 + apps/mobile/src/i18n/translations/fr.json | 3 + apps/mobile/src/i18n/translations/ja.json | 3 + apps/mobile/src/i18n/translations/ko.json | 3 + apps/mobile/src/i18n/translations/pt-BR.json | 3 + apps/mobile/src/i18n/translations/ru.json | 3 + apps/mobile/src/i18n/translations/sv.json | 3 + apps/mobile/src/i18n/translations/zh.json | 3 + apps/web/src/i18n/translations/de.json | 3 + apps/web/src/i18n/translations/en.json | 3 + apps/web/src/i18n/translations/es.json | 3 + apps/web/src/i18n/translations/fr.json | 3 + apps/web/src/i18n/translations/ja.json | 3 + apps/web/src/i18n/translations/ko.json | 3 + apps/web/src/i18n/translations/pt-BR.json | 3 + apps/web/src/i18n/translations/ru.json | 3 + apps/web/src/i18n/translations/sv.json | 3 + apps/web/src/i18n/translations/zh.json | 3 + .../client-runtime/src/rpc/session.test.ts | 80 +++++++++ packages/client-runtime/src/rpc/session.ts | 154 ++++++++++++------ 22 files changed, 241 insertions(+), 53 deletions(-) diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 039e1ddadd0bf..f4d80a116eece 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} konnte keine WebSocket-Verbindung herstellen.", "d9ce6c142a485959": "{host} hat {seconds} s lang nicht geantwortet.", "d6bdce8f4e6101a4": "{host} wurde getrennt.", + "8450a95e5214d199": "{host} hat ein Update der Serverkonfiguration gesendet, das dieser Client nicht lesen konnte.", + "56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.", + "368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.", "e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 91170171c1621..62b182b1a30c9 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} could not establish a WebSocket connection.", "d9ce6c142a485959": "{host} stopped responding for {seconds}s.", "d6bdce8f4e6101a4": "{host} disconnected.", + "8450a95e5214d199": "{host} sent a server configuration update this client could not read.", + "56b4ff3993c93eca": "{host} sent an incompatible server configuration.", + "368c4d4f99c66bfb": "Update the client and server to compatible versions.", "e5fd422e445391fc": "Upload failed. Tap to retry.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 398c20ce17f1f..55d4e81456cc5 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} no pudo establecer una conexión WebSocket.", "d9ce6c142a485959": "{host} dejó de responder durante {seconds} s.", "d6bdce8f4e6101a4": "{host} se desconectó.", + "8450a95e5214d199": "{host} envió una actualización de la configuración del servidor que este cliente no pudo leer.", + "56b4ff3993c93eca": "{host} envió una configuración del servidor incompatible.", + "368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.", "e5fd422e445391fc": "Error al subir. Toca para reintentar.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 1734d91934a04..245547981f3dc 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} n’a pas pu établir de connexion WebSocket.", "d9ce6c142a485959": "{host} ne répond plus depuis {seconds} s.", "d6bdce8f4e6101a4": "{host} est déconnecté.", + "8450a95e5214d199": "{host} a envoyé une mise à jour de la configuration du serveur que ce client n’a pas pu lire.", + "56b4ff3993c93eca": "{host} a envoyé une configuration de serveur incompatible.", + "368c4d4f99c66bfb": "Mettez à jour le client et le serveur vers des versions compatibles.", "e5fd422e445391fc": "Échec de l’envoi. Touchez pour réessayer.", "b2bc6bd92ea24e5c": "{size} Mo", "88f84178edbb7f57": "{size} Ko", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 113ada551f17d..a62452cddc89d 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} は WebSocket 接続を確立できませんでした。", "d9ce6c142a485959": "{host} は {seconds} 秒間応答していません。", "d6bdce8f4e6101a4": "{host} の接続が切断されました。", + "8450a95e5214d199": "{host} から、このクライアントで読み取れないサーバー設定の更新が送信されました。", + "56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。", + "368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。", "e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 7768bd410d434..87195d1e59336 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host}에서 WebSocket 연결을 설정할 수 없습니다.", "d9ce6c142a485959": "{host}이(가) {seconds}초 동안 응답하지 않습니다.", "d6bdce8f4e6101a4": "{host} 연결이 끊어졌습니다.", + "8450a95e5214d199": "{host}에서 이 클라이언트가 읽을 수 없는 서버 구성 업데이트를 보냈습니다.", + "56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.", + "368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.", "e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 88dbb8da5cd87..fb5d60acdbd89 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} não conseguiu estabelecer uma conexão WebSocket.", "d9ce6c142a485959": "{host} parou de responder por {seconds} s.", "d6bdce8f4e6101a4": "{host} desconectou.", + "8450a95e5214d199": "{host} enviou uma atualização da configuração do servidor que este cliente não conseguiu ler.", + "56b4ff3993c93eca": "{host} enviou uma configuração de servidor incompatível.", + "368c4d4f99c66bfb": "Atualize o cliente e o servidor para versões compatíveis.", "e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 2d0fb55302031..b5beca32c6869 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} не удалось установить WebSocket-соединение.", "d9ce6c142a485959": "{host} не отвечает уже {seconds} с.", "d6bdce8f4e6101a4": "{host} отключён.", + "8450a95e5214d199": "{host} отправил обновление конфигурации сервера, которое этот клиент не смог прочитать.", + "56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.", + "368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.", "e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.", "b2bc6bd92ea24e5c": "{size} МБ", "88f84178edbb7f57": "{size} КБ", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 70617afd183ca..28ed7e557146a 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} kunde inte upprätta en WebSocket-anslutning.", "d9ce6c142a485959": "{host} slutade svara i {seconds} s.", "d6bdce8f4e6101a4": "{host} kopplades från.", + "8450a95e5214d199": "{host} skickade en uppdatering av serverkonfigurationen som den här klienten inte kunde läsa.", + "56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.", + "368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.", "e5fd422e445391fc": "Uppladdningen misslyckades. Tryck för att försöka igen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} kB", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 485d4206bf054..52857eda6cc8a 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} 无法建立 WebSocket 连接。", "d9ce6c142a485959": "{host} 已 {seconds} 秒无响应。", "d6bdce8f4e6101a4": "{host} 已断开连接。", + "8450a95e5214d199": "{host} 发送了此客户端无法读取的服务器配置更新。", + "56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。", + "368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。", "e5fd422e445391fc": "上传失败。点按以重试。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 3a71e92063446..0db2fb8989ce2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} konnte keine WebSocket-Verbindung herstellen.", "d9ce6c142a485959": "{host} hat {seconds} s lang nicht geantwortet.", "d6bdce8f4e6101a4": "{host} wurde getrennt.", + "8450a95e5214d199": "{host} hat ein Update der Serverkonfiguration gesendet, das dieser Client nicht lesen konnte.", + "56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.", + "368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.", "e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 65ed2a4db1b89..3aa61a18f6b2b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} could not establish a WebSocket connection.", "d9ce6c142a485959": "{host} stopped responding for {seconds}s.", "d6bdce8f4e6101a4": "{host} disconnected.", + "8450a95e5214d199": "{host} sent a server configuration update this client could not read.", + "56b4ff3993c93eca": "{host} sent an incompatible server configuration.", + "368c4d4f99c66bfb": "Update the client and server to compatible versions.", "e5fd422e445391fc": "Upload failed. Tap to retry.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index dae05eda74dd9..60ddca69b570f 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} no pudo establecer una conexión WebSocket.", "d9ce6c142a485959": "{host} dejó de responder durante {seconds} s.", "d6bdce8f4e6101a4": "{host} se desconectó.", + "8450a95e5214d199": "{host} envió una actualización de la configuración del servidor que este cliente no pudo leer.", + "56b4ff3993c93eca": "{host} envió una configuración del servidor incompatible.", + "368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.", "e5fd422e445391fc": "Error al subir. Toca para reintentar.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 6054810c0c23d..fdcba31a1032f 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} n’a pas pu établir de connexion WebSocket.", "d9ce6c142a485959": "{host} ne répond plus depuis {seconds} s.", "d6bdce8f4e6101a4": "{host} est déconnecté.", + "8450a95e5214d199": "{host} a envoyé une mise à jour de la configuration du serveur que ce client n’a pas pu lire.", + "56b4ff3993c93eca": "{host} a envoyé une configuration de serveur incompatible.", + "368c4d4f99c66bfb": "Mettez à jour le client et le serveur vers des versions compatibles.", "e5fd422e445391fc": "Échec de l’envoi. Touchez pour réessayer.", "b2bc6bd92ea24e5c": "{size} Mo", "88f84178edbb7f57": "{size} Ko", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 188d63866545c..13379225ecf26 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} は WebSocket 接続を確立できませんでした。", "d9ce6c142a485959": "{host} は {seconds} 秒間応答していません。", "d6bdce8f4e6101a4": "{host} の接続が切断されました。", + "8450a95e5214d199": "{host} から、このクライアントで読み取れないサーバー設定の更新が送信されました。", + "56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。", + "368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。", "e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index fd4f1a5af2fc8..cc8261d7681ff 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host}에서 WebSocket 연결을 설정할 수 없습니다.", "d9ce6c142a485959": "{host}이(가) {seconds}초 동안 응답하지 않습니다.", "d6bdce8f4e6101a4": "{host} 연결이 끊어졌습니다.", + "8450a95e5214d199": "{host}에서 이 클라이언트가 읽을 수 없는 서버 구성 업데이트를 보냈습니다.", + "56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.", + "368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.", "e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index f8450e8032e5f..a9ce3832a0b9f 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} não conseguiu estabelecer uma conexão WebSocket.", "d9ce6c142a485959": "{host} parou de responder por {seconds} s.", "d6bdce8f4e6101a4": "{host} desconectou.", + "8450a95e5214d199": "{host} enviou uma atualização da configuração do servidor que este cliente não conseguiu ler.", + "56b4ff3993c93eca": "{host} enviou uma configuração de servidor incompatível.", + "368c4d4f99c66bfb": "Atualize o cliente e o servidor para versões compatíveis.", "e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 75b7db757cf04..ee0fe30aa4f39 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} не удалось установить WebSocket-соединение.", "d9ce6c142a485959": "{host} не отвечает уже {seconds} с.", "d6bdce8f4e6101a4": "{host} отключён.", + "8450a95e5214d199": "{host} отправил обновление конфигурации сервера, которое этот клиент не смог прочитать.", + "56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.", + "368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.", "e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.", "b2bc6bd92ea24e5c": "{size} МБ", "88f84178edbb7f57": "{size} КБ", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6a3525acc8636..fb02753220b14 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} kunde inte upprätta en WebSocket-anslutning.", "d9ce6c142a485959": "{host} slutade svara i {seconds} s.", "d6bdce8f4e6101a4": "{host} kopplades från.", + "8450a95e5214d199": "{host} skickade en uppdatering av serverkonfigurationen som den här klienten inte kunde läsa.", + "56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.", + "368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.", "e5fd422e445391fc": "Uppladdningen misslyckades. Tryck för att försöka igen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} kB", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index af1ca50a064b3..04044302284b7 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -637,6 +637,9 @@ "fc2020db8a3804c0": "{host} 无法建立 WebSocket 连接。", "d9ce6c142a485959": "{host} 已 {seconds} 秒无响应。", "d6bdce8f4e6101a4": "{host} 已断开连接。", + "8450a95e5214d199": "{host} 发送了此客户端无法读取的服务器配置更新。", + "56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。", + "368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。", "e5fd422e445391fc": "上传失败。点按以重试。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index 5882638af0c0c..ebd4780ba5064 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -291,6 +291,59 @@ const publishConfigEvents = Effect.fn("TestRpcSessionFactory.publishConfigEvents }); describe("RpcSessionFactory", () => { + it.effect.each([ + { established: false, closedWith: { _tag: "ConnectionBlockedError", reason: "unsupported" } }, + { + established: true, + closedWith: { _tag: "ConnectionTransientError", reason: "remote-unavailable" }, + }, + ])( + "ends the session when config fails to decode, after readiness=$established", + ({ established, closedWith }) => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const ready = yield* session.ready.pipe(Effect.exit, Effect.forkChild); + const socket = yield* awaitSocket(sockets); + socket.open(); + if (established) { + yield* completeInitialConfig(socket); + yield* Fiber.join(ready); + yield* completeInitialConfig(socket, { ...ENCODED_SERVER_CONFIG, cwd: 42 }); + } else { + yield* completeInitialConfig(socket, { ...ENCODED_SERVER_CONFIG, cwd: 42 }); + expect(yield* Fiber.join(ready)).toMatchObject({ + _tag: "Failure", + cause: { reasons: [{ _tag: "Fail", error: { reason: "unsupported" } }] }, + }); + } + + expect(yield* Effect.flip(session.closed)).toMatchObject({ ...closedWith, hop: "server" }); + }).pipe(Effect.scoped), + ); + + it.effect( + "fails readiness with the disconnect when the socket closes before its first config", + () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const ready = yield* Effect.forkChild(Effect.flip(session.ready)); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* awaitRequest(socket); + socket.close(1012, "service restart"); + + for (const error of [yield* Fiber.join(ready), yield* Effect.flip(session.closed)]) { + expect(error).toMatchObject({ + _tag: "ConnectionTransientError", + reason: "transport", + detail: "Test environment disconnected.", + }); + } + }).pipe(Effect.scoped), + ); + it.effect("connects while a large config snapshot downloads at 4000 bytes per second", () => Effect.gen(function* () { const { factory, sockets } = yield* makeFactory(); @@ -822,6 +875,33 @@ describe("RpcSessionFactory", () => { }), ); + it.effect("closes the session when the server interrupts the config stream", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const readyFiber = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(readyFiber); + + const closedFiber = yield* Effect.forkChild(Effect.flip(session.closed)); + const request = yield* awaitRequest(socket); + socket.serverMessage( + encodeJson({ + _tag: "Exit", + requestId: request.id, + exit: { _tag: "Failure", cause: [{ _tag: "Interrupt", fiberId: null }] }, + }), + ); + + expect(yield* Fiber.join(closedFiber)).toMatchObject({ + reason: "remote-unavailable", + detail: "Test environment config subscription ended.", + }); + }), + ); + it.effect.each([{ failure: "defect" as const }, { failure: "typed" as const }])( "keeps durable config state alive after an owned $failure failure", ({ failure }) => diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 409169ff1e345..91160a60941db 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -139,11 +139,14 @@ const isSocketErrorReason = Schema.is(Socket.SocketErrorReason); const PING_TIMEOUT_SECONDS = Duration.toSeconds(PING_TIMEOUT); function mapSessionRpcError( - error: InitialConfigError | ProbeError | ServerConfigSubscriptionError, - networkHint: string, + error: InitialConfigError | ProbeError | ServerConfigSubscriptionError | ConnectionAttemptError, via: "relay" | "direct", + socketFailure: () => ConnectionTransientError, ): ConnectionAttemptError { switch (error._tag) { + case "ConnectionBlockedError": + case "ConnectionTransientError": + return error; case "EnvironmentAuthorizationError": return new ConnectionBlockedError({ reason: "permission", @@ -160,11 +163,13 @@ function mapSessionRpcError( via, }); case "RpcClientError": - return new ConnectionTransientErrorClass({ - reason: "transport", - detail: `${error.message}${isSocketErrorReason(error.reason) ? networkHint : ""}`, - ...socketFailureLocation(via), - }); + return isSocketErrorReason(error.reason) + ? socketFailure() + : new ConnectionTransientErrorClass({ + reason: "transport", + detail: error.message, + ...socketFailureLocation(via), + }); } } @@ -194,47 +199,42 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( const connect = Effect.fnUntraced(function* (connection: PreparedConnection) { const via = connection.target._tag === "RelayConnectionTarget" ? "relay" : "direct"; - const networkHint = via === "relay" ? ` ${NETWORK_BLOCKING_HINT}` : ""; - const mapRpcError = (error: Parameters[0]) => - mapSessionRpcError(error, networkHint, via); yield* Effect.annotateCurrentSpan({ "connection.environment.id": connection.environmentId, }); const connected = yield* Deferred.make(); const disconnected = yield* Deferred.make(); - const pingTimedOut = yield* Ref.make(false); + let pingTimedOut = false; + const socketFailure = () => + new ConnectionTransientErrorClass({ + reason: "transport", + // The network hint only fits a socket that never opened. Once it + // opened, the path worked, and a host that goes quiet is more + // often overloaded or asleep than blocked. + ...(!Deferred.isDoneUnsafe(connected) + ? translatableDetail( + msg("{host} could not establish a WebSocket connection.", { + host: connection.label, + }), + ...(via === "relay" ? [NETWORK_BLOCKING_HINT] : []), + ) + : pingTimedOut + ? translatableDetail( + msg("{host} stopped responding for {seconds}s.", { + host: connection.label, + seconds: String(PING_TIMEOUT_SECONDS), + }), + UNRESPONSIVE_HOST_HINT, + ) + : translatableDetail(msg("{host} disconnected.", { host: connection.label }))), + ...socketFailureLocation(via), + }); + const mapRpcError = (error: Parameters[0]) => + mapSessionRpcError(error, via, socketFailure); const hooks = RpcClient.ConnectionHooks.of({ onConnect: Deferred.succeed(connected, undefined).pipe(Effect.asVoid), - onDisconnect: Effect.all([Deferred.isDone(connected), Ref.get(pingTimedOut)]).pipe( - Effect.flatMap(([wasConnected, timedOut]) => - Deferred.fail( - disconnected, - new ConnectionTransientErrorClass({ - reason: "transport", - // The network hint only fits a socket that never opened. Once it - // opened, the path worked, and a host that goes quiet is more - // often overloaded or asleep than blocked. - ...(!wasConnected - ? translatableDetail( - msg("{host} could not establish a WebSocket connection.", { - host: connection.label, - }), - ...(via === "relay" ? [NETWORK_BLOCKING_HINT] : []), - ) - : timedOut - ? translatableDetail( - msg("{host} stopped responding for {seconds}s.", { - host: connection.label, - seconds: String(PING_TIMEOUT_SECONDS), - }), - UNRESPONSIVE_HOST_HINT, - ) - : translatableDetail(msg("{host} disconnected.", { host: connection.label }))), - ...socketFailureLocation(via), - }), - ), - ), + onDisconnect: Effect.suspend(() => Deferred.fail(disconnected, socketFailure())).pipe( Effect.asVoid, ), }); @@ -267,7 +267,10 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( pingTimeout: PING_TIMEOUT, retryTransientErrors: false, retryPolicy: Schedule.recurs(0), - onPingTimeout: Ref.set(pingTimedOut, true), + // RpcClient runs this before it fails the open requests. + onPingTimeout: Effect.sync(() => { + pingTimedOut = true; + }), }).pipe( // Teardown sends an interrupt per open stream, and a write to a closed // socket waits out the client's 1s interrupt timeout before reconnecting. @@ -302,7 +305,10 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ); const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext)); const initialConfigDeferred = yield* Deferred.make(); - const serverConfigExit = yield* Deferred.make(); + const serverConfigExit = yield* Deferred.make< + void, + ServerConfigSubscriptionError | ConnectionAttemptError + >(); const configSubscriptionClosed = yield* Deferred.make(); const serverConfigState = yield* Ref.make(Option.none()); const serverConfigUpdates = yield* PubSub.sliding(64); @@ -310,6 +316,8 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( reason: "remote-unavailable", detail: `${connection.label} config subscription ended.`, }); + // An interrupt while the session is not closing came from the server; it ends the subscription. + let closingSession = false; const configRequestedAtMs = yield* Clock.currentTimeMillis; const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig]( onDemandSnapshots(serverConfigInput), @@ -362,8 +370,46 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( } }), ), + // An unreadable first snapshot means the versions are incompatible. A later + // unreadable update ends the session, and the reconnect's snapshot decides. + Effect.catchDefect((defect) => + Schema.isSchemaError(defect) + ? Effect.logWarning("Server configuration failed to decode.", { + environmentId: connection.environmentId, + issue: defect.message, + }).pipe( + Effect.andThen( + Effect.fail( + Deferred.isDoneUnsafe(initialConfigDeferred) + ? new ConnectionTransientErrorClass({ + reason: "remote-unavailable", + ...translatableDetail( + msg( + "{host} sent a server configuration update this client could not read.", + { host: connection.label }, + ), + ), + hop: "server", + via, + }) + : new ConnectionBlockedError({ + reason: "unsupported", + ...translatableDetail( + msg("{host} sent an incompatible server configuration.", { + host: connection.label, + }), + msg("Update the client and server to compatible versions."), + ), + hop: "server", + via, + }), + ), + ), + ) + : Effect.die(defect), + ), Effect.onExit((exit) => { - if (Exit.isSuccess(exit)) { + if (Exit.isSuccess(exit) || (Cause.hasInterruptsOnly(exit.cause) && !closingSession)) { return Effect.all([ Deferred.succeed(serverConfigExit, undefined), Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError), @@ -379,6 +425,12 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( }), ); yield* serverConfigSource.pipe(Effect.forkScoped); + // Finalizers run in reverse, so this is set before the fork above is interrupted. + yield* Effect.addFinalizer(() => + Effect.sync(() => { + closingSession = true; + }), + ); const initialConfig = Effect.raceFirst( Deferred.await(initialConfigDeferred), Deferred.await(serverConfigExit).pipe( @@ -424,7 +476,9 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ).pipe( Stream.catchCause((cause) => { if (Cause.hasInterruptsOnly(cause)) { - return Stream.failCause(cause); + return Stream.failCause( + Cause.fromReasons(cause.reasons.filter(Cause.isInterruptReason)), + ); } // The supervisor keeps the original cause. Shared durable consumers // need a transport-shaped failure so they wait for its replacement. @@ -471,17 +525,11 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( client: protocolClient, initialConfig, subscribeServerConfig, - ready: Deferred.await(connected).pipe( - Effect.andThen(initialConfig), - Effect.asVoid, - Effect.raceFirst(Deferred.await(disconnected)), - ), + ready: initialConfig.pipe(Effect.asVoid), probe, inboundFrames: Effect.sync(() => inboundFrames), - closed: Effect.raceFirst( - Deferred.await(disconnected), - Deferred.await(configSubscriptionClosed), - ), + // The config stream also fails on disconnect, and only it can report a decode failure. + closed: Deferred.await(configSubscriptionClosed), } satisfies RpcSession; }); From 620cf4770d992d642f822a13dc2539c2605a3500 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 05:38:38 -0800 Subject: [PATCH 072/162] fix(web): browser page translation no longer crashes the app when a turn updates (#40856) --- apps/web/src/appInit.tsx | 2 + .../lib/pageTranslationGuard.browser.test.tsx | 42 +++++++++++++++++++ apps/web/src/lib/pageTranslationGuard.ts | 20 +++++++++ 3 files changed, 64 insertions(+) create mode 100644 apps/web/src/lib/pageTranslationGuard.browser.test.tsx create mode 100644 apps/web/src/lib/pageTranslationGuard.ts diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index ae8e685c5c9ec..cce59f08f6d12 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -62,6 +62,7 @@ import { installChatRouteCommands } from "./shortcuts/chatRouteCommands"; import { startWorkspaceFocus } from "./lib/workspaceFocus"; import { m } from "./i18n/messages"; import { startI18n, subscribeI18n } from "./i18n/runtime"; +import { guardDomAgainstPageTranslation } from "./lib/pageTranslationGuard"; import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands"; import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut"; import { environmentThreadShells, threadEnvironment } from "./state/threads"; @@ -267,6 +268,7 @@ export function startAppServices(): AppRouter { } installDesktopPasteAsText(window.desktopBridge, window); + guardDomAgainstPageTranslation(); startClientAppearance(); startI18n(); diff --git a/apps/web/src/lib/pageTranslationGuard.browser.test.tsx b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx new file mode 100644 index 0000000000000..40d7e7597ccf8 --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { guardDomAgainstPageTranslation } from "./pageTranslationGuard"; + +// What Chrome's page translator does: swap each text node for translation. +function translatePage(root: Element) { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const textNodes: Text[] = []; + while (walker.nextNode()) textNodes.push(walker.currentNode as Text); + for (const text of textNodes) { + if (!text.nodeValue?.trim()) continue; + const outer = document.createElement("font"); + const inner = document.createElement("font"); + inner.textContent = `译:${text.nodeValue}`; + outer.append(inner); + text.replaceWith(outer); + } +} + +function Status({ running }: { running: boolean }) { + return ( +
    + {running ? "Working" : } + {"for 2s"} +
    + ); +} + +describe("guardDomAgainstPageTranslation", () => { + it("keeps React committing after page translation replaced its text nodes", async () => { + guardDomAgainstPageTranslation(); + await using screen = await render(, { router: false }); + translatePage(screen.container); + + // Removing "Working" hits removeChild; placing the icon before "for 2s" hits insertBefore. + await screen.rerender(); + await expect.element(screen.getByTestId("done")).toBeInTheDocument(); + await screen.rerender(); + await expect.element(screen.getByTestId("done")).not.toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/lib/pageTranslationGuard.ts b/apps/web/src/lib/pageTranslationGuard.ts new file mode 100644 index 0000000000000..de8dbceb8e2bf --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.ts @@ -0,0 +1,20 @@ +// Browser page translation (Chrome, Edge) swaps text nodes for wrappers React does not +// know about, so a later removeChild or insertBefore on the original node throws NotFoundError +// and takes down the whole tree. See facebook/react#11538. +export function guardDomAgainstPageTranslation(): void { + const proto = Node.prototype; + const removeChild = proto.removeChild; + const insertBefore = proto.insertBefore; + + proto.removeChild = function (this: Node, child: T): T { + // Already detached by the translator: nothing left to remove. + if (child.parentNode !== this) return child; + return removeChild.call(this, child) as T; + }; + + proto.insertBefore = function (this: Node, node: T, reference: Node | null): T { + // The anchor was replaced; append so the new node still shows. + const anchor = reference && reference.parentNode !== this ? null : reference; + return insertBefore.call(this, node, anchor) as T; + }; +} From 30372d0fade8903b4cd6c544768333fc7588fd37 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 22 Nov 2026 06:13:03 -0800 Subject: [PATCH 073/162] perf(mobile): keep image bytes outside draft JSON (#9727) Co-authored-by: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../review/ReviewCommentComposerSheet.tsx | 70 +++++++--- .../sharing/incoming-share-model.test.ts | 118 ++++++++++++++++- .../features/sharing/incoming-share-model.ts | 55 +++++--- apps/mobile/src/lib/composerFiles.test.ts | 81 +++++++----- apps/mobile/src/lib/composerImages.test.ts | 24 ++-- apps/mobile/src/lib/composerImages.ts | 122 +++++++++++------- apps/mobile/src/state/thread-outbox-model.ts | 6 +- .../src/state/use-composer-drafts.test.ts | 22 +++- apps/mobile/src/state/use-composer-drafts.ts | 4 +- 9 files changed, 368 insertions(+), 134 deletions(-) diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx index db2e7169d4930..881f67e86648f 100644 --- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx @@ -2,7 +2,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native" import { TextInputWrapper } from "expo-paste-input"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { T, useGT } from "gt-react-native"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { ScrollView, View, useWindowDimensions } from "react-native"; import * as Dialog from "../../components/ui/Dialog"; import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal"; @@ -16,6 +16,7 @@ import { cn } from "../../lib/cn"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages"; import { useNativePaste } from "../../lib/useNativePaste"; +import { scheduleUnusedComposerAttachmentCleanup } from "../../state/use-composer-drafts"; import { setPendingConnectionError } from "../../state/use-remote-environment-registry"; import { appendReviewCommentToDraft } from "../../state/use-thread-composer-state"; import { @@ -49,6 +50,31 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp const { environmentId, threadId } = props.route.params; const [commentText, setCommentText] = useState(""); const [attachments, setAttachments] = useState>([]); + const attachmentsRef = useRef(attachments); + const isMountedRef = useRef(true); + // Store file references before React commits, so closing the sheet can release them. + const replaceAttachments = (next: ReadonlyArray) => { + attachmentsRef.current = next; + setAttachments(next); + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases owned image files when the sheet unmounts + useEffect(() => { + isMountedRef.current = true; + return () => { + isMountedRef.current = false; + scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current); + }; + }, []); + + function appendImages(images: ReadonlyArray): void { + if (!isMountedRef.current) { + scheduleUnusedComposerAttachmentCleanup(images); + return; + } + if (images.length > 0) { + replaceAttachments([...attachmentsRef.current, ...images]); + } + } const [previewFile, setPreviewFile] = useState(null); const { selectedLines, highlightedLinesById } = useMemo(() => { @@ -90,27 +116,25 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp }; const handleNativePaste = useNativePaste((uris) => { void (async () => { - try { - const result = await convertPastedImagesToAttachments({ - uris, - existingCount: attachments.length, - }); - if (result.attachments.length > 0) { - setAttachments((current) => [...current, ...result.attachments]); - } - if (result.error) Dialog.alert(gt("Could not paste image"), result.error); - } catch (error) { + const result = await convertPastedImagesToAttachments({ + uris, + existingCount: attachmentsRef.current.length, + }).catch((error: unknown) => { console.error("[review comment] error converting pasted images", error); + return null; + }); + if (result === null) return; + appendImages(result.attachments); + if (result.error && isMountedRef.current) { + Dialog.alert(gt("Could not paste image"), result.error); } })(); }); async function handlePickImages(): Promise { - const result = await pickComposerImages({ existingCount: attachments.length }); - if (result.images.length > 0) { - setAttachments((current) => [...current, ...result.images]); - } - if (result.error) { + const result = await pickComposerImages({ existingCount: attachmentsRef.current.length }); + appendImages(result.images); + if (result.error && isMountedRef.current) { setPendingConnectionError(result.error); } } @@ -124,9 +148,10 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp environmentId, threadId, text: formatReviewCommentContext(target, commentText), - attachments, + attachments: attachmentsRef.current, }); - setAttachments([]); + scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current); + replaceAttachments([]); dismissComposer(); }; @@ -255,9 +280,12 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp onPressPreview={setPreviewFile} removeButtonPlacement="gutter" onRemove={(imageId) => { - setAttachments((current) => - current.filter((image) => image.id !== imageId), - ); + const current = attachmentsRef.current; + const removed = current.find((image) => image.id === imageId); + replaceAttachments(current.filter((image) => image.id !== imageId)); + if (removed) { + scheduleUnusedComposerAttachmentCleanup([removed]); + } }} /> diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts index 1dea547de53b4..7ca92b23c3208 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from "@effect/vitest"; +import { describe, expect, it, vi } from "vite-plus/test"; import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, @@ -13,6 +13,32 @@ import { selectIncomingShareAttachmentsForServer, } from "./incoming-share-model"; +const nativeImage = vi.hoisted(() => ({ + resize: vi.fn(), +})); + +vi.mock("expo-image-manipulator", () => ({ + SaveFormat: { PNG: "png", JPEG: "jpeg" }, + ImageManipulator: { + manipulate: (source: string | { width: number; height: number }) => { + let size = typeof source === "string" ? { width: 3000, height: 1500 } : source; + const context = { + resize: (next: { width: number; height: number }) => { + nativeImage.resize(next); + size = next; + return context; + }, + renderAsync: async () => ({ + ...size, + release: () => {}, + saveAsync: async () => ({ uri: "file:///cache/resized.png", base64: "YWJj" }), + }), + }; + return context; + }, + }, +})); + describe("incoming native shares", () => { it("converts shared text, URLs, and images into a durable composer draft", async () => { const image: SharePayload = { @@ -35,6 +61,9 @@ describe("incoming native shares", () => { originalName: "Screenshot.png", }; const removeOwnedFile = vi.fn(() => Promise.resolve()); + const readBase64 = vi.fn(async () => "YWJj"); + const persistedUri = "file:///documents/t3-composer-attachments/Screenshot.png"; + const persistFile = vi.fn(async () => persistedUri); const result = await buildIncomingShareDraft({ id: "share-1", @@ -42,7 +71,9 @@ describe("incoming native shares", () => { payloads, resolvedPayloads: [resolvedImage], fileReader: { - readBase64: async () => "YWJj", + readBase64, + persistFile, + readSize: async (uri) => (uri === persistedUri ? 3 : null), removeOwnedFile, }, }); @@ -59,16 +90,95 @@ describe("incoming native shares", () => { name: "Screenshot.png", mimeType: "image/png", sizeBytes: 3, - dataUrl: "data:image/png;base64,YWJj", - previewUri: "data:image/png;base64,YWJj", + fileUri: persistedUri, + previewUri: persistedUri, }, ], warnings: [], }); expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri); expect(hasIncomingShareContent(result)).toBe(true); }); + it("persists the resized PNG for a shared image over 2000px", async () => { + const header = Buffer.alloc(24); + header.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + header.set([0x49, 0x48, 0x44, 0x52], 12); + header.writeUInt32BE(3000, 16); + header.writeUInt32BE(1500, 20); + const persistedUri = "file:///documents/t3-composer-attachments/screenshot.png"; + const persistFile = vi.fn(async () => persistedUri); + const removeOwnedFile = vi.fn(async (_uri: string) => undefined); + + const draft = await buildIncomingShareDraft({ + id: "share-resize", + createdAt: "2026-07-15T10:00:00.000Z", + payloads: [ + { shareType: "image", value: "content://shared/screenshot", mimeType: "image/png" }, + ], + resolvedPayloads: [], + fileReader: { + readBase64: async () => header.toString("base64"), + persistFile, + readSize: async () => 3, + removeOwnedFile, + }, + }); + + expect(nativeImage.resize).toHaveBeenCalledWith({ width: 2000, height: 1000 }); + expect(persistFile).toHaveBeenCalledWith("file:///cache/resized.png", "screenshot"); + expect(draft.attachments).toEqual([ + { + id: "share-resize-image-0", + type: "image", + name: "screenshot", + mimeType: "image/png", + sizeBytes: 3, + fileUri: persistedUri, + previewUri: persistedUri, + }, + ]); + expect(draft.warnings).toEqual([]); + expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri); + }); + + it("releases a shared image when its stored size cannot be measured", async () => { + const image: SharePayload = { + shareType: "image", + value: "file:///shared/photo.png", + mimeType: "image/png", + }; + const persistedUri = "file:///documents/t3-composer-attachments/photo.png"; + const removeOwnedFile = vi.fn(async (_uri: string) => undefined); + const result = await buildIncomingShareDraft({ + id: "share-unmeasured", + createdAt: "2026-07-15T10:00:00.000Z", + payloads: [image], + resolvedPayloads: [ + { + ...image, + contentUri: image.value, + contentType: "image", + contentMimeType: "image/png", + contentSize: 3, + originalName: "photo.png", + }, + ], + fileReader: { + readBase64: async () => "unused", + persistFile: async () => persistedUri, + readSize: async () => null, + removeOwnedFile, + }, + }); + + expect(result.attachments).toEqual([]); + expect(result.warnings).toEqual(["'photo.png' is empty or could not be read."]); + expect(removeOwnedFile).toHaveBeenCalledWith(persistedUri); + expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + }); + it("skips oversized images and releases the temporary native file", async () => { const image: SharePayload = { shareType: "image", diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts index 9bfc2dcca1b29..86c17c6059e0e 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.ts @@ -412,6 +412,9 @@ export async function buildIncomingShareDraft(input: { continue; } + const name = resolved?.originalName ?? fallbackName(uri, index, mimeType); + let persistedImageUri: string | undefined; + let retainedImageUri: string | undefined; try { const sharedBase64 = await input.fileReader.readBase64(uri); // Use already-read bytes because native image loaders may not read the provider's file. @@ -421,36 +424,54 @@ export async function buildIncomingShareDraft(input: { base64: sharedBase64, }); const base64 = fitted?.base64 ?? sharedBase64; - const sizeBytes = fitted - ? estimateBase64ByteSize(base64) - : (resolved?.contentSize ?? estimateBase64ByteSize(base64)); - if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - warnings.push( - m( - msg("''{name}'' exceeds the 10 MB attachment limit.", { - name: resolved?.originalName ?? fallbackName(uri, index, mimeType), - }), - ), - ); + const decodedSize = estimateBase64ByteSize(base64); + if (decodedSize <= 0 || decodedSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + warnings.push(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }))); + continue; + } + if (input.fileReader.persistFile) { + persistedImageUri = await input.fileReader.persistFile(fitted?.uri ?? uri, name); + const sizeBytes = (await input.fileReader.readSize?.(persistedImageUri)) ?? null; + if (sizeBytes === null || sizeBytes <= 0) { + warnings.push(m(msg("''{name}'' is empty or could not be read.", { name }))); + continue; + } + if (sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, m)); + continue; + } + attachments.push({ + id: `${input.id}-image-${index}`, + type: "image", + name, + mimeType, + sizeBytes, + fileUri: persistedImageUri, + previewUri: persistedImageUri, + }); + retainedImageUri = persistedImageUri; continue; } const dataUrl = `data:${mimeType};base64,${base64}`; attachments.push({ id: `${input.id}-image-${index}`, type: "image", - name: resolved?.originalName ?? fallbackName(uri, index, mimeType), + name, mimeType, - sizeBytes, + sizeBytes: decodedSize, dataUrl, // Data-backed previews outlive temporary share files and App Group entries. previewUri: dataUrl, }); } catch { - warnings.push( - m(msg("Could not read ''{name}''.", { name: fallbackName(uri, index, mimeType) })), - ); + warnings.push(m(msg("Could not read ''{name}''.", { name }))); } finally { - await releaseOwnedFiles(input.fileReader, [uri, payload.value]); + await releaseOwnedFiles( + input.fileReader, + [uri, payload.value, persistedImageUri].filter( + (candidate) => candidate !== retainedImageUri, + ), + ); } } diff --git a/apps/mobile/src/lib/composerFiles.test.ts b/apps/mobile/src/lib/composerFiles.test.ts index bdcd35c36ff75..73f0af20fcc00 100644 --- a/apps/mobile/src/lib/composerFiles.test.ts +++ b/apps/mobile/src/lib/composerFiles.test.ts @@ -2,6 +2,9 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts"; import type { ImagePickerAsset } from "expo-image-picker"; +// Bytes of image files the tests create, so stored attachments can be read back and measured. +const imageFiles = new Map(); + const mocks = vi.hoisted(() => ({ documentUri: "file:///documents", pickFile: vi.fn(), @@ -57,6 +60,8 @@ vi.mock("expo-file-system", () => { async copy(destination: File): Promise { mocks.copy(this.uri, destination.uri); + const bytes = imageFiles.get(this.uri); + if (bytes !== undefined) imageFiles.set(destination.uri, bytes); } async base64(): Promise { @@ -99,6 +104,16 @@ import { import { isForegroundHandoffActive } from "./foreground-handoff"; import { retainComposerAttachmentFile } from "./composerAttachmentFiles"; +const STORED = "file:///documents/t3-composer-attachments/attachment-id"; + +function sizeOtherFilesAs(bytes: number): void { + mocks.size.mockImplementation((uri: string) => { + if (uri.startsWith("content:")) return null; + const stored = imageFiles.get(uri); + return stored === undefined ? bytes : Buffer.from(stored, "base64").byteLength; + }); +} + describe("composer file attachments", () => { beforeEach(() => { mocks.documentUri = "file:///documents"; @@ -110,7 +125,8 @@ describe("composer file attachments", () => { mocks.size.mockReset(); mocks.readBase64.mockReset(); mocks.manipulate.mockReset(); - mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? null : 42)); + imageFiles.clear(); + sizeOtherFilesAs(42); }); describe("photo library image conversion", () => { @@ -151,8 +167,11 @@ describe("composer file attachments", () => { width: size.width, height: size.height, release: mocks.release, - saveAsync: async (options: { format: string }) => - native.encode?.(size, options.format) ?? native.saved, + saveAsync: async (options: { format: string }) => { + const saved = native.encode?.(size, options.format) ?? native.saved; + if (saved.base64 !== undefined) imageFiles.set(saved.uri, saved.base64); + return saved; + }, }), }; return context; @@ -160,7 +179,7 @@ describe("composer file attachments", () => { }); it.each(["image/heic", "image/heif", undefined])( - "renders a %s photo to JPEG natively and previews the rendered file", + "renders a %s photo to JPEG natively and stores it in an owned file", async (mimeType) => { mocks.pickMedia.mockResolvedValue({ canceled: false, @@ -180,8 +199,8 @@ describe("composer file attachments", () => { name: "photo.jpg", mimeType: "image/jpeg", sizeBytes: 4, - dataUrl: `data:image/jpeg;base64,${rendered.base64}`, - previewUri: rendered.uri, + fileUri: `${STORED}-photo.jpg`, + previewUri: `${STORED}-photo.jpg`, }, ], error: null, @@ -200,6 +219,7 @@ describe("composer file attachments", () => { assets: [{ ...photo, fileName: name, mimeType: original.mimeType }], }); mocks.readBase64.mockResolvedValue(original.base64); + imageFiles.set(photo.uri, original.base64); const result = await pickComposerImages({ existingCount: 0 }); @@ -210,11 +230,12 @@ describe("composer file attachments", () => { expect.objectContaining({ name, mimeType: original.mimeType, - dataUrl: `data:${original.mimeType};base64,${original.base64}`, + fileUri: `${STORED}-${name}`, sizeBytes: Buffer.from(original.base64, "base64").byteLength, - previewUri: photo.uri, }), ]); + expect(result.images[0]).not.toHaveProperty("dataUrl"); + expect(imageFiles.get(`${STORED}-${name}`)).toBe(original.base64); }); it("shrinks a fitted PNG further when re-encoding it exceeds the image limit", async () => { @@ -229,7 +250,7 @@ describe("composer file attachments", () => { uri: `file:///cache/fitted-${size.width}x${size.height}.${format}`, base64: Buffer.alloc(size.width * size.height * 4).toString("base64"), }); - mocks.size.mockReturnValue(7 * 1024 * 1024); + sizeOtherFilesAs(7 * 1024 * 1024); mocks.readBase64.mockResolvedValue(header.toString("base64")); mocks.pickMedia.mockResolvedValue({ canceled: false, @@ -248,12 +269,14 @@ describe("composer file attachments", () => { name: "IMG_9280.png", mimeType: "image/png", sizeBytes: last.width * last.height * 4, - previewUri: `file:///cache/fitted-${last.width}x${last.height}.png`, + fileUri: `${STORED}-IMG_9280.png`, }), ); expect(image!.sizeBytes).toBeLessThanOrEqual(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES); expect(mocks.delete).toHaveBeenCalledWith("file:///cache/fitted-1397x2000.png"); - expect(mocks.delete).not.toHaveBeenCalledWith(image!.previewUri); + expect(imageFiles.get(image!.previewUri)).toBe( + Buffer.alloc(last.width * last.height * 4).toString("base64"), + ); }); it("measures the picker file instead of trusting the reported size", async () => { @@ -261,7 +284,7 @@ describe("composer file attachments", () => { canceled: false, assets: [{ ...photo, fileName: "photo.png", mimeType: "image/png", fileSize: 42 }], }); - mocks.size.mockReturnValue(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); + sizeOtherFilesAs(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); const result = await pickComposerImages({ existingCount: 0 }); @@ -372,7 +395,7 @@ describe("composer file attachments", () => { ); expect(result).toEqual({ attachments: [ - expect.objectContaining({ type: "image", dataUrl: "data:image/png;base64,YWJj" }), + expect.objectContaining({ type: "image", fileUri: `${STORED}-photo.png` }), { id: "attachment-id", type: "file", @@ -398,7 +421,7 @@ describe("composer file attachments", () => { expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]); expect(result.error).toBe("Video attachments are unavailable here."); - expect(mocks.copy).not.toHaveBeenCalled(); + expect(mocks.copy).not.toHaveBeenCalledWith(video.uri, expect.anything()); }); it("uses local video metadata when the picker omits its name, MIME type, or size", async () => { @@ -476,7 +499,7 @@ describe("composer file attachments", () => { expect(result.attachments).toEqual([expect.objectContaining({ type: "image" })]); expect(result.error).toBe("You can attach up to 100 attachments per message."); expect(mocks.pickMedia).toHaveBeenCalledWith(expect.objectContaining({ selectionLimit: 1 })); - expect(mocks.copy).not.toHaveBeenCalled(); + expect(mocks.copy).not.toHaveBeenCalledWith(video.uri, expect.anything()); }); it("reports a native video retrieval error and ends the foreground handoff", async () => { @@ -506,7 +529,7 @@ describe("composer file attachments", () => { canceled: false, assets: [{ uri: `file:///picker/${name}`, name, mimeType, size: 3 }], }); - mocks.size.mockReturnValue(3); + sizeOtherFilesAs(3); mocks.readBase64.mockResolvedValue("YWJj"); const result = await pickComposerFiles({ existingCount: 0 }); @@ -519,16 +542,14 @@ describe("composer file attachments", () => { name, mimeType: expected, sizeBytes: 3, - dataUrl: `data:${expected};base64,YWJj`, - previewUri: `data:${expected};base64,YWJj`, + fileUri: `${STORED}-${name}`, + previewUri: `${STORED}-${name}`, }, ], error: null, }); expect(mocks.manipulate).not.toHaveBeenCalled(); - expect(mocks.delete).toHaveBeenCalledWith( - `file:///documents/t3-composer-attachments/attachment-id-${name}`, - ); + expect(mocks.delete).not.toHaveBeenCalled(); }); it.each([ @@ -590,17 +611,19 @@ describe("composer file attachments", () => { header.writeUInt32BE(3000, 20); const original = header.toString("base64"); mocks.readBase64.mockResolvedValue(original); + imageFiles.set("file:///picker/photo.png", original); const resize = vi.fn(); const renderAsync = vi.fn(async () => ({ width: 4000, height: 3000, release: vi.fn(), - saveAsync: vi.fn(async () => ({ - uri: "file:///cache/fitted.png", - base64: oversized + saveAsync: vi.fn(async () => { + const base64 = oversized ? Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1).toString("base64") - : "YWJj", - })), + : "YWJj"; + imageFiles.set("file:///cache/fitted.png", base64); + return { uri: "file:///cache/fitted.png", base64 }; + }), })); mocks.manipulate.mockImplementation(() => { const context = { @@ -626,14 +649,12 @@ describe("composer file attachments", () => { type: "image", mimeType: "image/png", sizeBytes: oversized ? header.length : 3, - dataUrl: `data:image/png;base64,${oversized ? original : "YWJj"}`, - previewUri: oversized - ? `data:image/png;base64,${original}` - : "file:///cache/fitted.png", + fileUri: `${STORED}-photo.png`, }), ], error: null, }); + expect(imageFiles.get(`${STORED}-photo.png`)).toBe(oversized ? original : "YWJj"); }); it("releases the owned copy when reading an image fails", async () => { diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts index d7830b8ed3466..de05411a8f327 100644 --- a/apps/mobile/src/lib/composerImages.test.ts +++ b/apps/mobile/src/lib/composerImages.test.ts @@ -122,6 +122,8 @@ vi.mock("./uuid", () => ({ import { convertPastedImagesToAttachments, persistComposerAttachmentFile } from "./composerImages"; +const STORED = "file:///documents/t3-composer-attachments/attachment-id"; + function oversizedPng(): string { const png = Buffer.alloc(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1); Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(png); @@ -150,10 +152,12 @@ describe("native pasted image cleanup", () => { expect.objectContaining({ name: "pasted-image.jpeg", mimeType: "image/jpeg", - dataUrl: "data:image/jpeg;base64,aGVsbG8=", - previewUri: "data:image/jpeg;base64,aGVsbG8=", + fileUri: `${STORED}-pasted-image.jpeg`, + previewUri: `${STORED}-pasted-image.jpeg`, }), ]); + expect(attachments[0]).not.toHaveProperty("dataUrl"); + expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("aGVsbG8="); expect(files.get(uri)?.deleted).toBe(false); }); @@ -171,10 +175,10 @@ describe("native pasted image cleanup", () => { expect.objectContaining({ name: "pasted-image.jpeg", mimeType: "image/jpeg", - dataUrl: "data:image/jpeg;base64,cmVuZGVyZWQ=", - previewUri: "data:image/jpeg;base64,cmVuZGVyZWQ=", + fileUri: `${STORED}-pasted-image.jpeg`, }), ]); + expect(files.get(`${STORED}-pasted-image.jpeg`)?.base64).toBe("cmVuZGVyZWQ="); expect(files.get("file:///cache/rendered.jpeg")?.deleted).toBe(true); expect(files.get(uri)?.deleted).toBe(false); }); @@ -197,7 +201,7 @@ describe("native pasted image cleanup", () => { expect(files.get(uri)?.deleted).toBe(false); }); - it("converts owned files to data-backed previews and deletes the source", async () => { + it("stores owned pastes in an attachment file and deletes the source", async () => { const uri = "file:///private/var/mobile/Containers/Data/Application/app/tmp/t3-composer-paste/id.png"; const gif = @@ -212,11 +216,13 @@ describe("native pasted image cleanup", () => { expect(attachments).toEqual([ expect.objectContaining({ - dataUrl: "data:image/png;base64,aGVsbG8=", - previewUri: "data:image/png;base64,aGVsbG8=", + fileUri: `${STORED}-pasted-image.png`, + previewUri: `${STORED}-pasted-image.png`, }), - expect.objectContaining({ mimeType: "image/gif", dataUrl: "data:image/gif;base64,R0lGODlh" }), + expect.objectContaining({ mimeType: "image/gif", fileUri: `${STORED}-pasted-image.gif` }), ]); + expect(files.get(`${STORED}-pasted-image.png`)?.base64).toBe("aGVsbG8="); + expect(files.get(`${STORED}-pasted-image.gif`)?.base64).toBe("R0lGODlh"); expect(files.get(uri)?.deleted).toBe(true); expect(files.get(gif)?.deleted).toBe(true); }); @@ -267,7 +273,7 @@ describe("native pasted image cleanup", () => { const result = await convertPastedImagesToAttachments({ uris: [gone, kept], existingCount: 0 }); expect(result.attachments).toEqual([ - expect.objectContaining({ dataUrl: "data:image/png;base64,aGVsbG8=" }), + expect.objectContaining({ fileUri: `${STORED}-pasted-image.png` }), ]); expect(result.error).toBe("Could not read a pasted image."); }); diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index 69f26103134b9..4c81024c1d403 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -124,7 +124,7 @@ export function isFileBackedComposerAttachment( return attachment.fileUri !== undefined; } -/** Inline library/clipboard images own no file; local ids cannot resolve server assets. */ +/** Legacy inline images have only a local draft id, so a remote asset lookup cannot load them. */ export function composerAttachmentInlineUri( attachment: DraftComposerAttachment | undefined, ): string | undefined { @@ -135,6 +135,11 @@ export function composerAttachmentInlineUri( const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste"; const ATTACHMENT_COPY_CHUNK_BYTES = 64 * 1024; +// Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`. +function safeComposerAttachmentName(name: string): string { + return name.replace(/[^\w. -]/g, "-") || "file"; +} + export async function persistComposerAttachmentFile( uri: string, name: string, @@ -143,9 +148,7 @@ export async function persistComposerAttachmentFile( const { Directory, File, FileMode, Paths } = await import("expo-file-system"); const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY); directory.create({ idempotent: true, intermediates: true }); - // Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`. - const safeName = name.replace(/[^\w. -]/g, "-") || "file"; - const destination = new File(directory, `${uuidv4()}-${safeName}`); + const destination = new File(directory, `${uuidv4()}-${safeComposerAttachmentName(name)}`); const source = new File(uri); const sourceSize = source.size; if ( @@ -218,6 +221,35 @@ export async function persistComposerAttachmentFile( return destination.uri; } +async function ownedComposerImageAttachment(input: { + readonly fileUri: string; + readonly name: string; + readonly mimeType: string; +}): Promise { + try { + const { File } = await import("expo-file-system"); + const sizeBytes = new File(input.fileUri).size; + if (sizeBytes === null || sizeBytes <= 0) { + throw new Error(m(msg("''{name}'' is empty or could not be read.", { name: input.name }))); + } + if (sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + throw new Error( + fileAttachmentTooLargeMessage(input.name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, m), + ); + } + return { + ...input, + id: uuidv4(), + type: "image", + sizeBytes, + previewUri: input.fileUri, + }; + } catch (error) { + await removePersistedComposerAttachmentFile(input.fileUri); + throw error; + } +} + export async function removePersistedComposerAttachmentFile(uri: string): Promise { try { const { File, Paths } = await import("expo-file-system"); @@ -333,37 +365,29 @@ export async function pickComposerFiles(input: { attachments.push(attachment); continue; } + const { File } = await import("expo-file-system"); + let fileUri = attachment.fileUri; try { - const { File } = await import("expo-file-system"); - const original = await new File(attachment.fileUri).base64(); - const candidate = await fitComposerImage({ - uri: attachment.fileUri, - mimeType, - base64: original, - }); + const original = await new File(fileUri).base64(); + const candidate = await fitComposerImage({ uri: fileUri, mimeType, base64: original }); const fitted = candidate !== null && estimateBase64ByteSize(candidate.base64) <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES ? candidate : null; - const base64 = fitted?.base64 ?? original; - const sizeBytes = estimateBase64ByteSize(base64); - if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - throw new Error(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }))); + if (fitted !== null) { + fileUri = await persistComposerAttachmentFile( + fitted.uri, + name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + await removePersistedComposerAttachmentFile(attachment.fileUri); } - const dataUrl = `data:${mimeType};base64,${base64}`; - attachments.push({ - id: attachment.id, - type: "image", - name, - mimeType, - sizeBytes, - dataUrl, - previewUri: fitted?.uri ?? dataUrl, - }); - } finally { + } catch (cause) { await removePersistedComposerAttachmentFile(attachment.fileUri); + throw cause; } + attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType })); } catch (cause) { error = errorDisplayMessage(cause, m) ?? m(msg("Could not read ''{name}''.", { name })); } @@ -517,7 +541,7 @@ export async function pickComposerMedia(input: { ? mimeType : null; - let image: { base64: string; mimeType: string; name: string; previewUri: string }; + let image: { base64: string; mimeType: string; name: string; uri: string }; try { if (originalMimeType !== null) { const { File } = await import("expo-file-system"); @@ -531,7 +555,7 @@ export async function pickComposerMedia(input: { base64: fitted?.base64 ?? base64, mimeType: originalMimeType, name, - previewUri: fitted?.uri ?? asset.uri, + uri: fitted?.uri ?? asset.uri, }; } else { const rendered = await renderPhoto(asset.uri); @@ -539,7 +563,7 @@ export async function pickComposerMedia(input: { base64: rendered.base64, mimeType: "image/jpeg", name: /\.jpe?g$/i.test(name) ? name : `${name.replace(/\.[^.]+$/, "")}.jpg`, - previewUri: rendered.uri, + uri: rendered.uri, }; } } catch { @@ -553,15 +577,18 @@ export async function pickComposerMedia(input: { continue; } - attachments.push({ - id: uuidv4(), - type: "image", - name: image.name, - mimeType: image.mimeType, - sizeBytes, - dataUrl: `data:${image.mimeType};base64,${image.base64}`, - previewUri: image.previewUri, - }); + try { + const fileUri = await persistComposerAttachmentFile( + image.uri, + image.name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + attachments.push( + await ownedComposerImageAttachment({ fileUri, name: image.name, mimeType: image.mimeType }), + ); + } catch (cause) { + error = errorDisplayMessage(cause, m) ?? m(msg("Failed to read ''{name}''.", { name })); + } } return { @@ -639,6 +666,7 @@ export async function convertPastedImagesToAttachments(input: { temporaryUris.push(fitted.uri); } let base64 = fitted?.base64 ?? pastedBase64; + let sourceUri = fitted?.uri ?? uri; if ( rendered === null && estimateBase64ByteSize(base64) > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES @@ -647,6 +675,7 @@ export async function convertPastedImagesToAttachments(input: { temporaryUris.push(jpeg.uri); mimeType = "image/jpeg"; base64 = jpeg.base64; + sourceUri = jpeg.uri; } const sizeBytes = estimateBase64ByteSize(base64); if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { @@ -656,16 +685,13 @@ export async function convertPastedImagesToAttachments(input: { : m(msg("Could not read a pasted image.")); continue; } - const dataUrl = `data:${mimeType};base64,${base64}`; - attachments.push({ - id: uuidv4(), - type: "image", - name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`, - mimeType, - sizeBytes, - dataUrl, - previewUri: dataUrl, - }); + const name = `pasted-image.${mimeType.split("/")[1] ?? "png"}`; + const fileUri = await persistComposerAttachmentFile( + sourceUri, + name, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, + ); + attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType })); } catch (cause) { console.warn("Failed to read pasted image", uri, cause); error = m(msg("Could not read a pasted image.")); diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.ts index d85340a8556d2..e7e9fe9a302a0 100644 --- a/apps/mobile/src/state/thread-outbox-model.ts +++ b/apps/mobile/src/state/thread-outbox-model.ts @@ -34,8 +34,8 @@ import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/compose import type { DraftComposerAttachment } from "../lib/composerImages"; import { scopedThreadKey } from "../lib/scopedEntities"; -// Keep current writes until a compatible native baseline includes the v4 reader. -const THREAD_OUTBOX_SCHEMA_VERSION = 3; +// v4 file-backed writes require native baselines with embedded readers and storage guards. +const THREAD_OUTBOX_SCHEMA_VERSION = 4; const THREAD_OUTBOX_MAX_RETRY_DELAY_MS = 16_000; const QueuedThreadCreationSchema = Schema.Struct({ @@ -52,7 +52,7 @@ const QueuedThreadCreationSchema = Schema.Struct({ }); export const QueuedThreadMessageSchema = Schema.Struct({ - schemaVersion: Schema.Literals([1, 2, THREAD_OUTBOX_SCHEMA_VERSION, 4]), + schemaVersion: Schema.Literals([1, 2, 3, THREAD_OUTBOX_SCHEMA_VERSION]), environmentId: EnvironmentId, threadId: ThreadId, messageId: MessageId, diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index fd1c248f5de9b..8c1870f76836b 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -91,9 +91,12 @@ const composerDraftFileMocks = vi.hoisted(() => { exists = true; size = 3; parentDirectory = null; + uri = "file:///documents/attachment.png"; create() {} + async copy() {} + moveSync() {} async text() { @@ -144,6 +147,7 @@ const incomingShareStorageMocks = vi.hoisted(() => ({ vi.mock("expo-file-system", () => ({ Directory: composerDraftFileMocks.Directory, File: composerDraftFileMocks.File, + FileMode: {}, Paths: { document: { uri: "file:///documents" } }, })); @@ -297,7 +301,7 @@ it.each(["picker open", "reading image"] as const)( expect.objectContaining({ type: "image", name: "screenshot.png", - dataUrl: "data:image/png;base64,YWJj", + fileUri: "file:///documents/attachment.png", }), ], ); @@ -1217,6 +1221,22 @@ describe("mobile composer drafts", () => { expect( appAtomRegistry.get(composerDraftsAtom)[pasteKey]?.attachments.map(({ id }) => id), ).toEqual(["red", "blue"]); + + const makeStoredPaste = (id: string) => ({ + id, + type: "image" as const, + name: "pasted-image.png", + mimeType: "image/png", + sizeBytes: 3, + fileUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, + previewUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, + }); + const storedKey = "new-task:environment-1:project-stored-pastes"; + appendComposerDraftAttachments(storedKey, [makeStoredPaste("red")]); + appendComposerDraftAttachments(storedKey, [makeStoredPaste("green")]); + expect( + appAtomRegistry.get(composerDraftsAtom)[storedKey]?.attachments.map(({ id }) => id), + ).toEqual(["red", "green"]); }); it("keeps shared attachment files until every draft releases them", async () => { diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 0020defdc5915..10d8fd7a4f271 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -1431,7 +1431,9 @@ function isSameAttachment(a: DraftComposerAttachment, b: DraftComposerAttachment a.mimeType === b.mimeType && a.sizeBytes === b.sizeBytes && a.name === b.name && - (a.type !== "image" || b.type !== "image" || a.dataUrl === b.dataUrl) + (a.type !== "image" || + b.type !== "image" || + (a.dataUrl === b.dataUrl && a.fileUri === b.fileUri)) ); } From ad2bdc76a5bf22cd63b84e2cdee610c1a1b4bd18 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 06:14:38 -0800 Subject: [PATCH 074/162] fix(server): watch_pull_request says when checks already passed (#40866) --- apps/server/src/mcp/toolkits/pullRequests/handlers.ts | 9 ++++++--- apps/server/src/mcp/toolkits/pullRequests/tools.ts | 4 ++++ .../src/pullRequest/PullRequestWatchService.test.ts | 10 ++++++++++ apps/server/src/pullRequest/PullRequestWatchService.ts | 6 ++++++ 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index e422a799f3d9a..ddb3f2a025d43 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -66,6 +66,7 @@ import { PullRequestsToolkit, type ThreadPullRequestEntry, alreadyEndedWatchNext, + CHECKS_ALREADY_PASSED_WATCH_NEXT, CHILD_PULL_REQUEST_REPORT_NEXT, } from "./tools.ts"; @@ -333,9 +334,11 @@ const make = Effect.gen(function* () { .setWatching({ threadId, target: input, watching, until: input.until }) .pipe( Effect.map((result) => - result.state === undefined - ? result - : { ...result, next: alreadyEndedWatchNext(result.state) }, + result.state !== undefined + ? { ...result, next: alreadyEndedWatchNext(result.state) } + : result.checksState === "passing" + ? { ...result, next: CHECKS_ALREADY_PASSED_WATCH_NEXT } + : result, ), Effect.catchTags({ PullRequestWatchThreadNotFoundError: (error) => diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 847ae4ef19e7d..1e75c5bbaa19f 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -263,6 +263,7 @@ export const WatchPullRequestResult = Schema.Struct({ description: "The PR already ended, so nothing was watched.", }), ), + checksState: Schema.optional(PullRequestChecksState), next: Schema.optional(Schema.String), }); export type WatchPullRequestResult = typeof WatchPullRequestResult.Type; @@ -270,6 +271,9 @@ export type WatchPullRequestResult = typeof WatchPullRequestResult.Type; export const alreadyEndedWatchNext = (state: "merged" | "closed") => `This PR is already ${state}, so there is nothing to watch. Report that and end your turn.`; +export const CHECKS_ALREADY_PASSED_WATCH_NEXT = + "Checks already pass on this head, so no wake will come for them. Act on that now; the watch still wakes you on later changes."; + export const ThreadPullRequestEntry = Schema.Struct({ ...PullRequestIdentity, source: ThreadPullRequestLinkSource, diff --git a/apps/server/src/pullRequest/PullRequestWatchService.test.ts b/apps/server/src/pullRequest/PullRequestWatchService.test.ts index edf4fee9c5c56..8982e795e2615 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.test.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.test.ts @@ -205,6 +205,16 @@ describe("PullRequestWatchService", () => { }), ); + it.effect("tells the caller when the checks already passed, since no wake will report it", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ readChecksState: "passing" }); + const result = yield* harness.setWatching(true, { + url: "https://github.com/t3tools/t3code/pull/9", + }); + expect(result).toMatchObject({ wasWatching: false, checksState: "passing" }); + }), + ); + it.effect("reports a missing hosting CLI before saving a watch and still allows unwatch", () => Effect.gen(function* () { const missing = new PullRequestUnavailableError({ diff --git a/apps/server/src/pullRequest/PullRequestWatchService.ts b/apps/server/src/pullRequest/PullRequestWatchService.ts index 5e64ac4206896..32f51f540bf9f 100644 --- a/apps/server/src/pullRequest/PullRequestWatchService.ts +++ b/apps/server/src/pullRequest/PullRequestWatchService.ts @@ -2,6 +2,7 @@ import { CommandId, ThreadId, type OrchestrationV2ThreadShell, + type PullRequestChecksState, type PullRequestUnavailableError, type PullRequestWatchUntil, } from "@t3tools/contracts"; @@ -68,6 +69,8 @@ export class PullRequestWatchService extends Context.Service< readonly wasWatching: boolean; /** Set when the PR already ended, so no watch was registered. */ readonly state?: "merged" | "closed"; + /** CI as the start read saw it. Checks that already passed never wake the watch. */ + readonly checksState?: PullRequestChecksState; }, | PullRequestWatchFailedError | PullRequestWatchFromSubagentError @@ -130,6 +133,7 @@ const make = Effect.gen(function* () { if (watching && before?.snapshot?.state === "merged") return alreadyEnded("merged"); // A pending rollup has no failure yet, so any failure the first read finds is news. let checksPendingAtStart: boolean | undefined; + let checksStateAtStart: PullRequestChecksState | undefined; if (watching && !wasWatching) { const read = yield* pullRequests .summary( @@ -151,6 +155,7 @@ const make = Effect.gen(function* () { ); if (read?.state === "merged" || read?.state === "closed") return alreadyEnded(read.state); checksPendingAtStart = read === undefined ? undefined : read.checksState === "pending"; + checksStateAtStart = read?.checksState ?? undefined; } const uuid = yield* random.uuidV4().pipe(Effect.orDie); yield* engine @@ -180,6 +185,7 @@ const make = Effect.gen(function* () { ...target, watching: watchedLink(after)?.watch !== undefined, wasWatching, + ...(checksStateAtStart !== undefined && { checksState: checksStateAtStart }), }; }); From a445025645680d8c282011df5edc774f4551e6d8 Mon Sep 17 00:00:00 2001 From: Abhiram Kakarla <22UKakarlaA@qerdp.co.uk> Date: Sun, 22 Nov 2026 14:38:36 +0000 Subject: [PATCH 075/162] fix(codex): Open diff shows every file of a multi-file patch (#40874) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../Adapters/CodexAdapterV2.test.ts | 22 +++++++++++++ .../Adapters/CodexAdapterV2.ts | 32 ++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index ef4ffcf35c11b..d30748a0df77c 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -12809,6 +12809,28 @@ describe("CodexAdapterV2 post-settle continuation", () => { { operation: "delete", path: "/w/e.ts" }, { operation: "add", path: "/w/a.ts" }, ]); + assert.equal( + fileChanges[0]?.diffStr, + [ + 'diff --git "a//w/c.ts" "b//w/d.ts"', + '--- "a//w/c.ts"', + '+++ "b//w/d.ts"', + "@@", + 'diff --git "a//w/e.ts" "b//w/e.ts"', + '--- "a//w/e.ts"', + "+++ /dev/null", + "@@ -1,1 +0,0 @@", + "-gone", + "\\ No newline at end of file", + 'diff --git "a//w/a.ts" "b//w/a.ts"', + "--- /dev/null", + '+++ "b//w/a.ts"', + "@@ -0,0 +1,1 @@", + "+export {};", + "\\ No newline at end of file", + "", + ].join("\n"), + ); }).pipe( Effect.scoped, Effect.provide( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index e5dfd83559292..181ed17fd5c16 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -178,6 +178,35 @@ type CodexFileChangeKinds = Readonly< Record >; +// Diff parsers split at Git headers once one exists, so each file of a multi-file patch needs its own. +function codexMultiFilePatch( + changes: ReadonlyArray, +): string { + return changes + .map(({ path, kind, diff }) => { + const oldPath = path; + const newPath = (kind.type === "update" && kind.move_path) || path; + const git = `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${newPath}`)}\n`; + if (kind.type === "update" && diff.startsWith("diff --git ")) return diff; + if (kind.type === "update" && diff.startsWith("--- ")) return `${git}${diff}`; + let hunks = diff; + // Codex records added and deleted files as their raw contents. + if (kind.type !== "update") { + const lines = diff.split("\n"); + const hasFinalNewline = diff.endsWith("\n"); + if (hasFinalNewline) lines.pop(); + const added = kind.type === "add"; + const range = `1,${lines.length}`; + hunks = `@@ -${added ? "0,0" : range} +${added ? range : "0,0"} @@\n${lines.map((line) => `${added ? "+" : "-"}${line}`).join("\n")}\n${hasFinalNewline ? "" : "\\ No newline at end of file\n"}`; + } + const before = kind.type === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`); + const after = kind.type === "delete" ? "/dev/null" : JSON.stringify(`b/${newPath}`); + return `${git}--- ${before}\n+++ ${after}\n${hunks}`; + }) + .map((section) => (section.endsWith("\n") ? section : `${section}\n`)) + .join(""); +} + function codexFileChangeApprovalPrompt(input: { readonly reason?: string | null; readonly grantRoot?: string | null; @@ -4285,7 +4314,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updatedAt, type: "file_change", fileName: firstChange.path, - diffStr: firstChange.diff, + diffStr: + item.changes.length > 1 ? codexMultiFilePatch(item.changes) : firstChange.diff, changes: item.changes.map((change) => { const movePath = change.kind.type === "update" ? change.kind.move_path : undefined; return movePath From 2f19cec07933f9f5fe1fe380d98b0841f83b90be Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 06:41:15 -0800 Subject: [PATCH 076/162] fix(server): ACP startup gives up when the agent never answers the handshake (#40864) --- .../provider/acp/AcpJsonRpcConnection.test.ts | 20 ++++++++++++++ .../src/server/AcpSessionRuntime.ts | 27 ++++++++++++++++--- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index 796bc854d28d6..a000e05471bc6 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -1621,6 +1621,26 @@ describe("AcpSessionRuntime", () => { }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.effect("fails startup when the agent never answers initialize", () => + Effect.gen(function* () { + const initializeSent = yield* Deferred.make(); + const runtime = yield* AcpSessionRuntime.make({ + ...mockRuntimeOptions, + // A live child that reads stdin and never replies, like one stuck in disk sleep. + spawn: { command: "node", args: ["-e", "process.stdin.resume()"] }, + requestLogger: (event) => + event.method === "initialize" && event.status === "started" + ? Deferred.succeed(initializeSent, undefined) + : Effect.void, + }); + const startup = yield* runtime.start().pipe(Effect.forkChild); + yield* Deferred.await(initializeSent); + yield* TestClock.adjust("30 minutes"); + const exit = yield* Fiber.await(startup); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.effect("sends a cancel after the cancel timeout when its prompt never goes out", () => Effect.gen(function* () { const runtime = yield* AcpSessionRuntime.make({ diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index 2c488b6bdd83c..b08eef243fc3e 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -85,6 +85,8 @@ export type AcpSessionRuntimeEvent = }; const defaultSessionLoadTimeout = Duration.seconds(90); +// A live child that never answers the handshake would otherwise hold the start open forever. +const startupRequestTimeout = Duration.seconds(90); const defaultSessionLoadReplayIdleGap = Duration.seconds(2); const defaultCancelTimeout = Duration.seconds(15); const maxStartupMetadataUpdates = 32; @@ -1399,6 +1401,25 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( Effect.andThen(runLoggedRequest(method, payload, effect)), ); + const withStartupTimeout =
    ( + method: string, + effect: Effect.Effect, + ): Effect.Effect => + effect.pipe( + Effect.timeoutOrElse({ + duration: startupRequestTimeout, + orElse: () => + Effect.fail( + new EffectAcpErrors.AcpTransportError({ + operation: "call-rpc", + method, + detail: `${method} timed out waiting for RPC response`, + cause: undefined, + }), + ), + }), + ); + const runLoggedRequest = ( method: string, payload: unknown, @@ -2297,7 +2318,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const initializeResult = yield* runLoggedRequest( "initialize", initializePayload, - acp.agent.initialize(initializePayload), + withStartupTimeout("initialize", acp.agent.initialize(initializePayload)), ); yield* options.onInitialized?.(initializeResult) ?? Effect.void; return initializeResult; @@ -2445,7 +2466,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( sessionSetupResult = yield* runLoggedRequest( "session/resume", resumePayload, - acp.agent.resumeSession(resumePayload), + withStartupTimeout("session/resume", acp.agent.resumeSession(resumePayload)), ); } else { return yield* new EffectAcpErrors.AcpRequestError({ @@ -2462,7 +2483,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const created = yield* runLoggedRequest( "session/new", createPayload, - acp.agent.createSession(createPayload), + withStartupTimeout("session/new", acp.agent.createSession(createPayload)), ); sessionId = created.sessionId; sessionSetupResult = created; From 1d028248683f90f405b2d8e7b71682e3b67317ed Mon Sep 17 00:00:00 2001 From: Abhiram Kakarla <22UKakarlaA@qerdp.co.uk> Date: Sun, 22 Nov 2026 14:43:54 +0000 Subject: [PATCH 077/162] fix(server): a branch prefixed with another remote's name publishes under its full name (#40877) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 29 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 21 ++++++-------- 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d9a661c7b1237..b3ad640db4c7a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -10325,6 +10325,35 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "publishes a new branch prefixed with another remote's name under its full name", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const origin = yield* makeTmpDir("git-remote-"); + const fork = yield* makeTmpDir("git-fork-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(origin, ["init", "--bare"]); + yield* git(fork, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", origin]); + // e.g. the remote T3 adds when checking out a pull request from alice's fork. + yield* git(cwd, ["remote", "add", "alice", fork]); + yield* git(cwd, ["checkout", "-b", "alice/fix"]); + yield* writeTextFile(cwd, "fix.txt", "fix\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add fix", ""); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { status: "pushed", upstreamBranch: "origin/alice/fix" }); + assert.equal( + yield* git(origin, ["--git-dir=.", "rev-parse", "refs/heads/alice/fix"]), + yield* git(cwd, ["rev-parse", "HEAD"]), + ); + }), + ); + it.effect("still pushes a git-mangled tracking alias to its upstream head", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 8f3e3e16ca12b..f863f01bdb40a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2147,14 +2147,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map(parseRemoteNamesInGitOrder), ); - const resolvePublishBranchName = Effect.fn("resolvePublishBranchName")(function* ( - cwd: string, - branchName: string, - ) { - const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.orElseSucceed(() => [])); - const parsedRemoteRef = parseRemoteRefWithRemoteNames(branchName, remoteNames); - return parsedRemoteRef?.branchName ?? branchName; - }); + // Only the destination remote's prefix is dropped; `alice/fix` pushed to origin keeps its full name. + const resolvePublishBranchName = (branchName: string, remoteName: string) => + parseRemoteRefWithRemoteNames(branchName, [remoteName])?.branchName ?? branchName; const hasAnyRemote = (cwd: string) => resolveRepositoryPaths(cwd).pipe( @@ -3680,7 +3675,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // A gone local upstream still gets the full local name, as below. const branchName = goneUpstream?.branchName ?? - (configuredRemoteName === "." ? branch : yield* resolvePublishBranchName(cwd, branch)); + (configuredRemoteName === "." ? branch : resolvePublishBranchName(branch, remoteName)); return { remoteName, branchName, @@ -3731,10 +3726,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( Effect.orElseSucceed(() => null), ); - const branchName = yield* resolvePublishBranchName(cwd, branch); + const remoteName = publishRemoteName ?? upstream.remoteName; return { - remoteName: publishRemoteName ?? upstream.remoteName, - branchName, + remoteName, + branchName: resolvePublishBranchName(branch, remoteName), publishes: true, upstream, pushRemote: null, @@ -3774,7 +3769,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const requestedRemoteName = options?.remoteName?.trim() || null; if (requestedRemoteName) { - const publishBranch = yield* resolvePublishBranchName(cwd, branch); + const publishBranch = resolvePublishBranchName(branch, requestedRemoteName); yield* executeGitWithStableDiagnostics( "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", cwd, From f10e1eb3825a773cf702569d2258edfdbc8b77dc Mon Sep 17 00:00:00 2001 From: project516 <138796702+Project516@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:55:27 -0600 Subject: [PATCH 078/162] fix(server): list open delegated tasks when task_status or task_cancel finds no match (#40886) Co-authored-by: Julius Marminge --- .../src/mcp/OrchestratorMcpService.test.ts | 8 ++++ apps/server/src/mcp/OrchestratorMcpService.ts | 38 +++++++++++++++---- 2 files changed, 38 insertions(+), 8 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index ccd41144a5ea8..551a84109cfa2 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -106,6 +106,7 @@ describe("OrchestratorMcpService", () => { threadId: parentThreadId, origin: "app_owned", childThreadId, + title: "Merge", driver: "codex", model: "gpt-5.6-terra", result: "terminal result", @@ -252,6 +253,13 @@ describe("OrchestratorMcpService", () => { const commandIds = yield* Ref.get(acknowledgementCommandIds); assert.equal(commandIds.length, 2); assert.notEqual(commandIds[0], commandIds[1]); + + const missing = yield* service + .taskStatus(scope, NodeId.make("node:mcp-ack-missing")) + .pipe(Effect.flip); + assert.equal(missing.code, "task_not_found"); + assert.include(missing.message, "No delegated task with id node:mcp-ack-missing"); + assert.include(missing.message, `${taskId} (Merge)`); }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); }), ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 4062c509812c4..f9ad32a6e1d3e 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -154,6 +154,7 @@ const TASK_WAKE_EVENTS = [ { thread: "child", eventType: "runtime-request.updated" }, ] as const; const SECRET_REQUEST_POLL_INTERVAL_MS = 500; +const MAX_LISTED_TASKS = 10; const DEFAULT_THREAD_LIST_LIMIT = 10; const DEFAULT_THREAD_READ_LIMIT = 10; const DEFAULT_THREAD_RUN_LIMIT = 10; @@ -1805,6 +1806,33 @@ const make = Effect.gen(function* () { const requestKey = (clientRequestId: string | undefined): Effect.Effect => clientRequestId === undefined ? random.uuidV4() : Effect.succeed(clientRequestId); + const taskNotFound = Effect.fn("OrchestratorMcpService.taskNotFound")(function* ( + scope: McpThreadInvocationScope, + taskId: NodeId, + ): Effect.fn.Return { + const { subagents } = yield* loadThreadRecords(scope.thread.threadId, ["subagents"], { + omitSettledSubagents: true, + }); + const open = subagents.filter( + (task) => + task.origin === "app_owned" && + (task.childThreadId !== null || task.remoteChild !== undefined), + ); + const listed = open + .slice(0, MAX_LISTED_TASKS) + .map((task) => (task.title ? `${task.id} (${task.title})` : task.id)) + .join(", "); + const more = + open.length > MAX_LISTED_TASKS ? `, and ${open.length - MAX_LISTED_TASKS} more` : ""; + return yield* failure( + "task_not_found", + `No delegated task with id ${taskId} exists on thread ${scope.thread.threadId}. ` + + (open.length === 0 + ? "This thread has no open delegated tasks." + : `Open delegated tasks on this thread: ${listed}${more}.`), + ); + }); + const readTask = Effect.fn("OrchestratorMcpService.readTask")(function* ( scope: McpThreadInvocationScope, taskId: NodeId, @@ -1820,10 +1848,7 @@ const make = Effect.gen(function* () { candidate.threadId === scope.thread.threadId, ); if (task === undefined || (task.childThreadId === null && task.remoteChild === undefined)) { - return yield* failure( - "task_not_found", - `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`, - ); + return yield* taskNotFound(scope, taskId); } if (task.childThreadId === null) { return yield* readRemoteTask(scope, task, waitTimedOut, acknowledgeTerminal); @@ -3006,10 +3031,7 @@ const make = Effect.gen(function* () { task.remoteChild !== undefined, ); if (remoteTask === undefined) { - return yield* failure( - "task_not_found", - `Delegated task ${input.taskId} does not belong to thread ${scope.thread.threadId}.`, - ); + return yield* taskNotFound(scope, input.taskId); } return yield* remoteDelegation.cancel(scope, remoteTask, input); } From 2251de4d2e61f921b90fb7bfdabef8b1a34d8803 Mon Sep 17 00:00:00 2001 From: Abhiram Kakarla <22UKakarlaA@qerdp.co.uk> Date: Sun, 22 Nov 2026 15:23:05 +0000 Subject: [PATCH 079/162] fix(gitlab): find merge requests opened from a fork (#40894) Co-authored-by: Abhiram-745 <237478249+Abhiram-745@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/server/GitLabCli.ts | 46 +++++++++- .../GitLabSourceControlProvider.git.test.ts | 91 +++++++++++++++++++ .../GitLabSourceControlProvider.test.ts | 7 ++ .../src/server/GitLabSourceControlProvider.ts | 16 +++- .../src/server/gitLabMergeRequests.ts | 20 ++++ 5 files changed, 173 insertions(+), 7 deletions(-) diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.ts index b528c1ced5a8a..04a633bba7096 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.ts @@ -21,6 +21,8 @@ import * as SourceControlHost from "@t3tools/source-control-core/server/SourceCo import { decodeGitLabMergeRequestJson, decodeGitLabMergeRequestListJson, + type NormalizedGitLabMergeRequestRecord, + withSourceProjectPath, } from "./gitLabMergeRequests.ts"; import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; @@ -377,6 +379,10 @@ const decodeGitLabMergeRequestProject = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })), ); +const decodeGitLabProjectPath = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ path_with_namespace: TrimmedNonEmptyString })), +); + const RawGitLabNamespaceSchema = Schema.Struct({ id: Schema.Number, }); @@ -559,6 +565,35 @@ export const make = Effect.gen(function* () { ), ); + // glab's MR JSON names a fork's source project only by `source_project_id`. + const resolveSourceProjectPaths = Effect.fn("GitLabCli.resolveSourceProjectPaths")(function* ( + cwd: string, + records: ReadonlyArray, + paths: Map, + ) { + const ids = new Set(); + for (const record of records) { + const id = record.unresolvedSourceProjectId; + if (id !== undefined && !paths.has(id)) ids.add(id); + } + yield* Effect.forEach( + ids, + (id) => + execute({ cwd, args: ["api", `projects/${id}`] }).pipe( + Effect.flatMap((result) => decodeGitLabProjectPath(result.stdout.trim())), + Effect.map((project) => project.path_with_namespace), + Effect.orElseSucceed(() => null), + Effect.map((path) => void paths.set(id, path)), + ), + { concurrency: 8, discard: true }, + ); + return records.map((record) => + record.unresolvedSourceProjectId === undefined + ? record + : withSourceProjectPath(record, paths.get(record.unresolvedSourceProjectId) ?? null), + ); + }); + return GitLabCli.of({ execute, listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function* (input) { @@ -566,6 +601,7 @@ export const make = Effect.gen(function* () { let pageSize = limit; let page = 1; const items: GitLabMergeRequestSummary[] = []; + const sourceProjectPaths = input.source?.owner ? new Map() : null; while (items.length < limit) { const result = yield* execute({ cwd: input.cwd, @@ -600,7 +636,11 @@ export const make = Effect.gen(function* () { cause: Result.isFailure(decoded) ? decoded.failure : "MR list output was truncated", }); } - items.push(...decoded.success.map(toSummaryWithOptionalUpdatedAt)); + // Only a fork head can match a fork's merge request, so other lookups skip the API calls. + const records = sourceProjectPaths + ? yield* resolveSourceProjectPaths(input.cwd, decoded.success, sourceProjectPaths) + : decoded.success; + items.push(...records.map(toSummaryWithOptionalUpdatedAt)); // Count raw entries: the decoder drops invalid ones, which would end paging early. const entries = decodeJsonArray(raw); if ( @@ -635,7 +675,9 @@ export const make = Effect.gen(function* () { ); } - return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success)); + return resolveSourceProjectPaths(input.cwd, [decoded.success], new Map()).pipe( + Effect.map(([record]) => toSummaryWithOptionalUpdatedAt(record!)), + ); }), ), ), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts index 7038e6a82d630..abd2f7b82f218 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts @@ -106,6 +106,97 @@ it.effect("lists a nested-group fork's merge requests by source branch and names }), ); +// Real `glab mr list --output json` marshals client-go's BasicMergeRequest: a fork MR names its +// source project only by `source_project_id`, never by a `source_project` path. +it.effect("names a fork merge request's source project from real glab list output", () => + Effect.gen(function* () { + const branch = "feature/fork-work"; + const mergeRequest = (iid: number, sourceProjectId: number) => ({ + id: 9000 + iid, + iid, + project_id: 100, + title: `Work ${iid}`, + state: "opened", + target_branch: "main", + source_branch: branch, + source_project_id: sourceProjectId, + target_project_id: 100, + draft: false, + sha: "0123456789abcdef0123456789abcdef01234567", + updated_at: "2026-04-07T15:00:00.000Z", + references: { short: `!${iid}`, relative: `!${iid}`, full: `group/upstream!${iid}` }, + web_url: `https://gitlab.com/group/upstream/-/merge_requests/${iid}`, + }); + const output = JSON.stringify([ + mergeRequest(1, 101), + mergeRequest(2, 101), + mergeRequest(3, 100), + mergeRequest(4, 102), + ]); + const apiCalls: ReadonlyArray[] = []; + const provider = yield* GitLabSourceControlProvider.make.pipe( + Effect.provide( + GitLabCli.layer.pipe( + Layer.provideMerge( + TestSourceControlHost.layer({ + process: { + run: (input) => + Effect.sync(() => { + if (input.args[0] !== "api") return TestSourceControlHost.processOutput(output); + apiCalls.push(input.args); + return TestSourceControlHost.processOutput( + input.args[1] === "projects/101" + ? JSON.stringify({ id: 101, path_with_namespace: "alice/upstream" }) + : "not json", + ); + }), + }, + }), + ), + Layer.provide(FileSystem.layerNoop({})), + ), + ), + ); + + const upstreamHead = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: branch, + state: "open", + limit: 20, + }); + expect(upstreamHead[0]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toEqual([]); + + const changeRequests = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: `alice:${branch}`, + state: "open", + limit: 20, + }); + // GitManager drops a cross-repository MR whose head project is unnamed. + expect(changeRequests).toMatchObject([ + { + number: 1, + isCrossRepository: true, + headRepositoryNameWithOwner: "alice/upstream", + headRepositoryOwnerLogin: "alice", + }, + { number: 2, isCrossRepository: true, headRepositoryNameWithOwner: "alice/upstream" }, + { number: 3, isCrossRepository: false }, + { number: 4, isCrossRepository: true }, + ]); + expect(changeRequests[2]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(changeRequests[3]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toHaveLength(2); + expect(apiCalls).toEqual( + expect.arrayContaining([ + ["api", "projects/101"], + ["api", "projects/102"], + ]), + ); + }), +); + const withRepository = ( test: (input: { readonly git: (...args: string[]) => Effect.Effect; diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts index 8e5077044c6b3..c5a2d56037172 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts @@ -210,6 +210,13 @@ it.effect( headSelectors: ["octocat:feature", "feature"], state: "open", }), + { headSelectors: ["octocat:feature"], limit: 100 }, + ); + assert.deepStrictEqual( + provider.headBranchProbe?.({ + headSelectors: ["feature", "octocat:feature"], + state: "open", + }), { headSelectors: ["feature"], limit: 100 }, ); }), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts index a7d5b71ca47d3..2a2d4ac3e199c 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts @@ -211,11 +211,17 @@ export const make = Effect.gen(function* () { return SourceControlProvider.SourceControlProvider.of({ kind: SourceControlProviderKind.make("gitlab"), - // GitLab lists fork merge requests by source branch with no owner filter, so read a full page. - headBranchProbe: ({ headSelectors }) => ({ - headSelectors: headSelectors.filter((selector) => !selector.includes(":")), - limit: 100, - }), + // GitLab lists fork merge requests by source branch with no owner filter, so read a full page + // once per branch. The first selector wins: GitManager puts `owner:branch` first for a fork + // head, which tells the list to name fork source projects. + headBranchProbe: ({ headSelectors }) => { + const byBranch = new Map(); + for (const selector of headSelectors) { + const branch = SourceControlProvider.sourceBranch({ headSelector: selector }); + if (!byBranch.has(branch)) byBranch.set(branch, selector); + } + return { headSelectors: [...byBranch.values()], limit: 100 }; + }, readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")( function ({ cwd, treeish }) { return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute); diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts index ef4438f5ff3ee..a40abd786cf85 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts @@ -23,6 +23,8 @@ export interface NormalizedGitLabMergeRequestRecord { readonly isCrossRepository?: boolean; readonly headRepositoryNameWithOwner?: string | null; readonly headRepositoryOwnerLogin?: string | null; + /** Set when a cross-repository MR names its source project only by id. */ + readonly unresolvedSourceProjectId?: number; } const GitLabProjectReferenceSchema = Schema.Struct({ @@ -122,6 +124,24 @@ function normalizeGitLabMergeRequestRecord( ...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}), ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + ...(isCrossRepository === true && + !sourceProjectPath && + typeof raw.source_project_id === "number" + ? { unresolvedSourceProjectId: raw.source_project_id } + : {}), + }; +} + +export function withSourceProjectPath( + record: NormalizedGitLabMergeRequestRecord, + sourceProjectPath: string | null, +): NormalizedGitLabMergeRequestRecord { + const { unresolvedSourceProjectId: _, ...resolved } = record; + const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath); + return { + ...resolved, + ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), }; } From 2c4310eb061373bb1c6ccefe6dafd0500ee8f5e3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 07:29:08 -0800 Subject: [PATCH 080/162] fix(web): pasting a chat message with text and a picture keeps both (#40909) --- apps/web/src/components/chat/ChatComposer.tsx | 23 ++++++++---- .../chat/composerAttachmentFiles.test.ts | 7 ++++ .../chat/composerAttachmentFiles.ts | 35 ++++++++++++++----- 3 files changed, 50 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 6fb651c3471f6..af4871b451932 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -133,7 +133,8 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, - isImageOnlyClipboardHtml, + clipboardHtmlImageContent, + imagesToAttachBesidePastedText, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -2947,18 +2948,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const pastedContext = !isLiteralPendingAnswer && (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; + const canAttachFiles = !pastedContext && activeThreadId !== null && files.length > 0; + const htmlImageContent = + canAttachFiles && plainText.length > 0 + ? clipboardHtmlImageContent(event.clipboardData.getData("text/html")) + : "none"; if ( folders.length > 0 || - (!pastedContext && - activeThreadId && - files.length > 0 && + (canAttachFiles && shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment, - htmlIsOnlyImage: - plainText.length > 0 && - isImageOnlyClipboardHtml(event.clipboardData.getData("text/html")), + htmlIsOnlyImage: htmlImageContent === "only-image", })) ) { event.preventDefault(); @@ -2971,6 +2973,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } if (pastedContext) return; + const imagesBesideText = imagesToAttachBesidePastedText({ + files, + plainText, + bypassAutoAttachment, + htmlHasImageAndText: htmlImageContent === "image-and-text", + }); + if (imagesBesideText.length > 0) void addComposerAttachments(imagesBesideText); if (!foldPastedText(plainText, bypassAutoAttachment)) { return; } diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index f842566d7cd60..ac43d667d80ca 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts @@ -13,6 +13,7 @@ import { composerFileAttachmentMimeType, fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, + imagesToAttachBesidePastedText, normalizeComposerImageFileMimeType, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; @@ -141,6 +142,12 @@ describe("composer attachment files", () => { expect(shouldHandleComposerAttachmentPaste({ files: [image], plainText: "image.png" })).toBe( true, ); + // A QQ or WeChat message has its text beside an in the HTML: the image attaches too. + const message = { files: [image], plainText: "Look at this", htmlHasImageAndText: true }; + expect(shouldHandleComposerAttachmentPaste(message)).toBe(false); + expect(imagesToAttachBesidePastedText(message)).toEqual([image]); + expect(imagesToAttachBesidePastedText({ ...message, htmlHasImageAndText: false })).toEqual([]); + expect(imagesToAttachBesidePastedText({ ...message, bypassAutoAttachment: true })).toEqual([]); }); it("preserves text when the clipboard also includes generic image files", () => { diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 191c5841185ff..538d2dfd67304 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -247,11 +247,33 @@ function isOnlyFileNames(text: string, files: ReadonlyArray): boolean { .every((line) => names.has(line)); } -/** A browser's Copy Image puts only an in text/html; rich text sources put the text there. */ -export function isImageOnlyClipboardHtml(html: string): boolean { - if (html.length === 0) return false; +/** + * A browser's Copy Image puts only an in text/html; a chat message (QQ, WeChat) puts its text + * beside the ; rich text sources (Word, Pages) put only the text there. + */ +export function clipboardHtmlImageContent(html: string): "only-image" | "image-and-text" | "none" { + if (html.length === 0) return "none"; const body = new DOMParser().parseFromString(html, "text/html").body; - return body.querySelector("img") !== null && (body.textContent ?? "").trim().length === 0; + if (body.querySelector("img") === null) return "none"; + return (body.textContent ?? "").trim().length === 0 ? "only-image" : "image-and-text"; +} + +function isPastedImageFile(file: File): boolean { + const classification = classifyComposerAttachmentFile(file); + return classification === "image" || classification === "unsupported-image"; +} + +/** The images of a message copied with its text: they attach while the text pastes as text. */ +export function imagesToAttachBesidePastedText(input: { + readonly files: ReadonlyArray; + readonly plainText: string; + readonly bypassAutoAttachment?: boolean; + readonly htmlHasImageAndText: boolean; +}): File[] { + if (input.bypassAutoAttachment || input.plainText.length === 0 || !input.htmlHasImageAndText) { + return []; + } + return input.files.filter(isPastedImageFile); } export function shouldHandleComposerAttachmentPaste(input: { @@ -269,10 +291,7 @@ export function shouldHandleComposerAttachmentPaste(input: { ) { return true; } - const hasImage = input.files.some((file) => { - const classification = classifyComposerAttachmentFile(file); - return classification === "image" || classification === "unsupported-image"; - }); + const hasImage = input.files.some(isPastedImageFile); if (input.plainText.length === 0) { return hasImage || input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); } From 344de5fe8e70e9eeaacaedc34e7aa5e2a29287d1 Mon Sep 17 00:00:00 2001 From: Lokkuchakreshkumar Date: Sun, 22 Nov 2026 21:53:23 +0530 Subject: [PATCH 081/162] fix(antigravity): bound silent post-settle background command holds (#40858) Co-authored-by: LVC-Chakresh Co-authored-by: Julius Marminge --- .../Adapters/AntigravityAdapterV2.test.ts | 119 ++++++++++++++++++ .../Adapters/AntigravityAdapterV2.ts | 7 ++ .../src/provider/acp/AntigravityProtocol.ts | 6 + packages/provider-acp/src/server/adapter.ts | 57 ++++++++- 4 files changed, 187 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..5cbb4975e5e57 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1327,6 +1327,16 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); yield* startTurn(1, false); yield* throughPromptSettled; + // Progress keeps a command past the post-settle hold bound, which counts silence only. + for (const minute of [10, 20, 30]) { + yield* TestClock.adjust("10 minutes"); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "in_progress", + rawOutput: { output: `fetched ${minute} pages` }, + }); + } yield* TestClock.adjust("10 minutes"); yield* send({ sessionUpdate: "tool_call_update", @@ -1349,6 +1359,115 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // A command whose terminal update never arrives would hold the run in Working forever with + // an empty pending list and a finished reply above Stop. + it.effect("settles a silent background command after the post-settle hold timeout", () => + Effect.gen(function* () { + const { command, offers, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + const prompt = yield* throughPromptSettled; + + // A running tool keeps the inactivity watchdog re-armed, so 20 silent minutes do not + // settle this run on their own. + yield* TestClock.adjust("20 minutes"); + yield* TestClock.adjust("11 minutes"); + const run = yield* until((event) => event.type === "turn.terminal"); + const terminal = run.at(-1); + assert.equal( + terminal?.type === "turn.terminal" && terminal.status, + "completed", + "the bounded hold finalizes the turn instead of leaving it running forever", + ); + assert.equal(terminal?.type === "turn.terminal" && terminal.failure, null); + assert.lengthOf(offers, 0, "a silent command produces no wake on its own"); + const commandItem = [...prompt, ...run].findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.isTrue( + commandItem?.type === "turn_item.updated" && commandItem.turnItem.status === "completed", + "the silent command is no longer left as live activity on a settled run", + ); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("keeps a silent scheduled wake in its run past the command hold bound", () => + Effect.gen(function* () { + const { usage, offers, send, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({}, undefined, undefined, { + initialToolCalls: [ + { + sessionUpdate: "tool_call", + toolCallId: "call_schedule", + kind: "other", + title: "Run schedule", + status: "in_progress", + rawInput: { DurationSeconds: 3600, Prompt: "Continue the task" }, + }, + ], + }); + yield* startTurn(1, false); + yield* throughPromptSettled; + yield* TestClock.adjust("61 minutes"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "call_schedule", + status: "completed", + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Picked the task back up." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const run = yield* until((event) => event.type === "turn.terminal"); + assert.include( + JSON.stringify(run), + "Picked the task back up.", + "the wake reply stays in the run", + ); + assert.lengthOf(offers, 0); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("keeps an unanswered question open past the command hold bound", () => + Effect.gen(function* () { + const { command, usage, send, startTurn, until, throughPromptSettled, requestPermission } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + yield* throughPromptSettled; + const question = yield* requestPermission( + { + sessionId: "mock-session-1", + toolCall: { toolCallId: "interaction_1", kind: "other", title: "Which port?" }, + options: [ + { optionId: "3000", name: "3000", kind: "allow_once" }, + { optionId: "8080", name: "8080", kind: "allow_once" }, + ], + }, + { requestId: "question-1", method: "session/request_permission" }, + ).pipe(Effect.forkScoped({ startImmediately: true })); + yield* TestClock.adjust("31 minutes"); + yield* Fiber.interrupt(question); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Here is the chart." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const run = yield* until((event) => event.type === "turn.terminal"); + assert.include(JSON.stringify(run), "Here is the chart.", "the question kept the run open"); + }).pipe(Effect.provide(layerSession)), + ); + // Command 2 finishes during reply 1; agy dequeues command 2 after reply 1's usage_update and // needs >3 s before streaming reply 2. Wait for reply 2 (bounded by the 2-minute quiet limit), // but still finalize at 3 s when both commands were batched into reply 1. diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 3f629c813b615..c20afa04e31b8 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -41,6 +41,7 @@ import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTur import { antigravityApprovalOptions, antigravityToolOutlivesPrompt, + antigravityCommandOutlivesPrompt, antigravitySubagentOutput, classifyAntigravitySubagentToolCall, extractAntigravityUserInputQuestion, @@ -244,6 +245,12 @@ export function makeAntigravityAcpAdapterFlavor( wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true, toolOutlivesPrompt: antigravityToolOutlivesPrompt, + // agy sometimes loses the terminal update or wake for a background command, which would + // hold the turn in Working forever. 30 minutes still leaves long commands room. + postSettleCommandHold: { + timeout: "30 minutes", + isCommand: antigravityCommandOutlivesPrompt, + }, // session/cancel ends the agent's running commands, so only Stop sends it once the prompt // has ended. A message sent while a command runs leaves the command alone. preserveRuntimeOnSettledInterrupt: true, diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index c718667dcf42e..2e59a78e376b4 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -55,6 +55,12 @@ const ANTIGRAVITY_SCHEDULE_TITLES = new Set(["Run schedule", "Running schedule"] */ export function antigravityToolOutlivesPrompt(toolCall: AcpToolCallState): boolean { if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return true; + return antigravityCommandOutlivesPrompt(toolCall); +} + +/** A non-daemon command the agent awaits; unlike a schedule, it reports progress while it runs. */ +export function antigravityCommandOutlivesPrompt(toolCall: AcpToolCallState): boolean { + if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return false; const input = toolCall.data.rawInput; return toolCall.kind === "execute" && !(Predicate.isObject(input) && input.IsDaemon === true); } diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 21fe311588906..908c99e4eaeb3 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -637,6 +637,15 @@ export interface AcpAdapterV2Flavor { * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then. */ readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean; + /** + * Finalize a settled turn held only by running commands once the session has been silent for + * `timeout`, so a command that never reports back cannot leave the thread in Working forever. + * Other holds (questions, schedules, subagents) keep the turn open as before. + */ + readonly postSettleCommandHold?: { + readonly timeout: Duration.Input; + readonly isCommand: (toolCall: AcpToolCallState) => boolean; + }; readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; @@ -2742,7 +2751,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const notePromptProgress = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (notification?: EffectAcpSchema.SessionNotification) { - if (promptInactivityTimeoutMillis === undefined) return; + if ( + promptInactivityTimeoutMillis === undefined && + flavor.postSettleCommandHold === undefined + ) { + return; + } if ( notification !== undefined && !ACP_PROMPT_ACTIVITY_UPDATES.has(notification.update.sessionUpdate) @@ -4274,11 +4288,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const isMonitorEndNoticeText = (text: string): boolean => /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); - const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + const hasDeferredBackgroundWork = ( + context: ActiveAcpTurn, + ignoreTool?: (tool: AcpToolCallState) => boolean, + ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { + if (ignoreTool?.(tool) === true) continue; if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool)) return true; } @@ -8835,6 +8853,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void; }); + const schedulePostSettleHoldExpiry = Effect.fn("AcpAdapterV2.schedulePostSettleHoldExpiry")( + function* (context: ActiveAcpTurn) { + const hold = flavor.postSettleCommandHold; + if (hold === undefined) return; + if (!context.promptSettled || context.finalized) return; + const timeoutMillis = Duration.toMillis(hold.timeout); + const isRunningCommand = (tool: AcpToolCallState) => + toolStatus(tool.status) === "running" && hold.isCommand(tool); + let quietSince = yield* Clock.currentTimeMillis; + // Armed even without a command yet: a pending reply can still start one. + yield* Effect.gen(function* () { + while (!context.finalized) { + quietSince = Math.max(quietSince, context.lastProgressAt); + const now = yield* Clock.currentTimeMillis; + const remaining = quietSince + timeoutMillis - now; + if (remaining > 0) { + yield* Effect.sleep(Duration.millis(remaining)); + continue; + } + if ( + context.tools.values().some(isRunningCommand) && + !hasDeferredBackgroundWork(context, isRunningCommand) + ) { + yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); + return; + } + // Something else still holds the turn; count silence again once it clears. + quietSince = now; + } + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); + }, + ); + const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { @@ -9265,6 +9316,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (context.finalized) return; if (deferredBackgroundWork || pendingReply) { yield* closeTextStreams(context); + yield* schedulePostSettleHoldExpiry(context); if (pendingReply) { context.replyOpen = true; yield* scheduleDeferredFinalize(context); @@ -9665,6 +9717,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } if (!context.finalized) { + yield* schedulePostSettleHoldExpiry(context); if (hasDeferredBackgroundWork(context)) { yield* rearmDeferredFinalize(context); } else { From 5ddcc2598d0338614c2b2ea84da9470fd16be0da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 08:31:10 -0800 Subject: [PATCH 082/162] fix(desktop): WSL is not offered or started when only the Windows install stub exists (#40918) --- .../src/wsl/DesktopWslEnvironment.test.ts | 42 ++++++++++++++++++- apps/desktop/src/wsl/DesktopWslEnvironment.ts | 42 ++++++++++++++++++- 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index a563b6a4ee3a7..470091f334fb7 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -555,8 +555,40 @@ describe("parseResolvedPath", () => { // Path.layer joins with POSIX separators here, so the test windir is a POSIX path. const WSL_EXE = "/windows/System32/wsl.exe"; +const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService"; +const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager"; + +const registrySpawner = (keys: ReadonlyArray) => + ChildProcessSpawner.make((command) => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Effect.succeed( + ChildProcessSpawner.ExitCode( + command._tag === "StandardCommand" && + command.command === "reg.exe" && + keys.some((key) => command.args.includes(key)) + ? 0 + : 1, + ), + ), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), + ); -const isAvailable = (policy?: Parameters[0]) => +const isAvailable = ( + policy?: Parameters[0], + serviceKeys: ReadonlyArray = [STORE_SERVICE], +) => makeIsAvailable("win32", "/windows").pipe( Effect.provide( Layer.mergeAll( @@ -565,9 +597,17 @@ const isAvailable = (policy?: Parameters[ DesktopManagedPolicy.layerTest(policy), ), ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, registrySpawner(serviceKeys)), ); describe("makeIsAvailable", () => { + it.effect("needs a registered WSL service, not just the System32 install stub", () => + Effect.gen(function* () { + assert.isFalse(yield* isAvailable(undefined, [])); + assert.isTrue(yield* isAvailable(undefined, [INBOX_SERVICE])); + }), + ); + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => Effect.gen(function* () { assert.isTrue(yield* isAvailable()); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index f1d2fccde537b..9d9540a65dc7d 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1119,13 +1119,50 @@ const getUserHomeImpl = ( Effect.orElseSucceed(() => Option.none()), ); +// Store/MSI WSL registers WSLService and inbox WSL registers LxssManager; either key means installed. +const WSL_SERVICE_KEYS = [ + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService", + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager", +] as const; +const SERVICE_QUERY_TIMEOUT = Duration.seconds(5); + +const wslServiceRegistered = Effect.scoped( + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const registered = yield* Effect.forEach( + WSL_SERVICE_KEYS, + (key) => + spawner + .spawn( + ChildProcess.make("reg.exe", ["query", key], { + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + killSignal: "SIGTERM", + forceKillAfter: PROCESS_TERMINATE_GRACE, + }), + ) + .pipe(Effect.flatMap((handle) => handle.exitCode)), + { concurrency: "unbounded" }, + ); + return registered.some((exitCode) => (exitCode as unknown as number) === 0); + }), +).pipe( + Effect.timeoutOption(SERVICE_QUERY_TIMEOUT), + Effect.map(Option.getOrElse(() => false)), + Effect.orElseSucceed(() => false), +); + export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* ( platform: NodeJS.Platform, windir: string, ): Effect.fn.Return< boolean, never, - FileSystem.FileSystem | Path.Path | DesktopManagedPolicy.DesktopManagedPolicy + | FileSystem.FileSystem + | Path.Path + | DesktopManagedPolicy.DesktopManagedPolicy + | ChildProcessSpawner.ChildProcessSpawner > { if (platform !== "win32") return false; const path = yield* Path.Path; @@ -1134,6 +1171,8 @@ export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable" if (!(yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false)))) { return false; } + // System32\wsl.exe is also an install stub on Windows without WSL, so check for its service. + if (!(yield* wslServiceRegistered)) return false; // A server in WSL reads Linux's policy, never this machine's, so a managed machine runs none. return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( Effect.map((found) => found === undefined), @@ -1245,6 +1284,7 @@ export const layer = Layer.effect( // Cache availability so synchronous IPC bootstrap can read it without yielding to filesystem I/O. const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(Path.Path, environment.path), Effect.provideService( DesktopManagedPolicy.DesktopManagedPolicy, From ad446450e1cd66763cf03ed5c4b012913826f5d7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 08:33:25 -0800 Subject: [PATCH 083/162] fix(server): idle /ws connections behind a reverse proxy no longer drop every 60s (#40932) --- apps/server/src/socketHeartbeat.test.ts | 39 +++++++++++++++++++++++++ apps/server/src/socketHeartbeat.ts | 27 +++++++++++++++++ apps/server/src/ws.ts | 30 ++++++++++--------- 3 files changed, 82 insertions(+), 14 deletions(-) create mode 100644 apps/server/src/socketHeartbeat.test.ts create mode 100644 apps/server/src/socketHeartbeat.ts diff --git a/apps/server/src/socketHeartbeat.test.ts b/apps/server/src/socketHeartbeat.test.ts new file mode 100644 index 0000000000000..2cb002bbf8862 --- /dev/null +++ b/apps/server/src/socketHeartbeat.test.ts @@ -0,0 +1,39 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Scope from "effect/Scope"; +import * as Socket from "effect/socket/Socket"; +import * as TestClock from "effect/testing/TestClock"; + +import { + SOCKET_HEARTBEAT_FRAME, + SOCKET_HEARTBEAT_INTERVAL, + withSocketHeartbeat, +} from "./socketHeartbeat.ts"; + +describe("withSocketHeartbeat", () => { + it.effect("writes a heartbeat each interval until the writer's scope closes", () => + Effect.gen(function* () { + const written: Array = []; + const socket = withSocketHeartbeat( + Socket.make({ + reader: Effect.never, + writer: Effect.succeed({ + write: (chunk) => Effect.sync(() => void written.push(chunk)), + writeAll: (chunks) => Effect.sync(() => void written.push(...chunks)), + }), + }), + ); + const scope = yield* Scope.make(); + yield* Scope.provide(socket.writer, scope); + + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + assert.deepStrictEqual(written, [SOCKET_HEARTBEAT_FRAME, SOCKET_HEARTBEAT_FRAME]); + + yield* Scope.close(scope, Exit.void); + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + assert.strictEqual(written.length, 2); + }), + ); +}); diff --git a/apps/server/src/socketHeartbeat.ts b/apps/server/src/socketHeartbeat.ts new file mode 100644 index 0000000000000..6ffd9c9cf785c --- /dev/null +++ b/apps/server/src/socketHeartbeat.ts @@ -0,0 +1,27 @@ +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Socket from "effect/socket/Socket"; + +// Reverse proxies close a socket after 60 seconds without upstream bytes +// (nginx proxy_read_timeout, AWS ALB), and a suspended client stops pinging. +export const SOCKET_HEARTBEAT_INTERVAL = Duration.seconds(20); + +// RPC clients count any decoded frame as liveness and ignore unsolicited pongs. +export const SOCKET_HEARTBEAT_FRAME = '{"_tag":"Pong"}'; + +/** Server side: writes a heartbeat frame on an interval for as long as the writer is open. */ +export function withSocketHeartbeat(socket: Socket.Socket): Socket.Socket { + return Socket.make({ + reader: socket.reader, + writer: Effect.tap(socket.writer, (writer) => + writer + .write(SOCKET_HEARTBEAT_FRAME) + .pipe( + Effect.delay(SOCKET_HEARTBEAT_INTERVAL), + Effect.forever, + Effect.ignore, + Effect.forkScoped, + ), + ), + }); +} diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ddd07fcfad656..d1db4372ab871 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -201,6 +201,7 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { makePrepareTerminalLaunch } from "./workspace/restoreMissingWorktree.ts"; import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtocol.ts"; +import { withSocketHeartbeat } from "./socketHeartbeat.ts"; import * as ServerBrowser from "./preview/ServerBrowser.ts"; import * as DeviceService from "./device/DeviceService.ts"; import { remoteSshDeviceHosts } from "./device/localSshDeviceHost.ts"; @@ -3826,20 +3827,21 @@ export const layer = Layer.unwrap( ), ), ); - const framedRpcWebSocketHttpEffect = url.value.searchParams.has( - SOCKET_FRAME_PARTS_QUERY_PARAM, - ) - ? rpcWebSocketHttpEffect.pipe( - Effect.provideService( - HttpServerRequest.HttpServerRequest, - // The RPC server upgrades the request itself, so its socket is - // wrapped through the request it reads. - Object.create(request, { - upgrade: { value: Effect.map(request.upgrade, splitLargeSocketFrames) }, - }), - ), - ) - : rpcWebSocketHttpEffect; + const splitFrames = url.value.searchParams.has(SOCKET_FRAME_PARTS_QUERY_PARAM); + const framedRpcWebSocketHttpEffect = rpcWebSocketHttpEffect.pipe( + Effect.provideService( + HttpServerRequest.HttpServerRequest, + // The RPC server upgrades the request itself, so its socket is + // wrapped through the request it reads. + Object.create(request, { + upgrade: { + value: Effect.map(request.upgrade, (socket) => + withSocketHeartbeat(splitFrames ? splitLargeSocketFrames(socket) : socket), + ), + }, + }), + ), + ); return yield* Effect.acquireUseRelease( sessions.markConnected(session.sessionId), () => From cc4bb17955287e5a7ad2a64b05f491879ee888fa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 08:42:51 -0800 Subject: [PATCH 084/162] fix(server): thread reads no longer attribute T3 Code's compact-before-send /compact to the user (#40934) --- apps/server/src/cli/thread.ts | 7 +- .../OrchestratorMcpService.activity.test.ts | 129 ++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 4 +- 3 files changed, 138 insertions(+), 2 deletions(-) diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 09ee65c32172b..48d62fb4575b7 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -1024,7 +1024,12 @@ const threadShowCommand = Command.make("show", { const messages = yield* Effect.forEach(latest, (item) => readFullText(tools, threadId, item).pipe( Effect.map((text) => ({ - role: item.type === "user_message" ? "user" : "assistant", + role: + item.type === "assistant_message" + ? "assistant" + : item.createdBy === "system" + ? "system" + : "user", runId: item.runId, text, })), diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index a0953eb509e5f..cbe4be1e4b42f 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + MessageId, NodeId, type OrchestratorMcpThreadReadResult, type OrchestrationV2ThreadProjection, @@ -431,6 +432,134 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn }).pipe(Effect.provide(layer), Effect.runPromise); }); +it("readThread does not attribute the /compact T3 Code sends before a stale send to the user", async () => { + const compactRunId = RunId.make("run-mcp-compact-on-return"); + const sendRunId = RunId.make("run-mcp-held-send"); + const compactMessageId = MessageId.make("message-mcp-compact-on-return"); + const sendMessageId = MessageId.make("message-mcp-held-send"); + const projection = { + thread: baseThread({ + threadId: parentThreadId, + title: "Parent", + instanceId: parentInstanceId, + model: "gpt-5.4", + }), + runs: [ + makeRun({ id: compactRunId, ordinal: 1, status: "completed" }), + makeRun({ id: sendRunId, ordinal: 2, status: "completed" }), + ], + visibleTurnItems: [], + providerTurns: [], + runtimeRequests: [], + messages: [ + { + id: compactMessageId, + threadId: parentThreadId, + runId: compactRunId, + role: "user", + text: "/compact", + attachments: [], + createdBy: "user", + creationSource: "web", + idleCompaction: "onReturn", + }, + { + id: sendMessageId, + threadId: parentThreadId, + runId: sendRunId, + role: "user", + text: "use webgpu", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + ], + contextTransfers: [], + subagents: [], + updatedAt: now, + } as unknown as OrchestrationV2ThreadProjection; + const userRow = (position: number, runId: RunId, messageId: MessageId, text: string) => ({ + position, + visibility: "visible", + sourceThreadId: parentThreadId, + sourceItemId: TurnItemId.make(`turn-item-mcp-user-${position}`), + item: { + type: "user_message", + runId, + messageId, + status: "completed", + title: null, + text, + attachments: [], + updatedAt: now, + }, + }); + const rows = [ + userRow(0, compactRunId, compactMessageId, "/compact"), + { + position: 1, + visibility: "visible", + sourceThreadId: parentThreadId, + sourceItemId: TurnItemId.make("turn-item-mcp-compaction"), + item: { + type: "compaction", + runId: compactRunId, + status: "completed", + title: null, + summary: "Context compacted", + updatedAt: now, + }, + }, + userRow(2, sendRunId, sendMessageId, "use webgpu"), + ]; + + const layer = layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getTimelinePage: () => + Effect.succeed({ + items: rows as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"], + totalItems: rows.length, + hasMore: false, + hasEarlier: false, + }), + getThreadRecords: () => Effect.succeed(projection), + getProjectThreadRecords: () => Effect.succeed(projection), + getRunCount: () => Effect.succeed(projection.runs.length), + getThreadShell: () => + Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell), + } satisfies Partial), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + } satisfies Partial), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({ + list: () => Effect.succeed({ tasks: [] }), + } satisfies Partial), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + } satisfies Partial), + NodeCrypto.layer, + ), + ), + ); + + await Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + for (const view of ["activity", "messages"] as const) { + const result = yield* service.readThread(makeScope(), { threadId: parentThreadId, view }); + const fromUser = result.items.filter( + (item) => item.type === "user_message" && item.createdBy === "user", + ); + expect(fromUser.map((item) => item.text)).toEqual(["use webgpu"]); + } + }).pipe(Effect.provide(layer), Effect.runPromise); +}); + it("readThread returns the newest items that fit the response budget", async () => { const projection = { thread: baseThread({ diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index f9ad32a6e1d3e..156555c74d695 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1,6 +1,7 @@ import { CommandId, type RunId, + idleCompactionOf, isProviderAvailable, MessageId, type ModelSelection, @@ -1228,7 +1229,8 @@ function timelineItem(input: { ...(input.row.item.type === "subagent" ? { subagentId: input.row.item.subagentId } : {}), runId: input.row.item.runId, messageId, - createdBy: message?.createdBy ?? null, + createdBy: + message === undefined ? null : idleCompactionOf(message) ? "system" : message.createdBy, creationSource: message?.creationSource ?? null, ...(message?.senderThreadId === undefined ? {} : { senderThreadId: message.senderThreadId }), type: input.row.item.type, From 9de4ec1bfa0b222e71f8fc2ed71257c1c1d1a281 Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:49:19 +0100 Subject: [PATCH 085/162] fix(web,mobile): @-file mentions show by name in message previews, not as raw links (#40924) --- .../threads/threadQueueControlPresentation.ts | 5 ++- .../src/components/chat/ComposerStashMenu.tsx | 5 ++- .../src/components/chat/QueuedRunsControl.tsx | 5 ++- .../components/sidebar/SidebarDraftBlock.tsx | 5 ++- .../src/operations/threadTitle.ts | 3 +- .../shared/src/composerInlineTokens.test.ts | 14 +++++++ packages/shared/src/composerInlineTokens.ts | 15 ++++++++ ...-message-shows-file-mention-by-name.e2e.ts | 37 +++++++++++++++++++ 8 files changed, 84 insertions(+), 5 deletions(-) create mode 100644 scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts diff --git a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts index 8a6ed2e03085a..50a004d679003 100644 --- a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts +++ b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts @@ -5,6 +5,7 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; export const REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL = msg("Remove queued message"); @@ -43,7 +44,9 @@ export function resolveThreadQueueRowControls(input: { displayText: isAttachmentOnlyBootstrapPrompt(input.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(input.text, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(input.text, (reference) => reference.label), + ), ).trim(), isEditing, }; diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index c55d843510080..46e3fec307bf1 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -3,6 +3,7 @@ import { BookmarkIcon, FileIcon, FileTextIcon } from "lucide-react"; import { memo, useEffect, useEffectEvent, useRef, useState, type RefObject } from "react"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { RelativeTime } from "../RelativeTime"; import { m, type MessageResolver } from "~/i18n/messages"; @@ -18,7 +19,9 @@ function missingImageCount(entry: PromptStashEntry): number { export function stashEntrySnippet(entry: PromptStashEntry, resolve: MessageResolver = m): string { const trimmed = assistantCitationsToPlainText( - replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + ), ) .trim() .replace(/\s+/g, " "); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index d8318b7279e7d..20ea71f88adcd 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -10,6 +10,7 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { parseGoalCommand, type ChatAttachment as ContractChatAttachment, @@ -272,7 +273,9 @@ export function QueuedRunsControl({ const previewText = isAttachmentOnlyBootstrapPrompt(item.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(item.text, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(item.text, (reference) => reference.label), + ), ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; // The server decides on the agent's text, and a goal command can stop the turn. diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 4cb082a1f7ddd..e0b0d92a764ac 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -3,6 +3,7 @@ import type { ContextMenuSource } from "@t3tools/contracts"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { T, useGT } from "gt-react"; import { SquarePenIcon, XIcon } from "lucide-react"; import { @@ -85,7 +86,9 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { const gt = useGT(); const promptPreview = assistantCitationsToPlainText( - replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + ), ) .trim() .split("\n", 1)[0] ?? ""; diff --git a/packages/client-runtime/src/operations/threadTitle.ts b/packages/client-runtime/src/operations/threadTitle.ts index 0f57de34036a5..bb1fcd7648dbf 100644 --- a/packages/client-runtime/src/operations/threadTitle.ts +++ b/packages/client-runtime/src/operations/threadTitle.ts @@ -3,6 +3,7 @@ import type { MFunctionType } from "gt-i18n/types"; import type { ChatAttachment } from "@t3tools/contracts"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { truncate } from "@t3tools/shared/String"; import { collectComposerModelMentions } from "../composerModelMentions.ts"; @@ -45,7 +46,7 @@ export function threadTitleTextFromPrompt( return reference.label; }); return ( - normalizeTitleSeed(modelMentionsAsSlugs(prose)) || + normalizeTitleSeed(modelMentionsAsSlugs(composerFileLinksToPlainText(prose))) || (imageIds.size > 0 ? attachedImagesTitle(imageIds.size, resolve) : "") ); } diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index 5317347aad13b..c8c17b84a9b7b 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import { collectComposerInlineTokens as collectWithoutMath, type CollectComposerInlineTokensOptions, + composerFileLinksToPlainText, composerMathRanges, } from "./composerInlineTokens.ts"; import { markdownMathRanges } from "./markdownMath.ts"; @@ -230,3 +231,16 @@ describe("collectComposerInlineTokens", () => { ).toEqual(["$x_i$"]); }); }); + +describe("composerFileLinksToPlainText", () => { + it("shows file mentions by name and leaves other links as written", () => { + const mentions = ["src/foo.ts", ".gitignore", "pkg/__init__.py", "docs/My File (draft).md"] + .map(serializeComposerFileLink) + .join(" "); + expect(composerFileLinksToPlainText(`Review ${mentions}`)).toBe( + "Review foo.ts .gitignore __init__.py My File (draft).md", + ); + const links = "See [docs](https://example.com) and [the config](src/config.ts)"; + expect(composerFileLinksToPlainText(links)).toBe(links); + }); +}); diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index b11a42b74a945..80a1b4d6916ae 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,3 +1,5 @@ +import { fileBasename } from "./path.ts"; + /** The formulas a Markdown parser finds in text, as source offsets. */ export type FindMathRanges = ( text: string, @@ -173,3 +175,16 @@ export function collectComposerInlineTokens( ) .sort((left, right) => left.start - right.start); } + +/** Shows each `@`-file link by its file name, as its composer chip does, for one-line previews. */ +export function composerFileLinksToPlainText(text: string): string { + let result = ""; + let cursor = 0; + // The composer reads a link as a mention only before whitespace, so one may end the text. + for (const token of collectMentionTokens(`${text} `)) { + if (!token.source.startsWith("[")) continue; + result += text.slice(cursor, token.start) + fileBasename(token.value); + cursor = token.end; + } + return result + text.slice(cursor); +} diff --git a/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts new file mode 100644 index 0000000000000..8ee5453bbba20 --- /dev/null +++ b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A queued message shows its @-file mention by name, not as a raw link", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "src/foo.ts": "export {};\n" }); + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Review @foo"); + await screen.getByRole("option", "foo.ts", { exact: false }).tap(); + await expect(composer).toContainText("foo.ts"); + + // The showcase recording streams for several seconds, long enough to queue behind its turn. + await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Show me again"])); + await screen.getByText("Working for", { exact: false }).waitFor(); + // Enter steers by default; the alternate send queues. + await browser.keyboard.press("ControlOrMeta+Enter"); + + const queued = screen.getByRole("listitem", "Queued message 1 of 1, not sent"); + await queued.waitFor(); + // Read the row once: the queued message sends, and its row goes, when the turn ends. + const text = await queued.textContent(); + await app.screenshot("queued-row"); + expect(text).toContain("Review foo.ts"); + }, +); From 7ddc81d639aa75ca6e0cbffb0f394ea3f0d83308 Mon Sep 17 00:00:00 2001 From: Matthew Waters Date: Sun, 22 Nov 2026 17:10:23 +0000 Subject: [PATCH 086/162] fix(web): tool calls stay grouped after a usage-limit pause again (#40905) --- apps/web/src/components/ChatView.tsx | 6 +++++ .../chat/MessagesTimeline.logic.test.ts | 24 ++++++++++++++++++- .../components/chat/MessagesTimeline.logic.ts | 11 +++++++-- .../src/components/chat/MessagesTimeline.tsx | 3 +++ 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d17af4f620755..4f1d764ffef29 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1085,6 +1085,11 @@ export default function ChatView(props: ChatViewProps) { recovery: activeThreadShell?.limitRecovery, snoozedUntil: activeThreadShell?.snoozedUntil, }); + // The run whose limit rows client-runtime hides (deriveUsageLimitNoticeRows). + const usageLimitRunId = + serverRuntime?.status === "failed" && serverRuntime.lastErrorClass === "usage_limit" + ? (serverLatestRun?.runId ?? null) + : null; const timelineThreadError = limitRecoveryRun !== null && visibleThreadError === serverRuntime?.lastError ? null @@ -3644,6 +3649,7 @@ export default function ChatView(props: ChatViewProps) { listRef={legendListRef} runs={serverProjection?.runs ?? []} latestRun={activeActivityRun} + usageLimitRunId={usageLimitRunId} announcedRun={announcedRun(activeActivityRun, serverProjection?.runs ?? [])} detailBehindShell={isDetailBehindShell( activeLatestRun, diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 0a703a675f0ac..76dc0aa6471bf 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -4744,7 +4744,29 @@ describe("failed turn transcript", () => { ); expect(work.at(-1)?.detail).toBe("The provider stopped this turn.\nRetry later."); expect(work.at(-1)?.createdAt).toBe("2026-09-20T12:00:00.000Z"); - if (isLatest) return; + if (isLatest) { + // The recovery notice hides the failure row; the run's work stays grouped. + const noticeRows = deriveMessagesTimelineRows({ + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: items.filter((row) => row.item.type !== "error"), + optimisticMessages: [], + }), + latestRun: { + runId, + status: "failed", + startedAt: DateTime.formatIso(at), + completedAt: DateTime.formatIso(at), + }, + usageLimitRunId: runId, + isWorking: false, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + expect(noticeRows.find((row) => row.kind === "work-toggle")).toEqual( + expect.objectContaining({ hiddenCount: 3, expanded: false }), + ); + return; + } const entriesWithoutTools = deriveTimelineEntriesFromVisibleTurnItems({ visibleTurnItems: items.filter((row) => row.item.type !== "command_execution"), optimisticMessages: [], diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index b00a48185b9db..2d920ad816277 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1056,8 +1056,9 @@ function failedTimelineRunIds( function itemizedFailedRunIds( entries: ReadonlyArray, failedRunIds: ReadonlySet, + usageLimitRunId: RunId | null, ) { - const usageLimited = new Set(); + const usageLimited = new Set(usageLimitRunId ? [usageLimitRunId] : []); const otherFailures = new Set(); for (const entry of entries) { const item = timelineEntryFailedItem(entry); @@ -1612,6 +1613,8 @@ export function deriveMessagesTimelineRows( timelineEntries: ReadonlyArray; pendingApprovalRequestIds?: ReadonlySet; latestRun?: TimelineLatestRun | null; + /** The usage-limited run whose failure row the recovery notice replaces. */ + usageLimitRunId?: RunId | null; runningRunId?: RunId | null; expandedRunIds?: ReadonlySet; expandedAttemptIds?: ReadonlySet; @@ -1663,7 +1666,11 @@ export function deriveMessagesTimelineRows( const nextRows: MessagesTimelineRow[] = []; const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(timelineEntries); const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null); - const itemizedRunIds = itemizedFailedRunIds(timelineEntries, failedRunIds); + const itemizedRunIds = itemizedFailedRunIds( + timelineEntries, + failedRunIds, + input.usageLimitRunId ?? null, + ); const liveSubagentEntryIds = liveSubagentCardEntryIds(timelineEntries); const retainedAssistantReplyIds = retainedAssistantReplyEntryIds(timelineEntries); const supersededFoldsByAnchorEntryId = deriveSupersededAttemptFolds( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 89cc3f8701c55..fe60471993e36 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -257,6 +257,7 @@ interface MessagesTimelineProps { listRef: React.RefObject; timelineEntries: ReadonlyArray; latestRun: TimelineLatestRun | null; + usageLimitRunId?: RunId | null; /** The run the screen reader announcer follows; see announcedRun. */ announcedRun?: { readonly runId: RunId; readonly status: TimelineLatestRun["status"] } | null; /** See isDetailBehindShell. */ @@ -381,6 +382,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ activeFindMatch = null, findNavigationId = 0, latestRun, + usageLimitRunId = null, announcedRun = null, detailBehindShell = false, runningRunId = null, @@ -748,6 +750,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ timelineEntries, pendingApprovalRequestIds, latestRun, + usageLimitRunId, runningRunId, expandedRunIds: visibleExpandedRunIds, expandedAttemptIds: visibleExpandedAttemptIds, From ec35ad6618ea8ca72069b3f35198786deabb550a Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:00:38 +0100 Subject: [PATCH 087/162] fix(server): t3 doctor no longer reports a database just under 1 GiB as "1024.0 MiB" (#40952) Co-authored-by: MarcoDotIO <20867620+MarcoDotIO@users.noreply.github.com> --- apps/server/src/cli/doctor.test.ts | 28 ++++++++++++++++++++++++++++ apps/server/src/cli/doctor.ts | 14 +++++++++----- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/apps/server/src/cli/doctor.test.ts b/apps/server/src/cli/doctor.test.ts index 6315378d07cb8..44dfd1bc27eff 100644 --- a/apps/server/src/cli/doctor.test.ts +++ b/apps/server/src/cli/doctor.test.ts @@ -8,6 +8,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as TestClock from "effect/testing/TestClock"; +import * as TestConsole from "effect/testing/TestConsole"; import * as BootService from "../cloud/bootService.ts"; import { runDoctor } from "./doctor.ts"; @@ -118,6 +119,33 @@ it.effect( }).pipe(Effect.provide(layerHost)), ); +it.effect("reports sizes just under the next unit in that unit", () => + Effect.gen(function* () { + yield* runDoctor( + { dbPath: "/test/statev2.sqlite", serverRuntimeStatePath: "/test/server-runtime.json" }, + { fix: false, dryRun: true }, + ).pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(BootService.BootService)({}), + Layer.mock(DatabaseMaintenance)({ + inspect: () => + Effect.succeed({ + databaseBytes: 1024 ** 3 - 4096, + reclaimableBytes: 1024 ** 2 - 512, + incrementalVacuumEnabled: true, + legacyDatabaseBytes: null, + legacyOnlyRecords: null, + }), + }), + ), + ), + ); + const [summary] = yield* TestConsole.logLines; + assert.strictEqual(summary, "Database: 1.00 GiB, 1.0 MiB reclaimable."); + }).pipe(Effect.provide(Layer.merge(layerHost, TestConsole.layer))), +); + it.effect("warns how long reclaiming can take and reports each step with its elapsed time", () => Effect.gen(function* () { const output: string[] = []; diff --git a/apps/server/src/cli/doctor.ts b/apps/server/src/cli/doctor.ts index 50cd852e5b4b1..60af29ac41e7b 100644 --- a/apps/server/src/cli/doctor.ts +++ b/apps/server/src/cli/doctor.ts @@ -13,12 +13,16 @@ import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntim import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import * as CliService from "./service.ts"; -const formatBytes = (bytes: number) => - bytes >= 1024 ** 3 +// Pick the unit after rounding, so a size just under 1 GiB reads "1.00 GiB", not "1024.0 MiB". +const formatBytes = (bytes: number) => { + const mebibytes = (bytes / 1024 ** 2).toFixed(1); + const kibibytes = Math.ceil(bytes / 1024); + return Number(mebibytes) >= 1024 ? `${(bytes / 1024 ** 3).toFixed(2)} GiB` - : bytes >= 1024 ** 2 - ? `${(bytes / 1024 ** 2).toFixed(1)} MiB` - : `${Math.ceil(bytes / 1024)} KiB`; + : kibibytes >= 1024 + ? `${mebibytes} MiB` + : `${kibibytes} KiB`; +}; const formatElapsed = (nanos: bigint) => { const seconds = Number(nanos / 1_000_000_000n); From 69720261214c047e583b494675ea9624bbe3a00a Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:02:10 +0100 Subject: [PATCH 088/162] fix(web): show clone failure after progress is dismissed (#40951) Co-authored-by: Julius Marminge --- .../ProjectCloneToastCoordinator.tsx | 57 +++++---- ...e-failure-after-dismissing-progress.e2e.ts | 113 ++++++++++++++++++ 2 files changed, 148 insertions(+), 22 deletions(-) create mode 100644 scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts diff --git a/apps/web/src/components/ProjectCloneToastCoordinator.tsx b/apps/web/src/components/ProjectCloneToastCoordinator.tsx index 846644c537a12..778c195e2d29e 100644 --- a/apps/web/src/components/ProjectCloneToastCoordinator.tsx +++ b/apps/web/src/components/ProjectCloneToastCoordinator.tsx @@ -45,6 +45,8 @@ interface TrackedToast { readonly toastId: ReturnType; readonly renderedKey: string; readonly phase: ProjectCloneSnapshot["phase"]; + readonly startedAt: ProjectCloneSnapshot["startedAt"]; + readonly closed?: true; } function renderKey(clone: ProjectCloneSnapshot): string { @@ -98,6 +100,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI seen.add(clone.projectId); const key = renderKey(clone); const tracked = toasts.current.get(clone.projectId); + const sameAttempt = tracked?.startedAt === clone.startedAt; const name = projectCloneDisplayName(clone); const closeToast = () => { const current = toasts.current.get(clone.projectId); @@ -111,7 +114,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } - if (tracked?.renderedKey === key) continue; + if (sameAttempt && tracked.renderedKey === key) continue; if ( isProjectCloneToastSilenced(ref) && (clone.phase === "running" || clone.phase === "done") @@ -119,6 +122,34 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } + if ( + sameAttempt && + tracked.closed && + (tracked.phase !== "running" || clone.phase !== "failed") + ) { + continue; + } + + const showToast = (options: ReturnType) => { + const rendered = { renderedKey: key, phase: clone.phase, startedAt: clone.startedAt }; + if (tracked && !tracked.closed) { + toastManager.update(tracked.toastId, options); + toasts.current.set(clone.projectId, { toastId: tracked.toastId, ...rendered }); + return; + } + + const toastId = toastManager.add({ + ...options, + // Updates to a closing toast are ignored, even before it has been removed. + onClose: () => { + const current = toasts.current.get(clone.projectId); + if (current?.toastId === toastId) { + toasts.current.set(clone.projectId, { ...current, closed: true }); + } + }, + }); + toasts.current.set(clone.projectId, { toastId, ...rendered }); + }; if (clone.phase === "running") { const options = stackedThreadToast({ @@ -136,13 +167,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "running" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "running" }); - } + showToast(options); continue; } @@ -161,13 +186,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "done" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "done" }); - } + showToast(options); continue; } @@ -199,13 +218,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: clone.phase }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: clone.phase }); - } + showToast(options); } for (const [projectId, tracked] of toasts.current) { diff --git a/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts new file mode 100644 index 0000000000000..739497a827757 --- /dev/null +++ b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts @@ -0,0 +1,113 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fixture holds Git's HTTP request open. +import * as NodeHttp from "node:http"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { ProjectId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Stream from "effect/Stream"; + +import { T3_HOME } from "../e2e.config.ts"; +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; + +test( + "Dismissing clone progress leaves the later failure notification visible", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Other work", messages: ["Start"] }); + const gitRequest = Promise.withResolvers(); + const remote = NodeHttp.createServer((_request, response) => { + gitRequest.resolve(response); + }); + + try { + await new Promise((resolve) => remote.listen(0, "127.0.0.1", resolve)); + const address = remote.address(); + if (!address || typeof address === "string") throw new Error("No Git fixture port"); + const projectId = ProjectId.make( + await runPromise( + SecureRandom.SecureRandom.pipe( + Effect.flatMap((random) => random.uuidV4()), + Effect.provide(NodeCrypto.layer), + ), + ), + ); + const name = "pending-clone"; + const origin = app.baseUrl ?? ""; + await t3.open(thread); + await screen.getByText("Start", { exact: true }).waitFor(); + + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + const createdAt = DateTime.formatIso(yield* DateTime.now); + yield* client["projectClone.start"]({ + projectId, + title: name, + createdAt, + remoteUrl: `http://127.0.0.1:${address.port}/${name}.git`, + destinationPath: `${project}/../${name}`, + }); + }).pipe(Effect.scoped), + ); + const response = await gitRequest.promise; + + const toastTitle = (title: string) => + browser.locator(`[data-slot="toast-title"]:text-is("${title}")`); + const dismiss = async (title: string) => { + await browser + .locator( + `[data-position]:has(> div > [data-slot="toast-close"]):has([data-slot="toast-title"]:text-is("${title}"))`, + ) + .getByRole("button", "Dismiss notification", { exact: true }) + .tap(); + await toastTitle(title).waitFor({ state: "detached" }); + }; + const progress = toastTitle(`Cloning ${name}`); + const failure = toastTitle(`Failed to clone ${name}`); + + await progress.waitFor(); + await dismiss(`Cloning ${name}`); + + response.writeHead(404).end(); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + yield* client.subscribeProjectClones({}).pipe( + Stream.filter((clones) => + clones.some((clone) => clone.projectId === projectId && clone.phase === "failed"), + ), + Stream.runHead, + ); + }).pipe(Effect.scoped, Effect.timeout("10 seconds")), + ); + + try { + await expect(failure).toBeVisible(); + } finally { + await app.screenshot("after-background-clone-fails"); + } + + await dismiss(`Failed to clone ${name}`); + + const retryRequest = Promise.withResolvers(); + remote.once("request", (_request, response) => retryRequest.resolve(response)); + const retry = await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + return yield* client["projectClone.retry"]({ projectId }); + }).pipe(Effect.scoped), + ); + await expect(retry.applied).toBe(true); + const retryResponse = await retryRequest.promise; + await expect(progress).toBeVisible(); + retryResponse.writeHead(404).end(); + await expect(failure).toBeVisible(); + } finally { + remote.close(); + remote.closeAllConnections(); + } + }, +); From bc13afaa3c42be200956b6181d21642883d77903 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:31:53 +0100 Subject: [PATCH 089/162] Invalidate pending theme imports when a replacement is too large (#40965) Co-authored-by: Julius Marminge --- .../ThemeImportDialog.browser.test.tsx | 52 +++++++++++++++ .../components/settings/ThemeImportDialog.tsx | 5 +- ...-theme-file-supersedes-earlier-read.e2e.ts | 64 +++++++++++++++++++ 3 files changed, 119 insertions(+), 2 deletions(-) create mode 100644 scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts diff --git a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx index 8eecf79f5d33a..fd5b90f9c6c19 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx @@ -157,6 +157,58 @@ it("sizes an oversized theme file just under 1 MB as 1.00 MB", async () => { ); }); +it.each(["failed read", "batch install"])( + "keeps the oversized replacement warning after a superseded %s", + async (earlierImport) => { + using _themes = isolateThemes(); + await using _screen = await render( + {}} + onImported={() => true} + onImportedMany={() => {}} + />, + ); + const earlierRead = Promise.withResolvers(); + const readStarted = Promise.withResolvers(); + const earlierFile = Object.assign(themeFile("Dusk"), { + text() { + readStarted.resolve(); + return earlierRead.promise; + }, + }); + const input = document.querySelector('input[type="file"]')!; + const files = new DataTransfer(); + if (earlierImport === "batch install") files.items.add(themeFile("Dawn")); + files.items.add(earlierFile); + await act(async () => { + input.files = files.files; + input.dispatchEvent(new Event("change", { bubbles: true })); + await readStarted.promise; + }); + await expect.element(page.getByRole("button", { name: "Reading…" })).toBeDisabled(); + await userEvent.upload( + input, + new File([" ".repeat(256 * 1024 + 1)], earlierFile.name, { type: "application/json" }), + ); + const warning = page.getByText(/^That file is/); + await expect.element(warning).toBeVisible(); + + await act(async () => { + if (earlierImport === "batch install") { + earlierRead.resolve(JSON.stringify(theme("Dusk"))); + } else { + earlierRead.reject(new Error("Could not read Dusk")); + } + await earlierRead.promise.catch(() => {}); + }); + + expect(getCustomThemes().map((theme) => theme.label)).toEqual([]); + expect(page.getByRole("alert").element().textContent).toMatch(/^That file is/); + await expect.element(page.getByRole("button", { name: "Choose files" })).toBeEnabled(); + }, +); + function themeJsonc(name: string, background: string) { return `{ // VS Code themes use JSONC even with a .json extension. diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsx index 189560efdee9e..aeac23821884f 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.tsx @@ -233,19 +233,20 @@ function ThemeImportBody({ const [isReading, setIsReading] = useState(false); const [isDropTarget, setIsDropTarget] = useState(false); const [conflicts, setConflicts] = useState | null>(null); - // A newer read supersedes an older one still in flight. + // A new file selection supersedes a pending import even if the selection is rejected. const importRequestRef = useRef(0); const isCurrentRequest = (requestId: number) => requestId === importRequestRef.current && !signal.aborted; const readThemeFile = async (file: ImportableThemeFile) => { + const requestId = ++importRequestRef.current; const oversized = describeOversizedThemeFile(file.size); if (oversized) { + setIsReading(false); setError(oversized); return; } - const requestId = ++importRequestRef.current; setIsReading(true); const fileText = await settlePromise(() => file.text()); if (!isCurrentRequest(requestId)) return; diff --git a/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts new file mode 100644 index 0000000000000..49186eaa4429a --- /dev/null +++ b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts @@ -0,0 +1,64 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +declare global { + interface Window { + releaseOldThemeRead: () => void; + } +} + +test( + "An earlier theme file cannot become the draft after its replacement is rejected", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await t3.open("/settings/appearance"); + await screen.getByRole("button", "Add theme", { exact: true }).tap(); + const dialog = screen.getByRole("dialog", "Add a theme"); + + await browser.evaluate(() => { + const target = document.querySelector('input[type="file"]')?.parentElement; + if (!target) throw new Error("No theme file drop target"); + + const gate = Promise.withResolvers(); + const theme = JSON.stringify({ + version: 1, + name: "Earlier theme", + appearance: "dark", + colors: { accent: "#734ee4" }, + }); + const first = new File([theme], "earlier.json", { type: "application/json" }); + const text = File.prototype.text; + File.prototype.text = function () { + if (this.name === first.name) return gate.promise.then(() => theme); + return text.call(this); + }; + window.releaseOldThemeRead = gate.resolve; + + const drop = (file: File) => { + const files = new DataTransfer(); + files.items.add(file); + target.dispatchEvent( + new DragEvent("drop", { dataTransfer: files, bubbles: true, cancelable: true }), + ); + }; + drop(first); + drop(new File([" ".repeat(300_000)], "replacement.json", { type: "application/json" })); + return null; + }); + + await dialog.getByText(/That file is/).waitFor(); + await browser.evaluate(async () => { + window.releaseOldThemeRead(); + // Let the earlier file response and its React update reach the dialog. + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + return null; + }); + await app.screenshot("dialog-after-earlier-theme-read-finishes"); + await expect(dialog.getByRole("button", "Add theme", { exact: true })).toBeDisabled(); + }, +); From 4e1c1fea7aa21189b2b363aefd38892377625307 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:06:09 +0100 Subject: [PATCH 090/162] fix(mobile): show linked thread history page errors (#40973) --- .../threads/LinkedThreadSheet.test.tsx | 134 ++++++++++++++++++ .../features/threads/LinkedThreadSheet.tsx | 21 ++- apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + apps/mobile/vite.config.ts | 1 + 13 files changed, 164 insertions(+), 2 deletions(-) create mode 100644 apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx new file mode 100644 index 0000000000000..748fb333239a0 --- /dev/null +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx @@ -0,0 +1,134 @@ +import { expect, it } from "@effect/vitest"; +import { + followLinkedThread, + type LinkedThreadView as LinkedThreadState, +} from "@t3tools/client-runtime/linked-thread"; +import { EnvironmentId, type OrchestrationV2ThreadHistoryPage } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { vi } from "vite-plus/test"; + +import { v2Projection } from "../../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures"; +import { useLinkedThreadView } from "../../state/linkedThread"; +import { LinkedThreadView } from "./LinkedThreadSheet"; + +vi.mock("@react-navigation/native", () => ({ + StackActions: {}, + useIsFocused: () => true, + useNavigation: () => ({}), +})); +vi.mock("react-native", () => { + const Container = ({ children }: { children: ReactNode }) =>
    {children}
    ; + return { + AppState: { currentState: "active", addEventListener: () => ({ remove() {} }) }, + Platform: { OS: "android" }, + Pressable: Container, + ScrollView: Container, + Text: Container, + View: Container, + }; +}); +vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) })); +vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null })); +vi.mock("../../components/ui/Button", () => ({ + Button: (props: { label: string; disabled?: boolean; onPress: () => void }) => ( + + ), +})); +vi.mock("../../components/ui/ScreenContent", () => ({ + ScreenContent: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../native/SelectableMarkdownText", () => ({ SelectableMarkdownText: () => null })); +vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environments: [] }) })); +vi.mock("../../state/linkedThread", () => ({ + useConnectLinkedEnvironment: () => ({ state: { phase: "idle" } }), + useLinkedThreadView: vi.fn(), +})); +vi.mock("../../state/peerLinks", () => ({ peerLinkEnvironment: {} })); +vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({}) })); +vi.mock("../files/FileMarkdownPreview", () => ({ useMarkdownPreviewStyles: () => ({}) })); +vi.mock("./ReadOnlyComposerBar", () => ({ + ReadOnlyComposerBar: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("./thread-inspector-header", () => ({ ThreadInspectorHeader: () => null })); +vi.mock("./useOpenLinkedThread", () => ({ useOpenLinkedThread: () => undefined })); + +it.effect( + "shows a page error after Load earlier fails on an already disconnected linked chat", + () => + Effect.gen(function* () { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + const root = createRoot(container); + const target = { + viaEnvironmentId: EnvironmentId.make("via"), + environmentId: EnvironmentId.make("linked"), + threadId: v2Projection.thread.id, + label: "Linked test environment", + title: null, + }; + const warning = "Linked test environment is not answering this environment"; + const pageError = "Could not load earlier turns. Try again."; + const loadEarlier = () => + [...container.querySelectorAll("button")].find( + (button) => button.textContent === "Load earlier", + )!; + + try { + const unavailable = { _tag: "PeerLinkThreadReadError", reason: "unreachable" }; + const pages = + yield* Queue.unbounded< + Effect.Effect + >(); + const views = yield* Queue.unbounded(); + yield* followLinkedThread({ + items: Stream.make({ + kind: "snapshot", + snapshotSequence: 1, + projection: v2Projection, + historyCursor: "before-recent", + hasMoreHistory: true, + } as const).pipe(Stream.concat(Stream.fail(unavailable))), + historyPage: () => Queue.take(pages).pipe(Effect.flatten), + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.forkScoped, + ); + + const renderNext = Effect.gen(function* () { + const view = yield* Queue.take(views); + vi.mocked(useLinkedThreadView).mockReturnValue({ + view, + error: view.error ?? null, + retry() {}, + }); + act(() => root.render()); + }); + + yield* renderNext; // Initial snapshot. + yield* renderNext; // Connection warning. + expect(container.textContent).toContain(warning); + expect(container.textContent).not.toContain(pageError); + + act(() => loadEarlier().click()); + yield* renderNext; + yield* Queue.offer(pages, Effect.fail(unavailable)); + yield* renderNext; + expect(loadEarlier().parentElement?.textContent).toContain(pageError); + expect(container.textContent).toContain(warning); + + act(() => loadEarlier().click()); + yield* renderNext; + expect(container.textContent).not.toContain(pageError); + expect(loadEarlier().disabled).toBe(true); + } finally { + act(() => root.unmount()); + vi.unstubAllGlobals(); + } + }).pipe(Effect.scoped), +); diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx index 0096c9d576a91..7ec2c4dac2cc8 100644 --- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -286,6 +286,9 @@ export function LinkedThreadView(props: { const scroll = useRef>(null); // Follows new items only while the reader is already at the end. const atEnd = useRef(true); + const showHistoryError = + view !== null && view.thread.historyCursor !== null && view.history.failed; + const lastLayoutHadHistoryError = useRef(false); const working = projection !== null && isLinkedThreadWorking(projection); const connection = useConnectLinkedEnvironment(target); const connectState = connection.state; @@ -334,7 +337,12 @@ export function LinkedThreadView(props: { atEnd.current = contentSize.height - layoutMeasurement.height - contentOffset.y < 80; }} onContentSizeChange={() => { - if (atEnd.current) scroll.current?.scrollToEnd({ animated: false }); + // A page error can resize the top of a short feed whose reader is also near the end. + const historyErrorChanged = lastLayoutHadHistoryError.current !== showHistoryError; + lastLayoutHadHistoryError.current = showHistoryError; + if (atEnd.current && !historyErrorChanged) { + scroll.current?.scrollToEnd({ animated: false }); + } }} > {view === null || projection === null ? ( @@ -351,7 +359,7 @@ export function LinkedThreadView(props: { ) : ( <> {view.thread.historyCursor !== null ? ( - +
  • ))} {props.notebook.cells.length === 0 ? ( diff --git a/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts new file mode 100644 index 0000000000000..c944cf1ec9d42 --- /dev/null +++ b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts @@ -0,0 +1,80 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const savedResults = Array.from({ length: 17 }, (_, index) => `Saved result ${index + 1}`); +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: [ + { output_type: "stream", name: "stdout", text: Array(12).fill("Processing").join("\n") }, + ...savedResults.map((result) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `${result}` }, + })), + ], + }, + ], +}; +const lastOutput = '[data-notebook-output="0-17"]'; + +test( + "All saved notebook outputs render when they fit in a tall preview", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // The stream puts the final result below the fold until the user scrolls. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 1070; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator('[data-notebook-output="0-15"] iframe').waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = viewport.scrollHeight; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + const bounds = viewport.getBoundingClientRect(); + return Array.from(viewport.querySelectorAll("[data-notebook-output]"), (output) => { + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return "Output is offscreen"; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }); + }, lastOutput), + ) + .toEqual(savedResults); + } finally { + await app.screenshot("last-saved-output-in-tall-preview"); + } + }, +); diff --git a/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts new file mode 100644 index 0000000000000..2897ecc0df7eb --- /dev/null +++ b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts @@ -0,0 +1,77 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: Array.from({ length: 17 }, (_, index) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `Saved result ${index + 1}` }, + })), + }, + ], +}; +const fifteenthOutputFrame = '[data-notebook-output="0-14"] iframe'; +const lastOutput = '[data-notebook-output="0-16"]'; + +test( + "A visible saved notebook output renders when earlier outputs have scrolled above it", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // Leave room for the final output and fewer than sixteen preceding outputs. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 940; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator(fifteenthOutputFrame).waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = 170; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const output = document.querySelector(selector); + const viewport = output?.closest(".scrollbar-gutter-both"); + if (!output || !viewport) return null; + const bounds = viewport.getBoundingClientRect(); + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return null; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }, lastOutput), + ) + .toBe("Saved result 17"); + } finally { + await app.screenshot("last-saved-output"); + } + }, +); From 87554a7b86d17ce9efc9f72d58d1f2f0f47f7e99 Mon Sep 17 00:00:00 2001 From: Stefan Mirea Date: Sun, 22 Nov 2026 19:45:42 +0000 Subject: [PATCH 095/162] fix(web): editing a queued message keeps its attachment chips resolved (#40945) Co-authored-by: gemini-4-neon Co-authored-by: Julius Marminge --- apps/web/src/components/ChatView.tsx | 6 + .../components/ComposerPromptEditorTiptap.tsx | 3 + apps/web/src/components/chat/ChatComposer.tsx | 116 ++++++++++++++---- .../chat/composerContextUndo.test.ts | 69 ++++++++++- .../components/chat/composerContextUndo.ts | 44 ++++++- .../components/chat/queuedMessageEdit.test.ts | 95 +++++++++++++- .../src/components/chat/queuedMessageEdit.ts | 90 +++++++++++++- .../chat/useComposerContextImport.ts | 20 +++ .../chat/useQueuedRunEdit.browser.test.tsx | 82 +++++++++++-- .../src/components/chat/useQueuedRunEdit.ts | 64 +++++++++- .../composerContextPresentation.test.ts | 98 ++++++++++++++- .../composerContextPresentation.tsx | 64 +++++++++- apps/web/src/lib/composerContextRecords.ts | 36 ++++-- 13 files changed, 726 insertions(+), 61 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 4f1d764ffef29..229ac99e3a756 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3946,9 +3946,15 @@ export default function ChatView(props: ChatViewProps) { onExpandImage={onExpandTimelineImageStable} onFileOpen={openFileAttachmentStable} editingQueuedAttachments={queuedRunEdit.editingAttachments} + removedEditingQueuedAttachments={ + queuedRunEdit.removedEditingAttachments + } onRemoveEditingQueuedAttachment={ queuedRunEdit.removeEditingAttachment } + onRestoreEditingQueuedAttachment={ + queuedRunEdit.restoreEditingAttachment + } /> )} diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 402156b001286..634b7a9389e93 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -203,6 +203,8 @@ export interface ComposerPromptEditorProps { contextIds: string[], /** False when only the caret or selection moved. */ textChanged: boolean, + /** True when the change came from undo or redo. */ + fromHistory?: boolean, ) => void; onVisibleSelectionChange?: () => void; onCommandKeyDown?: (key: string, event: KeyboardEvent, isTaskItem?: boolean) => boolean; @@ -1127,6 +1129,7 @@ function ComposerPromptEditorTiptapInner( suppressTrigger, contextIds, previousSnapshot.value !== nextValue, + isHistoryTransaction(transaction), ); }; diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index af4871b451932..85a7f6173bf96 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -23,6 +23,7 @@ import { import type { KeybindingCommand, AssistantCitation, + ComposerContextId, ResponseContextRecord, ChatAttachment as ContractChatAttachment, ChatFileAttachment, @@ -120,6 +121,7 @@ import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { + type QueuedAttachmentContextBinding, reconcileAttachmentContextReferences, useRetainedContextPayloads, } from "./composerContextUndo"; @@ -287,6 +289,7 @@ import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; import { cancelHeldComposerSend, countPreparingComposerImages, @@ -457,8 +460,11 @@ export interface ChatComposerProps { editingQueuedAttachments: ReadonlyArray<{ readonly attachment: ContractChatAttachment; readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; }> | null; + removedEditingQueuedAttachments?: ReadonlyArray | undefined; onRemoveEditingQueuedAttachment: (attachmentId: string) => void; + onRestoreEditingQueuedAttachment?: ((attachment: ContractChatAttachment) => void) | undefined; onCompactContext: () => void; onSend: ( @@ -599,7 +605,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onExpandImage, onFileOpen, editingQueuedAttachments, + removedEditingQueuedAttachments, onRemoveEditingQueuedAttachment, + onRestoreEditingQueuedAttachment, } = props; const { activePendingProgress: incomingPendingProgress, @@ -657,6 +665,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingProgress.activeQuestion.id, ) : null; + const queuedEditOwnsComposer = + questionAttachmentTarget === null && pendingUserInputs.length === 0; + const activeEditingQueuedAttachments = queuedEditOwnsComposer ? editingQueuedAttachments : null; + const activeRemovedEditingQueuedAttachments = queuedEditOwnsComposer + ? removedEditingQueuedAttachments + : undefined; const attachmentDraftTarget = questionAttachmentTarget ?? composerDraftTarget; const attachmentDraft = useComposerThreadDraft(attachmentDraftTarget); const questionTakesSnapShots = @@ -757,33 +771,55 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cwd: gitCwd ?? undefined, projectId: activeProjectId ?? undefined, expandImage: (imageId: string) => { - const preview = buildExpandedImagePreview( - composerImages, - imageId, - copyComposerSnapshotStable, - ); + const preview = + buildExpandedImagePreview(composerImages, imageId, copyComposerSnapshotStable) ?? + buildExpandedImagePreview( + (activeEditingQueuedAttachments ?? []).flatMap(({ attachment, url }) => + isQueuedImageAttachment(attachment) && url ? [{ ...attachment, previewUrl: url }] : [], + ), + imageId, + ); if (preview) onExpandImage(preview); }, - openFile: setPreviewFileId, + openFile: (fileId: string) => { + if (composerFiles.some((file) => file.id === fileId)) { + setPreviewFileId(fileId); + return; + } + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (queuedFile && isQueuedFileAttachment(queuedFile)) onFileOpen(queuedFile); + }, openMention: (path: string) => useRightPanelStore.getState().openFile(routeThreadRef, path), expandVideo: (fileId: string) => { const file = composerFiles.find((candidate) => candidate.id === fileId); - if (!file || !isVideoAttachment(file)) return; - const localPreview = buildExpandedImagePreview([file], file.id); - if (localPreview) { - onExpandImage(localPreview); + if (file && isVideoAttachment(file)) { + const localPreview = buildExpandedImagePreview([file], file.id); + if (localPreview) { + onExpandImage(localPreview); + return; + } + if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + return; + } + const persistedPreview = buildAttachmentVideoPreview(environmentId, { + type: "file", + id: file.uploadedAttachmentId, + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + }); + if (persistedPreview) onExpandImage(persistedPreview); return; } - if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (!queuedFile || !isQueuedFileAttachment(queuedFile) || !isVideoAttachment(queuedFile)) { return; } - const persistedPreview = buildAttachmentVideoPreview(environmentId, { - type: "file", - id: file.uploadedAttachmentId, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - }); + const persistedPreview = buildAttachmentVideoPreview(environmentId, queuedFile); if (persistedPreview) onExpandImage(persistedPreview); }, openPullRequest: (event: React.MouseEvent, url: string) => { @@ -798,6 +834,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentContexts: composerEnvironmentContexts, images: composerImages, files: composerFiles, + existingAttachments: activeEditingQueuedAttachments ?? undefined, + environmentId, uploadsByImageId, }); const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length; @@ -1393,12 +1431,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null); if (!record) return []; if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file); - return [ - record.kind === "image" && attachment.type === "image" && attachment.source - ? { ...record, source: attachment.source } - : record, - ]; + return [record]; }), + ...(activeEditingQueuedAttachments ?? []).flatMap(({ attachment, contextIds }) => { + if (!isQueuedImageAttachment(attachment) && !isQueuedFileAttachment(attachment)) return []; + return (contextIds ?? []) + .filter((contextId) => wanted.has(contextId)) + .map((contextId) => + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + ); + }), ]; if (records.length === 0) return null; const fragment = encodeComposerContextFragment({ @@ -1447,6 +1493,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments: activeRemovedEditingQueuedAttachments, + onRestoreQueuedAttachment: onRestoreEditingQueuedAttachment, }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared prompt ref in step with the committed draft prompt for imperative handlers @@ -1652,6 +1700,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cursorAdjacentToMention: boolean, contextIds: string[], textChanged: boolean, + fromHistory = false, ) => { refreshWorkspaceSnapshotOnTyping(); const trigger = cursorAdjacentToMention @@ -1762,6 +1811,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const attachmentChanges = reconcileAttachmentContextReferences({ referencedContextIds: referenced, files: composerFiles, + queuedAttachments: (activeEditingQueuedAttachments ?? []).map( + ({ attachment, contextIds }) => ({ + attachment, + contextIds: contextIds ?? [], + }), + ), + removedQueuedAttachments: activeRemovedEditingQueuedAttachments ?? [], + fromHistory, images: composerImages, previewAnnotations: composerPreviewAnnotations, retained: retainedContextPayloads, @@ -1781,6 +1838,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (attachmentChanges.filesToRestore.length > 0) { addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore); } + for (const attachmentId of attachmentChanges.queuedAttachmentIdsToRemove) { + onRemoveEditingQueuedAttachment(attachmentId); + } + for (const attachment of attachmentChanges.queuedAttachmentsToRestore) { + onRestoreEditingQueuedAttachment?.(attachment); + } setComposerCursor(nextCursor); updateTrigger(trigger); }; @@ -3814,11 +3877,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) )} {!isComposerCollapsedMobile && - pendingUserInputs.length === 0 && - editingQueuedAttachments !== null && - editingQueuedAttachments.length > 0 && ( + activeEditingQueuedAttachments !== null && + activeEditingQueuedAttachments.length > 0 && ( )} diff --git a/apps/web/src/components/chat/composerContextUndo.test.ts b/apps/web/src/components/chat/composerContextUndo.test.ts index a763b47a0d6d7..c493aa2dfc8fd 100644 --- a/apps/web/src/components/chat/composerContextUndo.test.ts +++ b/apps/web/src/components/chat/composerContextUndo.test.ts @@ -1,4 +1,8 @@ -import type { PreviewAnnotationPayload } from "@t3tools/contracts"; +import { + ChatAttachmentId, + ComposerContextId, + type PreviewAnnotationPayload, +} from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import type { ComposerImageAttachment } from "../../composerDraftStore"; @@ -37,7 +41,7 @@ const annotation = { } satisfies PreviewAnnotationPayload; function retention(): RetainedAttachmentContextPayloads { - return { files: new Map(), previewAnnotations: new Map() }; + return { files: new Map(), previewAnnotations: new Map(), restoredQueuedImageIds: new Set() }; } describe("reconcileAttachmentContextReferences", () => { @@ -88,4 +92,65 @@ describe("reconcileAttachmentContextReferences", () => { }), ]); }); + + it("drops a queued file with its chip, keeps a queued image, and lets undo and redo restore and remove either", () => { + const file = { + attachment: { + type: "file" as const, + id: ChatAttachmentId.make("server-file"), + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }, + contextIds: [ComposerContextId.make("file_local")], + }; + const queuedImage = { + attachment: { + type: "image" as const, + id: ChatAttachmentId.make("server-image"), + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }, + contextIds: [ComposerContextId.make("image_local")], + }; + const base = { files: [], images: [], previewAnnotations: [], retained: retention() }; + + const deleted = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [file, queuedImage], + }); + expect(deleted.queuedAttachmentIdsToRemove).toEqual([file.attachment.id]); + + const undone = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(["file_local", "image_local"]), + removedQueuedAttachments: [file, queuedImage], + }); + expect(undone.queuedAttachmentsToRestore).toEqual([file.attachment, queuedImage.attachment]); + + const redone = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [file, queuedImage], + fromHistory: true, + }); + expect(redone.queuedAttachmentIdsToRemove).toEqual([ + file.attachment.id, + queuedImage.attachment.id, + ]); + + reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(["image_local"]), + removedQueuedAttachments: [queuedImage], + }); + const backspaced = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [queuedImage], + }); + expect(backspaced.queuedAttachmentIdsToRemove).toEqual([]); + }); }); diff --git a/apps/web/src/components/chat/composerContextUndo.ts b/apps/web/src/components/chat/composerContextUndo.ts index fd2a0cde59341..4c96ec12b70fc 100644 --- a/apps/web/src/components/chat/composerContextUndo.ts +++ b/apps/web/src/components/chat/composerContextUndo.ts @@ -1,4 +1,6 @@ import type { + ChatAttachment, + ComposerContextId, EnvironmentContextRecord, PreviewAnnotationPayload, ThreadContextRecord, @@ -9,15 +11,23 @@ import type { ComposerFileAttachment, ComposerImageAttachment } from "../../comp import { fileContextReference, previewAnnotationContextId } from "../../lib/composerContextRecords"; import type { TerminalContextDraft } from "../../lib/terminalContext"; import type { ReviewCommentContext } from "../../reviewCommentContext"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; interface RetainedPreviewAnnotation { annotation: PreviewAnnotationPayload; image: ComposerImageAttachment | undefined; } +export interface QueuedAttachmentContextBinding { + readonly attachment: ChatAttachment; + readonly contextIds: ReadonlyArray; +} + export interface RetainedAttachmentContextPayloads { files: Map; previewAnnotations: Map; + /** Queued images brought back because their chip reappeared. */ + restoredQueuedImageIds: Set; } export interface RetainedContextPayloads extends RetainedAttachmentContextPayloads { @@ -35,6 +45,7 @@ function createRetainedContextPayloads(): RetainedContextPayloads { environments: new Map(), files: new Map(), previewAnnotations: new Map(), + restoredQueuedImageIds: new Set(), }; } @@ -61,12 +72,19 @@ export function useRetainedContextPayloads(draftTargetKey: string): RetainedCont export function reconcileAttachmentContextReferences(input: { referencedContextIds: ReadonlySet; files: ReadonlyArray; + /** Attachments of a queued message being edited, and those removed during the edit. */ + queuedAttachments?: ReadonlyArray; + removedQueuedAttachments?: ReadonlyArray; + /** The change came from undo or redo. */ + fromHistory?: boolean; images: ReadonlyArray; previewAnnotations: ReadonlyArray; retained: RetainedAttachmentContextPayloads; }): { filesToRemove: string[]; filesToRestore: ComposerFileAttachment[]; + queuedAttachmentIdsToRemove: string[]; + queuedAttachmentsToRestore: ChatAttachment[]; annotationIdsToRemove: string[]; annotationsToRestore: RetainedPreviewAnnotation[]; } { @@ -86,6 +104,23 @@ export function reconcileAttachmentContextReferences(input: { return file ? [file] : []; }); + const isReferenced = (entry: QueuedAttachmentContextBinding) => + entry.contextIds.some((contextId) => input.referencedContextIds.has(contextId)); + const restoredImageIds = input.retained.restoredQueuedImageIds; + const queuedAttachmentIdsToRemove = (input.queuedAttachments ?? []).flatMap((entry) => { + if (entry.contextIds.length === 0 || isReferenced(entry)) return []; + if (isQueuedFileAttachment(entry.attachment)) return [entry.attachment.id]; + // Like draft images, a queued image outlives its deleted chip, unless undo or redo + // takes away a chip whose return had brought the image back. + const wasRestored = restoredImageIds.delete(entry.attachment.id); + return wasRestored && input.fromHistory ? [entry.attachment.id] : []; + }); + const queuedAttachmentsToRestore = (input.removedQueuedAttachments ?? []).flatMap((entry) => { + if (!isReferenced(entry)) return []; + if (isQueuedImageAttachment(entry.attachment)) restoredImageIds.add(entry.attachment.id); + return [entry.attachment]; + }); + const imagesById = new Map(input.images.map((image) => [image.id, image])); const liveAnnotationContextIds = new Set( input.previewAnnotations.map((annotation) => previewAnnotationContextId(annotation.id)), @@ -106,5 +141,12 @@ export function reconcileAttachmentContextReferences(input: { return retained ? [retained] : []; }); - return { filesToRemove, filesToRestore, annotationIdsToRemove, annotationsToRestore }; + return { + filesToRemove, + filesToRestore, + queuedAttachmentIdsToRemove, + queuedAttachmentsToRestore, + annotationIdsToRemove, + annotationsToRestore, + }; } diff --git a/apps/web/src/components/chat/queuedMessageEdit.test.ts b/apps/web/src/components/chat/queuedMessageEdit.test.ts index 49d22add3a239..0ebfdacdbb607 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.test.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.test.ts @@ -1,4 +1,11 @@ -import { EnvironmentId, MessageId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { + ChatAttachmentId, + ComposerContextId, + EnvironmentId, + MessageId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { beforeEach, describe, expect, it } from "vite-plus/test"; @@ -10,7 +17,12 @@ import { } from "../../composerDraftStore"; import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue"; import { environmentContextRecord, responseContextRecord } from "../../lib/composerContextRecords"; -import { prepareQueuedEditAttachments, recoverQueuedMessageEdit } from "./queuedMessageEdit"; +import { formatInlineContextReference } from "../../lib/composerContextReferences"; +import { + matchRestorableQueuedAttachment, + prepareQueuedEditAttachments, + recoverQueuedMessageEdit, +} from "./queuedMessageEdit"; const environmentId = EnvironmentId.make("remote-environment"); const threadTarget = scopeThreadRef(environmentId, ThreadId.make("thread:edit")); @@ -193,6 +205,85 @@ describe("queued message file edits", () => { expect(store.getComposerDraft(threadTarget)).toBeNull(); }); + it("strips existing queued attachment references when recovering an edit into the thread draft", () => { + const store = useComposerDraftStore.getState(); + const chip = formatInlineContextReference({ + kind: "image", + contextId: "image_queued-1", + label: "image.png", + }); + store.setPrompt(editTarget, `Check ${chip} closely`); + expect( + recoverQueuedMessageEdit({ + ...originalMessage, + originalText: `Check ${chip}`, + existingAttachmentContextIds: ["image_queued-1"], + }), + ).toBe("kept"); + expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Check closely"); + expect(store.getComposerDraft(editTarget)).toBeNull(); + + store.clearComposerContent(threadTarget); + store.setPrompt(editTarget, chip); + expect( + recoverQueuedMessageEdit({ + ...originalMessage, + originalText: `${chip} note`, + existingAttachmentContextIds: ["image_queued-1"], + }), + ).toBe("discarded"); + expect(store.getComposerDraft(threadTarget)).toBeNull(); + }); + + it("matches a removed queued attachment for same-environment paste while rejecting other environments or payloads", () => { + const fileId = ChatAttachmentId.make("server-file-1"); + const contextId = ComposerContextId.make("file_local-1"); + const removedAttachment = { + type: "file" as const, + id: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + const record = { + version: 1 as const, + kind: "file" as const, + contextId, + label: "notes.txt", + attachmentId: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: environmentId, + record, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toEqual({ attachment: removedAttachment, contextId }); + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: EnvironmentId.make("other-environment"), + record, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toBeNull(); + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: environmentId, + record: { ...record, attachmentId: ChatAttachmentId.make("different-file") }, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toBeNull(); + }); + it("does not overwrite a separate draft when the queued run leaves", () => { const store = useComposerDraftStore.getState(); store.setPrompt(threadTarget, "Separate draft"); diff --git a/apps/web/src/components/chat/queuedMessageEdit.ts b/apps/web/src/components/chat/queuedMessageEdit.ts index e6b59e3a96b83..ca58777dcb44a 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.ts @@ -1,5 +1,14 @@ import { resolveQueuedEditExit } from "@t3tools/client-runtime/queued-run-edit"; -import type { ChatAttachment, ResponseContextRecord } from "@t3tools/contracts"; +import type { + ChatAttachment, + ChatFileAttachment, + ChatImageAttachment, + ComposerContextId, + ComposerContextRecord, + EnvironmentId, + OrchestrationMessageContext, + ResponseContextRecord, +} from "@t3tools/contracts"; import * as Equal from "effect/Equal"; import { composerDraftHasUserContent, @@ -11,6 +20,68 @@ import { import { msg } from "gt-react"; import { m } from "../../i18n/messages"; import { releaseDraftAttachments } from "../../lib/attachmentUploadQueue"; +import { + attachmentContextRecord, + isSameComposerContextPayload, +} from "../../lib/composerContextRecords"; +import { removeInlineContextReference } from "../../lib/composerContextReferences"; + +export function isQueuedImageAttachment( + attachment: ChatAttachment, +): attachment is ChatImageAttachment { + return attachment.type === "image"; +} + +export function isQueuedFileAttachment( + attachment: ChatAttachment, +): attachment is ChatFileAttachment { + return attachment.type === "file"; +} + +export function attachmentContextIdsForRecord( + context: OrchestrationMessageContext | undefined, + attachment: Pick, +): ComposerContextId[] { + return (context?.records ?? []).flatMap((record) => + record.kind === attachment.type && + "attachmentId" in record && + record.attachmentId === attachment.id + ? [record.contextId] + : [], + ); +} + +export function matchRestorableQueuedAttachment(input: { + readonly environmentId: EnvironmentId; + readonly sourceEnvironmentId: EnvironmentId | null; + readonly record: Extract; + readonly removedQueuedAttachments: ReadonlyArray<{ + readonly attachment: ChatAttachment; + readonly contextIds: ReadonlyArray; + }>; +}): { readonly attachment: ChatAttachment; readonly contextId: ComposerContextId } | null { + if (input.sourceEnvironmentId !== input.environmentId) return null; + const match = input.removedQueuedAttachments.find( + ({ attachment, contextIds }) => + (isQueuedImageAttachment(attachment) || isQueuedFileAttachment(attachment)) && + attachment.type === input.record.kind && + contextIds.some((contextId) => + isSameComposerContextPayload( + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + input.record, + ), + ), + ); + if (!match || match.contextIds.length === 0) return null; + const contextId = + match.contextIds.find((candidate) => candidate === input.record.contextId) ?? + match.contextIds[0]!; + return { attachment: match.attachment, contextId }; +} /** Staged attachments upload as soon as they are added, so a dropped edit must release them. */ export function discardQueuedEditDraft(target: ComposerThreadTarget): void { @@ -31,9 +102,21 @@ export function recoverQueuedMessageEdit(input: { readonly originalText: string; readonly originalReplyTo: ResponseContextRecord | null; readonly removedExistingAttachment?: boolean; + readonly existingAttachmentContextIds?: ReadonlyArray; }): "kept" | "discarded" | "clean" { const store = useComposerDraftStore.getState(); const draft = store.getComposerDraft(input.editTarget); + const strippedPrompt = + draft && (input.existingAttachmentContextIds?.length ?? 0) > 0 + ? input.existingAttachmentContextIds!.reduce( + (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt, + draft.prompt, + ) + : draft?.prompt; + const recoveredDraft = + draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt + ? { ...draft, prompt: strippedPrompt } + : draft; const recovery = resolveQueuedEditExit({ editChanged: input.removedExistingAttachment === true || @@ -42,10 +125,13 @@ export function recoverQueuedMessageEdit(input: { (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0)), // A cleared edit has nothing to put back, so it can only be discarded. threadDraftEmpty: - composerDraftHasUserContent(draft) && + composerDraftHasUserContent(recoveredDraft) && !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget)), }); if (recovery === "kept") { + if (draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt) { + store.setPrompt(input.editTarget, strippedPrompt); + } store.moveComposerContent(input.editTarget, input.threadTarget); store.clearComposerContent(input.editTarget); } else { diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 61d0abd7319a6..458f39dc98638 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -10,6 +10,7 @@ import * as Schema from "effect/Schema"; import type { RefObject } from "react"; import type { ChatComposerProps } from "./ChatComposer"; import { + type ChatAttachment, type ComposerContextClipboardFragment, type ComposerContextRecord, type EnvironmentId, @@ -59,6 +60,8 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; import { useStableCallback } from "../../hooks/useStableCallback"; import { countPreparingComposerImages } from "./preparingComposerImages"; +import type { QueuedAttachmentContextBinding } from "./composerContextUndo"; +import { matchRestorableQueuedAttachment } from "./queuedMessageEdit"; const isUnreachable = Schema.is( Schema.Union([ConnectionTransientError, ConnectionBlockedError, EnvironmentRpcUnavailableError]), @@ -94,6 +97,8 @@ export function useComposerContextImport(input: { readonly promptRef: RefObject; readonly pendingThreadImportsRef: RefObject>; readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[]; + readonly removedQueuedAttachments?: ReadonlyArray | undefined; + readonly onRestoreQueuedAttachment?: ((attachment: ChatAttachment) => void) | undefined; }) { const { environmentId, @@ -112,6 +117,8 @@ export function useComposerContextImport(input: { promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments, + onRestoreQueuedAttachment, } = input; const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); @@ -433,6 +440,19 @@ export function useComposerContextImport(input: { case "image": case "file": { if (skippedDependentAttachmentIds.has(record.contextId)) break; + if (questionAttachmentTarget === null && !conflicts) { + const restored = matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId, + record, + removedQueuedAttachments: removedQueuedAttachments ?? [], + }); + if (restored) { + onRestoreQueuedAttachment?.(restored.attachment); + rewritten.set(record.contextId, restored.contextId); + break; + } + } if (sourceEnvironmentId === null && !conflicts) { rewritten.set(record.contextId, record.contextId); break; diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index a88da51cce16e..5ad406da5ef91 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -2,6 +2,7 @@ import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; import { EnvironmentId, ChatAttachmentId, + ComposerContextId, MessageId, RunId, ThreadId, @@ -363,22 +364,83 @@ describe("useQueuedRunEdit", () => { expect(draft?.environmentContexts).toEqual([machine]); }); - it("saves only the thread mentions still in the edited message", async () => { + it("saves only the thread mentions and attachments still in the edited message", async () => { const { hook } = setup(); mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); const kept = threadContextRecord(THREAD_B, "Kept"); const removed = threadContextRecord(THREAD_A, "Removed"); + const removedImageId = ChatAttachmentId.make("server-image-removed"); + const keptFileId = ChatAttachmentId.make("server-file-kept"); + const removedImageContextId = ComposerContextId.make("image_local-removed"); + const keptFileContextId = ComposerContextId.make("file_local-kept"); + const removedImage = { + type: "image" as const, + id: removedImageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const keptFile = { + type: "file" as const, + id: keptFileId, + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; + const removedImageRecord = { + version: 1 as const, + kind: "image" as const, + contextId: removedImageContextId, + label: "image.png", + attachmentId: removedImageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const keptFileRecord = { + version: 1 as const, + kind: "file" as const, + contextId: keptFileContextId, + label: "legacy.pdf", + attachmentId: keptFileId, + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; const messageId = MessageId.make("message-1"); - const text = [kept, removed] - .map((record) => formatInlineContextReference(threadContextReference(record))) - .join(" and "); - const messages = [{ id: messageId, text, context: { version: 1, records: [kept, removed] } }]; + const text = [ + formatInlineContextReference(threadContextReference(kept)), + formatInlineContextReference(threadContextReference(removed)), + formatInlineContextReference({ + kind: "image", + contextId: removedImageContextId, + label: "image.png", + }), + ].join(" and "); + const messages = [ + { + id: messageId, + text, + context: { version: 1, records: [kept, removed, removedImageRecord, keptFileRecord] }, + }, + ]; await using _screen = await render(view(THREAD_A, "queued", hook, messages)); - await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] })); + await act(() => + requireHook(hook).beginEdit({ + runId: RUN, + messageId, + text, + attachments: [removedImage, keptFile], + }), + ); const target = requireHook(hook).draftTarget; - await act(() => useComposerDraftStore.getState().setThreadContexts(target, [kept])); + await act(() => { + useComposerDraftStore.getState().setThreadContexts(target, [kept]); + requireHook(hook).removeEditingAttachment(removedImageId); + }); const draft = useComposerDraftStore.getState().getComposerDraft(target); + expect(draft?.prompt).not.toContain(removedImageContextId); await requireHook(hook).saveEdit( { ...savedContent(draft?.prompt ?? ""), threadContexts: draft?.threadContexts ?? [] }, () => {}, @@ -387,7 +449,11 @@ describe("useQueuedRunEdit", () => { expect(mocks.editQueuedRun).toHaveBeenCalledWith( expect.objectContaining({ input: expect.objectContaining({ - edit: expect.objectContaining({ context: { version: 1, records: [kept] } }), + text: draft?.prompt, + edit: expect.objectContaining({ + attachments: [keptFile], + context: { version: 1, records: [keptFileRecord, kept] }, + }), }), }), ); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index 77989f8aebc0d..a33fd9177635c 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -69,6 +69,7 @@ import type { ChatComposerHandle } from "./ChatComposer"; import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles"; import { composerDraftContentChanged } from "./composerSend.logic"; import { + attachmentContextIdsForRecord, discardQueuedEditDraft, prepareQueuedEditAttachments, recoverQueuedMessageEdit, @@ -80,10 +81,9 @@ interface EditingQueuedRun { readonly runId: RunId; readonly messageId: MessageId; readonly originalText: string; + readonly originalAttachments: ReadonlyArray; readonly existingAttachments: ReadonlyArray; readonly context?: OrchestrationMessageContext | undefined; - /** Removing a server attachment changes the message even when the draft looks untouched. */ - readonly removedExistingAttachment?: true; } // Keyed by the route thread, so an edit survives navigating away and back. @@ -238,13 +238,34 @@ export function useQueuedRunEdit(input: { const urlByAttachmentId = new Map( imageResources.map((resource, index) => [resource.attachmentId, imageUrls[index] ?? null]), ); + const originalReferencedContextIds = + editing === null ? null : new Set(collectInlineContextIds(editing.originalText)); + const attachmentContextIds = (attachment: ChatAttachment) => + editing === null + ? [] + : attachmentContextIdsForRecord(editing.context, attachment).filter((contextId) => + originalReferencedContextIds!.has(contextId), + ); const editingAttachments = editing === null ? null : editing.existingAttachments.map((attachment) => ({ attachment, url: urlByAttachmentId.get(attachment.id) ?? null, + contextIds: attachmentContextIds(attachment), })); + const existingAttachmentIds = new Set( + (editing?.existingAttachments ?? []).map((attachment) => attachment.id), + ); + const removedEditingAttachments = + editing === null + ? [] + : editing.originalAttachments + .filter((attachment) => !existingAttachmentIds.has(attachment.id)) + .map((attachment) => ({ + attachment, + contextIds: attachmentContextIds(attachment), + })); const focusComposerSoon = () => { window.requestAnimationFrame(() => composerRef.current?.focusAtEnd()); @@ -290,6 +311,7 @@ export function useQueuedRunEdit(input: { runId: request.runId, messageId: request.messageId, originalText: text, + originalAttachments: request.attachments, existingAttachments: request.attachments, context, }, @@ -313,7 +335,13 @@ export function useQueuedRunEdit(input: { threadTarget: threadDraftTarget, originalText: edit.originalText, originalReplyTo: reply ?? null, - removedExistingAttachment: edit.removedExistingAttachment === true, + removedExistingAttachment: + edit.existingAttachments.length < edit.originalAttachments.length, + existingAttachmentContextIds: (edit.context?.records ?? []).flatMap((record) => + (record.kind === "image" || record.kind === "file") && "attachmentId" in record + ? [record.contextId] + : [], + ), }); if (recovery === "clean") return; const title = appAtomRegistry.get( @@ -345,13 +373,39 @@ export function useQueuedRunEdit(input: { focusComposerSoon(); }); const removeEditingAttachment = useStableCallback((attachmentId: string) => { + const removed = editing?.existingAttachments.find( + (attachment) => attachment.id === attachmentId, + ); + const contextIds = removed ? attachmentContextIdsForRecord(editing?.context, removed) : []; queuedRunEdits.update(editKey, (current) => ({ ...current, - removedExistingAttachment: true, existingAttachments: current.existingAttachments.filter( (attachment) => attachment.id !== attachmentId, ), })); + if (editing !== null && contextIds.length > 0) { + const target = queuedRunEditDraftId(routeThreadRef, editing.runId); + const store = useComposerDraftStore.getState(); + const currentPrompt = store.getComposerDraft(target)?.prompt ?? ""; + const nextPrompt = contextIds.reduce( + (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt, + currentPrompt, + ); + if (nextPrompt !== currentPrompt) store.setPrompt(target, nextPrompt); + } + }); + const restoreEditingAttachment = useStableCallback((attachment: ChatAttachment) => { + queuedRunEdits.update(editKey, (current) => { + const keptIds = new Set([ + ...current.existingAttachments.map((entry) => entry.id), + attachment.id, + ]); + // Filtering the originals keeps the restored attachment in its original position. + return { + ...current, + existingAttachments: current.originalAttachments.filter((entry) => keptIds.has(entry.id)), + }; + }); }); // The same move as the queued row's "Send now" while a turn runs. @@ -478,9 +532,11 @@ export function useQueuedRunEdit(input: { isSaving, draftTarget, editingAttachments, + removedEditingAttachments, beginEdit, cancelEdit, removeEditingAttachment, + restoreEditingAttachment, saveEdit, }; } diff --git a/apps/web/src/components/composerContextPresentation.test.ts b/apps/web/src/components/composerContextPresentation.test.ts index 77b0a5fb7815e..641e190ef86a3 100644 --- a/apps/web/src/components/composerContextPresentation.test.ts +++ b/apps/web/src/components/composerContextPresentation.test.ts @@ -1,8 +1,16 @@ -import { ThreadId } from "@t3tools/contracts"; +import { ChatAttachmentId, ComposerContextId, EnvironmentId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { buildMessageContext } from "~/lib/composerContextRecords"; -import { composerContextRecordsFromDraft } from "./composerContextPresentation"; +import { composerFileNeedsReattach } from "~/composerDraftStore"; +import { + attachmentContextRecord, + buildMessageContext, + isSameComposerContextPayload, +} from "~/lib/composerContextRecords"; +import { + composerContextRecordsFromDraft, + uploadedContextRecordFromDraft, +} from "./composerContextPresentation"; describe("composerContextRecordsFromDraft", () => { it("resolves each wire reference to its own backing draft even when producer ids collide", () => { @@ -53,4 +61,88 @@ describe("composerContextRecordsFromDraft", () => { expect(draftRecords.get(record.contextId)?.kind).toBe(record.kind); } }); + + it("resolves existing queued attachments under their original wire context ids", () => { + const environmentId = EnvironmentId.make("env-1"); + const imageContextId = ComposerContextId.make("image_local-shot"); + const fileContextId = ComposerContextId.make("file_local-notes"); + const imageId = ChatAttachmentId.make("server-shot"); + const fileId = ChatAttachmentId.make("server-notes"); + const source = { + kind: "snap-shot" as const, + capturedAt: "2026-11-22T14:00:00.000Z", + appName: "Safari", + windowTitle: "Example", + }; + const imageAttachment = { + type: "image" as const, + id: imageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + source, + }; + const draftRecords = composerContextRecordsFromDraft({ + terminalContexts: [], + environmentId, + existingAttachments: [ + { + attachment: imageAttachment, + url: "http://127.0.0.1/assets/server-shot", + contextIds: [imageContextId], + }, + { + attachment: { + type: "file", + id: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }, + url: null, + contextIds: [fileContextId], + }, + ], + }); + + const imageEntry = draftRecords.get(imageContextId); + expect(imageEntry).toMatchObject({ + kind: "image", + record: { + id: imageId, + name: "image.png", + previewUrl: "http://127.0.0.1/assets/server-shot", + source, + }, + }); + const uploadedImageRecord = uploadedContextRecordFromDraft(imageEntry!); + expect(uploadedImageRecord).toMatchObject({ + kind: "image", + contextId: imageContextId, + attachmentId: imageId, + source, + }); + expect( + isSameComposerContextPayload( + uploadedImageRecord!, + attachmentContextRecord({ + attachment: imageAttachment, + attachmentId: imageId, + contextId: imageContextId, + }), + ), + ).toBe(true); + + const fileEntry = draftRecords.get(fileContextId); + expect(fileEntry?.kind).toBe("file"); + if (fileEntry?.kind === "file") { + expect(composerFileNeedsReattach(fileEntry.record)).toBe(false); + expect(fileEntry.record.uploadEnvironmentId).toBe(environmentId); + } + expect(uploadedContextRecordFromDraft(fileEntry!)).toMatchObject({ + kind: "file", + contextId: fileContextId, + attachmentId: fileId, + }); + }); }); diff --git a/apps/web/src/components/composerContextPresentation.tsx b/apps/web/src/components/composerContextPresentation.tsx index ab7ce9b40186b..0fb3f31e5413e 100644 --- a/apps/web/src/components/composerContextPresentation.tsx +++ b/apps/web/src/components/composerContextPresentation.tsx @@ -2,7 +2,10 @@ import ChatMarkdown from "./ChatMarkdown"; import { isSvgAttachment } from "@t3tools/shared/image"; import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview"; import type { + ChatAttachment, + ComposerContextId, EnvironmentContextRecord, + EnvironmentId, PreviewAnnotationPayload, ThreadContextRecord, } from "@t3tools/contracts"; @@ -40,6 +43,7 @@ import { } from "~/lib/composerContextRecords"; import type { TerminalContextDraft } from "~/lib/terminalContext"; import type { ReviewCommentContext } from "~/reviewCommentContext"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./chat/queuedMessageEdit"; import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts"; import { EnvironmentContextChip } from "./EnvironmentContextChip"; import { ThreadContextChip } from "./ThreadContextChip"; @@ -60,6 +64,11 @@ import { UnresolvedChip, } from "./contextChipParts"; +export interface ComposerImageContextAttachment extends Omit { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; +} + export type ComposerDraftContextRecord = | { kind: "terminal"; record: TerminalContextDraft } | { kind: "review-comment"; record: ReviewCommentContext } @@ -68,8 +77,18 @@ export type ComposerDraftContextRecord = record: PreviewAnnotationPayload; screenshot?: ComposerImageAttachment | undefined; } - | { kind: "image"; record: ComposerImageAttachment; upload?: AttachmentUploadState | undefined } - | { kind: "file"; record: ComposerFileAttachment; upload?: AttachmentUploadState | undefined } + | { + kind: "image"; + record: ComposerImageContextAttachment; + upload?: AttachmentUploadState | undefined; + contextId?: ComposerContextId | undefined; + } + | { + kind: "file"; + record: ComposerFileAttachment; + upload?: AttachmentUploadState | undefined; + contextId?: ComposerContextId | undefined; + } | { kind: "thread"; record: ThreadContextRecord } | { kind: "environment"; record: EnvironmentContextRecord }; @@ -84,7 +103,7 @@ export const EMPTY_COMPOSER_CONTEXT_RECORDS: ComposerDraftContextRecords = new M export function uploadedContextRecordFromDraft(entry: ComposerDraftContextRecord) { if (entry.kind !== "image" && entry.kind !== "file") return null; - return uploadedAttachmentContextRecord(entry.record, entry.upload); + return uploadedAttachmentContextRecord(entry.record, entry.upload, entry.contextId); } export const ComposerContextRecordsContext = createContext( @@ -99,9 +118,44 @@ export function composerContextRecordsFromDraft(input: { environmentContexts?: ReadonlyArray; images?: ReadonlyArray; files?: ReadonlyArray; + existingAttachments?: + | ReadonlyArray<{ + readonly attachment: ChatAttachment; + readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; + }> + | undefined; + environmentId?: EnvironmentId | undefined; uploadsByImageId?: Readonly>; }): ComposerDraftContextRecords { const records = new Map(); + for (const entry of input.existingAttachments ?? []) { + for (const contextId of entry.contextIds ?? []) { + if (isQueuedImageAttachment(entry.attachment)) { + records.set(contextId, { + kind: "image", + contextId, + record: { + ...entry.attachment, + previewUrl: entry.url ?? "", + file: null, + uploadedAttachmentId: entry.attachment.id, + }, + }); + } else if (isQueuedFileAttachment(entry.attachment)) { + records.set(contextId, { + kind: "file", + contextId, + record: { + ...entry.attachment, + file: null, + uploadedAttachmentId: entry.attachment.id, + ...(input.environmentId ? { uploadEnvironmentId: input.environmentId } : {}), + }, + }); + } + } + } for (const record of input.images ?? []) { records.set(imageContextReference(record).contextId, { kind: "image", @@ -183,7 +237,7 @@ function useUploadStatusSuffix( } function attachmentTooltip( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: Pick, upload: AttachmentUploadState | undefined, resolve: MessageResolver, ): string { @@ -193,7 +247,7 @@ function attachmentTooltip( } function ImageContextChip(props: { - record: ComposerImageAttachment; + record: ComposerImageContextAttachment; upload: AttachmentUploadState | undefined; }) { const actions = use(ComposerContextActionsContext); diff --git a/apps/web/src/lib/composerContextRecords.ts b/apps/web/src/lib/composerContextRecords.ts index 31b7239719f1a..6f1c9d3bb8227 100644 --- a/apps/web/src/lib/composerContextRecords.ts +++ b/apps/web/src/lib/composerContextRecords.ts @@ -9,6 +9,8 @@ import { COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS, } from "@t3tools/contracts"; import type { + ChatFileAttachment, + ChatImageAttachment, ComposerContextId, ComposerContextRecord, EnvironmentContextRecord, @@ -488,39 +490,59 @@ export function fileContextReference(file: ComposerFileAttachment): ComposerCont }; } +export type ComposerContextAttachment = + | ComposerImageAttachment + | ComposerFileAttachment + | (Omit & { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; + }) + | ChatImageAttachment + | ChatFileAttachment; + export interface BoundComposerAttachment { - attachment: ComposerImageAttachment | ComposerFileAttachment; + attachment: ComposerContextAttachment; attachmentId: string; + contextId?: ComposerContextId | undefined; } /** Returns null until the attachment has a server id. */ export function uploadedAttachmentContextRecord( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: ComposerContextAttachment, upload: AttachmentUploadState | undefined, + contextId?: ComposerContextId, ): ImageContextRecord | FileContextRecord | null { const attachmentId = - attachment.type === "file" && attachment.uploadedAttachmentId !== undefined + "uploadedAttachmentId" in attachment && attachment.uploadedAttachmentId !== undefined ? attachment.uploadedAttachmentId : upload?.status === "ready" ? upload.attachmentId : undefined; - return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId }); + return attachmentId === undefined + ? null + : attachmentContextRecord({ attachment, attachmentId, contextId }); } export function attachmentContextRecord( bound: BoundComposerAttachment, ): ImageContextRecord | FileContextRecord { - const { attachment, attachmentId } = bound; + const { attachment, attachmentId, contextId } = bound; const base = { version: 1 as const, - contextId: toKindScopedComposerContextId(attachment.type, attachment.id), + contextId: contextId ?? toKindScopedComposerContextId(attachment.type, attachment.id), label: sanitizeComposerContextLabel(attachment.name, attachment.type), attachmentId, name: attachment.name, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes, }; - return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" }; + return attachment.type === "image" + ? { + ...base, + kind: "image", + ...(attachment.source !== undefined ? { source: attachment.source } : {}), + } + : { ...base, kind: "file" }; } export function buildMessageContext(input: { From 28706aceb6fb3babf2cbae0dc0c3edd93b9b6d5f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 11:45:51 -0800 Subject: [PATCH 096/162] fix(server): unlinking an environment ends its session on the other machine (#41005) --- apps/server/src/auth/EnvironmentAuth.ts | 23 ++++++++ apps/server/src/auth/McpOAuth.test.ts | 17 ++++++ apps/server/src/auth/McpOAuth.ts | 1 + apps/server/src/auth/mcpOAuthHttp.ts | 13 ++++ apps/server/src/cli/environment.ts | 14 +++-- .../src/mcp/toolkits/orchestrator/handlers.ts | 4 +- .../src/mcp/toolkits/orchestrator/tools.ts | 2 +- apps/server/src/peer/PeerLinks.test.ts | 16 ++++- apps/server/src/peer/PeerLinks.ts | 59 +++++++++++++++++-- .../src/provider/agentContextBudget.json | 2 +- apps/server/src/ws.ts | 3 +- .../settings/LinkedEnvironmentsSettings.tsx | 15 ++++- apps/web/src/i18n/translations/de.json | 4 +- apps/web/src/i18n/translations/en.json | 4 +- apps/web/src/i18n/translations/es.json | 4 +- apps/web/src/i18n/translations/fr.json | 4 +- apps/web/src/i18n/translations/ja.json | 4 +- apps/web/src/i18n/translations/ko.json | 4 +- apps/web/src/i18n/translations/pt-BR.json | 4 +- apps/web/src/i18n/translations/ru.json | 4 +- apps/web/src/i18n/translations/sv.json | 4 +- apps/web/src/i18n/translations/zh.json | 4 +- docs/user/remote-access.md | 6 +- packages/contracts/src/auth.ts | 9 +++ packages/contracts/src/environmentHttp.ts | 7 +++ packages/contracts/src/orchestratorMcp.ts | 1 + packages/contracts/src/peerLink.ts | 6 +- 27 files changed, 206 insertions(+), 32 deletions(-) diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index 202ca25310d13..977840617d04c 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -635,6 +635,10 @@ export class EnvironmentAuth extends Context.Service< readonly authenticateMcpClient: ( request: HttpServerRequest.HttpServerRequest, ) => Effect.Effect; + /** Ends the MCP client session `token` belongs to. False when it is no live MCP client token. */ + readonly revokeMcpClientToken: ( + token: string, + ) => Effect.Effect; readonly issueMcpClientSession: (input: { readonly label: string; readonly access: AuthMcpClientAccess; @@ -1637,6 +1641,24 @@ export const make = Effect.gen(function* () { ); }; + const revokeMcpClientToken: EnvironmentAuth["Service"]["revokeMcpClientToken"] = Effect.fn( + "EnvironmentAuth.revokeMcpClientToken", + )(function* (token) { + const session = yield* sessions.verify(token).pipe( + Effect.asSome, + Effect.catchIf(SessionStore.isSessionCredentialInvalidError, () => Effect.succeedNone), + Effect.mapError((cause) => new ServerAuthSessionCredentialValidationError({ cause })), + ); + if ( + Option.isNone(session) || + session.value.subject !== MCP_CLIENT_SUBJECT || + session.value.method !== "bearer-access-token" + ) { + return false; + } + return yield* revokeSession(session.value.sessionId); + }); + const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) => sessions .issue({ @@ -1719,6 +1741,7 @@ export const make = Effect.gen(function* () { issueWebSocketTicket, issueStartupPairingUrl, authenticateMcpClient, + revokeMcpClientToken, issueMcpClientSession, consumeMcpApprovalCode, }); diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index d72a716673e66..f66d0b1c6e81c 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -209,6 +209,7 @@ it.effect("derives discovery metadata from the origin the client reached", () => authorization_endpoint: `${ORIGIN}/oauth/mcp/authorize`, token_endpoint: `${ORIGIN}/oauth/mcp/token`, registration_endpoint: `${ORIGIN}/oauth/mcp/register`, + revocation_endpoint: `${ORIGIN}/oauth/mcp/revoke`, code_challenge_methods_supported: ["S256"], }); }), @@ -396,6 +397,22 @@ it.live("signs in with a pairing code and issues a token only /mcp accepts", () }), ); expect(ticket.status).toBe(401); + + // Revocation ends only an MCP client's own session; any other token is answered alike and kept. + const owner = yield* auth.exchangeBootstrapCredentialForAccessToken( + (yield* auth.issuePairingCredential()).credential, + undefined, + { deviceType: "desktop" }, + ); + const bearer = (token: string) => + HttpServerRequest.fromWeb(at("/api", { headers: { authorization: `Bearer ${token}` } })); + for (const other of ["not-a-token", owner.access_token]) { + expect((yield* handler(at("/oauth/mcp/revoke", form({ token: other })))).status).toBe(200); + } + yield* auth.authenticateHttpRequest(bearer(owner.access_token)); + const revoked = yield* handler(at("/oauth/mcp/revoke", form({ token: token.access_token }))); + expect(revoked.status).toBe(200); + yield* auth.authenticateMcpClient(bearer(token.access_token)).pipe(Effect.flip); }), ), ); diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index 9ab0bfe1c176a..e63c600ae1b2d 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -97,6 +97,7 @@ export const authorizationServerMetadata = ( authorization_endpoint: `${urls.issuer}/oauth/mcp/authorize`, token_endpoint: `${urls.issuer}/oauth/mcp/token`, registration_endpoint: `${urls.issuer}/oauth/mcp/register`, + revocation_endpoint: `${urls.issuer}/oauth/mcp/revoke`, response_types_supported: ["code"], grant_types_supported: ["authorization_code"], code_challenge_methods_supported: ["S256"], diff --git a/apps/server/src/auth/mcpOAuthHttp.ts b/apps/server/src/auth/mcpOAuthHttp.ts index 6e10362000adf..c9ffde0ecda99 100644 --- a/apps/server/src/auth/mcpOAuthHttp.ts +++ b/apps/server/src/auth/mcpOAuthHttp.ts @@ -9,6 +9,7 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { HttpServerRequest, HttpServerResponse } from "effect/http"; @@ -20,6 +21,7 @@ import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth"; import * as CloudLink from "../cloud/CloudLink.ts"; import { agentApprovalAppUrlConfig } from "../cloud/publicConfig.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as EnvironmentAuth from "./EnvironmentAuth.ts"; import * as McpOAuth from "./McpOAuth.ts"; import { renderErrorPage } from "./mcpOAuthHtml.ts"; @@ -75,6 +77,7 @@ export const layer = HttpApiBuilder.group( "mcpOAuth", Effect.fnUntraced(function* (handlers) { const oauth = yield* McpOAuth.McpOAuth; + const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth; const cloudLink = yield* CloudLink.CloudLink; const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity; const hostedAppUrl = yield* agentApprovalAppUrlConfig.pipe( @@ -205,6 +208,16 @@ export const layer = HttpApiBuilder.group( yield* noStore; return yield* oauth.exchangeCode({ request, urls: yield* requestUrls, token: payload }); }), + ) + .handle("revoke", ({ payload }) => + Effect.gen(function* () { + yield* noStore; + // RFC 7009 §2.2: an unknown or already revoked token gets the same 200 as a revoked one. + if (payload.token === undefined) return; + yield* environmentAuth + .revokeMcpClientToken(Redacted.value(payload.token)) + .pipe(Effect.orDie); + }), ); }), ); diff --git a/apps/server/src/cli/environment.ts b/apps/server/src/cli/environment.ts index 8c6d2ab78c041..9243d0340eabf 100644 --- a/apps/server/src/cli/environment.ts +++ b/apps/server/src/cli/environment.ts @@ -293,16 +293,20 @@ const environmentUnlinkCommand = Command.make("unlink", { ), }).pipe( Command.withDescription( - "Forget a linked environment here. Revoke it in that environment's Sharing & access to end its session there too.", + "Forget a linked environment here, and end its session there when that environment answers.", ), Command.withHandler((flags) => runWithPeerLinks(flags, (links) => Effect.gen(function* () { - const removed = yield* links.unlink(EnvironmentId.make(flags.environmentId)); + const { removed, endedThere } = yield* links.unlink( + EnvironmentId.make(flags.environmentId), + ); yield* Console.log( - removed - ? `Forgot ${flags.environmentId}. Revoke it in that environment's Sharing & access to end its session there.\n` - : `No linked environment ${flags.environmentId}.\n`, + !removed + ? `No linked environment ${flags.environmentId}.\n` + : endedThere + ? `Forgot ${flags.environmentId} and ended its session there.\n` + : `Forgot ${flags.environmentId}. It did not answer, so revoke it in that environment's Sharing & access to end its session there.\n`, ); }), ), diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index d90a118be468e..57932ac21a619 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -218,7 +218,7 @@ const handlers = { t3_environment_unlink: McpToolAccess.writesEnvironment(({ environmentId }) => Effect.gen(function* () { const links = yield* PeerLinks.PeerLinks; - const removed = yield* links + const result = yield* links .unlink(environmentId) .pipe( Effect.mapError( @@ -226,7 +226,7 @@ const handlers = { new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }), ), ); - return { environmentId, removed }; + return { environmentId, ...result }; }), ), t3_thread_interrupt: McpToolAccess.writesThreads( diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index b2866bb0babc5..f617b61fabaa3 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -350,7 +350,7 @@ const EnvironmentLinkTool = Tool.make("t3_environment_link", { const EnvironmentUnlinkTool = Tool.make("t3_environment_unlink", { description: - "Forget a linked environment. That machine's Connections list its session until revoked there.", + "Forget a linked environment. Its session on that machine ends too when the machine answers.", parameters: OrchestratorMcpEnvironmentUnlinkInput, success: OrchestratorMcpEnvironmentUnlinkResult, failure: OrchestratorMcpFailure, diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts index 0b1f4f716474c..8f1d6cc381d63 100644 --- a/apps/server/src/peer/PeerLinks.test.ts +++ b/apps/server/src/peer/PeerLinks.test.ts @@ -157,7 +157,7 @@ it.effect("routes peer reads to readers and sees uncommitted link updates", () = expect((yield* links.list)[0]?.label).toBe("Uncommitted box"); }), ); - expect(yield* links.unlink(box.environmentId)).toBe(true); + expect(yield* links.unlink(box.environmentId)).toEqual({ removed: true, endedThere: false }); expect(yield* links.list).toEqual([]); }), ); @@ -206,6 +206,20 @@ it.effect("links with a pairing code, and the peer holds its agents to the limit // A refusal keeps the peer's reason. const notFound = yield* probe(a, undefined, "refuse").pipe(Effect.flip); expect(notFound).toMatchObject({ code: "thread_not_found", message: "No such thread." }); + + // Unlinking ends the session on B too, instead of leaving a live credential behind. + expect(yield* a.links.unlink(box.environmentId)).toEqual({ removed: true, endedThere: true }); + expect(yield* linkedSessions(b)).toEqual([]); + + // An address that now answers as another environment never receives the token. + const other = yield* serveApart(descriptorOf("environment-other", "Other")); + const relink = yield* b.auth.issuePairingCredential({ access: "auto", purpose: "peer-link" }); + yield* a.links.link({ url: b.url, pairingCode: relink.credential, access: "auto" }); + yield* a.sql`UPDATE peer_environment_links SET urls_json = ${JSON.stringify([other.url])}`; + expect(yield* a.links.unlink(box.environmentId)).toEqual({ + removed: true, + endedThere: false, + }); }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/peer/PeerLinks.ts b/apps/server/src/peer/PeerLinks.ts index 5325e5745c5d7..859266c469c70 100644 --- a/apps/server/src/peer/PeerLinks.ts +++ b/apps/server/src/peer/PeerLinks.ts @@ -116,8 +116,10 @@ export class PeerLinks extends Context.Service< readonly get: ( environmentId: EnvironmentId, ) => Effect.Effect, PeerLinkError>; - /** Forgets the link here. The peer still lists the session until it is revoked there. */ - readonly unlink: (environmentId: EnvironmentId) => Effect.Effect; + /** Forgets the link here, then asks the peer to end the link's session. */ + readonly unlink: ( + environmentId: EnvironmentId, + ) => Effect.Effect<{ readonly removed: boolean; readonly endedThere: boolean }, PeerLinkError>; /** An address that answers as the linked peer, with its token, ready to call. */ readonly resolve: ( environmentId: EnvironmentId, @@ -665,16 +667,63 @@ const make = Effect.gen(function* () { ), ); + /** Best effort: a peer that is gone or too old to revoke lets its session expire instead. */ + const revokeAtPeer = Effect.fn("PeerLinks.revokeAtPeer")( + function* (environmentId: EnvironmentId, urlsJson: string, token: string) { + const urls = yield* decodeUrls(urlsJson); + // A race over no addresses never settles. + if (urls.length === 0) return false; + yield* Effect.raceAll( + urls.map((url) => + // An address can change hands after linking; only the linked peer may see the token. + answersAs(url, environmentId).pipe( + Effect.flatMap(Effect.fromOption), + Effect.andThen(clientFor(url)), + Effect.flatMap((client) => + client.mcpOAuth + .revoke({ payload: { token: Redacted.make(token) } }) + .pipe(Effect.timeout(probeTimeout(url))), + ), + ), + ), + ); + return true; + }, + Effect.catchCause((cause) => + Effect.logDebug("The unlinked peer did not revoke the link's session", { cause }).pipe( + Effect.as(false), + ), + ), + ); + const unlink: PeerLinks["Service"]["unlink"] = Effect.fn("PeerLinks.unlink")( function* (environmentId) { - const deleted = yield* sql<{ secret_name: string }>` + const deleted = yield* sql<{ secret_name: string; urls_json: string }>` DELETE FROM peer_environment_links WHERE environment_id = ${environmentId} - RETURNING secret_name + RETURNING secret_name, urls_json `.pipe(Effect.catch(failStorage)); + let endedThere = false; for (const row of deleted) { + // Unreadable only skips the revocation; the secret is still removed below. + const token = yield* secrets + .get(row.secret_name) + .pipe( + Effect.catch((cause) => + Effect.logWarning("Could not read the unlinked peer's token", { cause }).pipe( + Effect.as(Option.none()), + ), + ), + ); yield* secrets.remove(row.secret_name).pipe(Effect.catch(failStorage)); + if (Option.isSome(token)) { + endedThere = yield* revokeAtPeer( + environmentId, + row.urls_json, + new TextDecoder().decode(token.value), + ); + } } - return deleted.length > 0; + return { removed: deleted.length > 0, endedThere }; }, ); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 222f23b6b02d9..4d4286111477f 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 59170 + "mcpToolListJsonBytes": 59168 } diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index d1db4372ab871..b5faaaa16f97c 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2734,8 +2734,7 @@ export const layerWsRpc = ( [WS_METHODS.peerLinksNames]: (_input) => peerLinks.names.pipe(Effect.map((links) => ({ links }))), [WS_METHODS.peerLinksLink]: (input) => peerLinks.link(input), - [WS_METHODS.peerLinksUnlink]: ({ environmentId }) => - peerLinks.unlink(environmentId).pipe(Effect.map((removed) => ({ removed }))), + [WS_METHODS.peerLinksUnlink]: ({ environmentId }) => peerLinks.unlink(environmentId), [WS_METHODS.peerLinksSubscribeThread]: (input) => peerThreadRelay.subscribe(input), [WS_METHODS.peerLinksThreadHistoryPage]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 954c0e1c4ee3c..5ab6debec7255 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -659,7 +659,7 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu const forget = async () => { const confirmed = await (requestConfirmDialog( gt( - "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.", { label: link.label }, ), { variant: "destructive" }, @@ -668,7 +668,18 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu setBusy(true); const result = await unlink({ environmentId, input: { environmentId: link.environmentId } }); setBusy(false); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + if (result._tag === "Success") { + if (result.value.removed && result.value.endedThere !== true) { + toastManager.add({ + type: "warning", + title: gt("{label} did not answer", { label: link.label }), + description: gt( + "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + { label: link.label }, + ), + }); + } + } else if (!isAtomCommandInterrupted(result)) { failureToast(gt("Could not forget the link"), String(squashAtomCommandFailure(result))); } }; diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0db2fb8989ce2..c9aebc46cd49d 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -8928,7 +8928,9 @@ "fb71127e5746a6bc": "Unter „Freigabe & Zugriff“ dort oder mit t3 pair", "1e3fee7084791773": "Auch {target} zurück mit {source} verknüpfen", "ea34a190b0bd804c": "Agenten auf {target} können dann auch auf {source} arbeiten.", - "ad5ed0ce61b966eb": "{label} vergessen? Agenten von hier arbeiten dort nicht mehr. Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.", + "974f8c65e8b5f492": "{label} vergessen? Agenten hier arbeiten dort nicht mehr, und ihre Sitzung auf {label} endet ebenfalls, wenn es antwortet.", + "6cf9e3083b15614f": "{label} hat nicht geantwortet", + "34ccbdf619b83be3": "Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.", "81c9796bf61b306a": "Verknüpfung konnte nicht vergessen werden", "130e51beb6cf5aad": "Umgebung verknüpfen", "122c3e355699e69d": "Agenten hier können dort dann Threads starten, ihnen Nachrichten senden und auf sie warten. Sie erscheint unter „Autorisierte Clients“ in „Freigabe & Zugriff“ dieser Umgebung und kann dort widerrufen werden.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 3aa61a18f6b2b..0808df7eab79b 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -8936,7 +8936,9 @@ "fb71127e5746a6bc": "From Sharing & access there, or t3 pair", "1e3fee7084791773": "Also link {target} back to {source}", "ea34a190b0bd804c": "Agents on {target} can then work on {source} too.", - "ad5ed0ce61b966eb": "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + "974f8c65e8b5f492": "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.", + "6cf9e3083b15614f": "{label} did not answer", + "34ccbdf619b83be3": "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", "81c9796bf61b306a": "Could not forget the link", "130e51beb6cf5aad": "Link an environment", "122c3e355699e69d": "Agents here can then launch, message and wait on threads there. It appears under Authorized clients in that environment's Sharing & access, where it can be revoked.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 60ddca69b570f..88f660710fce2 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -8926,7 +8926,9 @@ "fb71127e5746a6bc": "Desde Compartir y acceso allí, o t3 pair", "1e3fee7084791773": "Vincular también {target} de vuelta a {source}", "ea34a190b0bd804c": "Los agentes de {target} podrán trabajar también en {source}.", - "ad5ed0ce61b966eb": "¿Olvidar {label}? Los agentes de aquí dejarán de trabajar allí. Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.", + "974f8c65e8b5f492": "¿Olvidar {label}? Los agentes de aquí dejan de trabajar allí, y su sesión en {label} también termina si responde.", + "6cf9e3083b15614f": "{label} no respondió", + "34ccbdf619b83be3": "Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.", "81c9796bf61b306a": "No se pudo olvidar el vínculo", "130e51beb6cf5aad": "Vincular un entorno", "122c3e355699e69d": "Así los agentes de aquí podrán iniciar hilos allí, enviarles mensajes y esperarlos. Aparece en Clientes autorizados, en Compartir y acceso de ese entorno, donde se puede revocar.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index fdcba31a1032f..114dd21e96fd4 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -8928,7 +8928,9 @@ "fb71127e5746a6bc": "Depuis Partage et accès sur cette machine, ou t3 pair", "1e3fee7084791773": "Associer aussi {target} en retour à {source}", "ea34a190b0bd804c": "Les agents de {target} pourront alors aussi travailler sur {source}.", - "ad5ed0ce61b966eb": "Oublier {label} ? Les agents d’ici cessent d’y travailler. Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.", + "974f8c65e8b5f492": "Oublier {label} ? Les agents d’ici cessent d’y travailler, et leur session sur {label} prend fin aussi s’il répond.", + "6cf9e3083b15614f": "{label} n’a pas répondu", + "34ccbdf619b83be3": "Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.", "81c9796bf61b306a": "Impossible d’oublier l’association", "130e51beb6cf5aad": "Associer un environnement", "122c3e355699e69d": "Les agents d’ici pourront alors lancer des fils là-bas, leur envoyer des messages et les attendre. L’association apparaît sous Clients autorisés dans Partage et accès de cet environnement, où elle peut être révoquée.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 13379225ecf26..e207333046ee3 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -8884,7 +8884,9 @@ "fb71127e5746a6bc": "リンク先の「共有とアクセス」、または t3 pair から", "1e3fee7084791773": "{target} から {source} へも逆方向にリンクする", "ea34a190b0bd804c": "{target} のエージェントも {source} で作業できるようになります。", - "ad5ed0ce61b966eb": "{label} を削除しますか?ここのエージェントはそこで作業できなくなります。そこでのセッションも終了するには、{label} の「共有とアクセス」で \"T3 Code · …\" を取り消してください。", + "974f8c65e8b5f492": "{label} を削除しますか?ここのエージェントはそこで作業できなくなり、{label} が応答すればそこでのセッションも終了します。", + "6cf9e3083b15614f": "{label} が応答しませんでした", + "34ccbdf619b83be3": "そこでのセッションも終了するには、{label} の「共有とアクセス」で \"T3 Code · …\" を取り消してください。", "81c9796bf61b306a": "リンクを削除できませんでした", "130e51beb6cf5aad": "環境をリンク", "122c3e355699e69d": "これで、ここのエージェントがそこでスレッドを起動し、メッセージを送り、完了を待てるようになります。リンクはその環境の「共有とアクセス」の「承認済みクライアント」に表示され、そこで取り消せます。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index cc8261d7681ff..d0c34a39635f7 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -8887,7 +8887,9 @@ "fb71127e5746a6bc": "그곳의 공유 및 액세스 또는 t3 pair에서", "1e3fee7084791773": "{target}에서 {source}(으)로도 반대 방향 연결", "ea34a190b0bd804c": "그러면 {target}의 에이전트도 {source}에서 작업할 수 있습니다.", - "ad5ed0ce61b966eb": "{label}을(를) 삭제할까요? 이곳의 에이전트가 그곳에서 더 이상 작업하지 않습니다. 그곳의 세션도 끝내려면 {label}의 공유 및 액세스에서 \"T3 Code · …\"를 취소하세요.", + "974f8c65e8b5f492": "{label}을(를) 잊을까요? 여기의 에이전트는 그곳에서 더 이상 작업하지 않으며, {label}이(가) 응답하면 그곳의 세션도 종료됩니다.", + "6cf9e3083b15614f": "{label}이(가) 응답하지 않았습니다", + "34ccbdf619b83be3": "그곳의 세션도 끝내려면 {label}의 공유 및 액세스에서 \"T3 Code · …\"를 취소하세요.", "81c9796bf61b306a": "링크를 삭제할 수 없습니다", "130e51beb6cf5aad": "환경 연결", "122c3e355699e69d": "그러면 이곳의 에이전트가 그곳에서 스레드를 시작하고, 메시지를 보내고, 기다릴 수 있습니다. 해당 환경의 공유 및 액세스에서 승인된 클라이언트에 표시되며 그곳에서 취소할 수 있습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index a9ce3832a0b9f..d32f4d0a45121 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -8927,7 +8927,9 @@ "fb71127e5746a6bc": "Em Compartilhamento e acesso de lá, ou t3 pair", "1e3fee7084791773": "Vincular também {target} de volta a {source}", "ea34a190b0bd804c": "Os agentes de {target} poderão trabalhar também em {source}.", - "ad5ed0ce61b966eb": "Esquecer {label}? Os agentes daqui deixam de funcionar lá. Revogue \"T3 Code · …\" em Compartilhamento e acesso de {label} para encerrar a sessão lá também.", + "974f8c65e8b5f492": "Esquecer {label}? Os agentes daqui param de trabalhar lá, e a sessão deles em {label} também termina se ele responder.", + "6cf9e3083b15614f": "{label} não respondeu", + "34ccbdf619b83be3": "Revogue \"T3 Code · …\" em Compartilhamento e acesso de {label} para encerrar a sessão lá também.", "81c9796bf61b306a": "Não foi possível esquecer o vínculo", "130e51beb6cf5aad": "Vincular um ambiente", "122c3e355699e69d": "Os agentes daqui poderão então iniciar threads lá, enviar mensagens e aguardá-las. Ele aparece em Clientes autorizados em Compartilhamento e acesso daquele ambiente, onde pode ser revogado.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index ee0fe30aa4f39..c000355e83081 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -8928,7 +8928,9 @@ "fb71127e5746a6bc": "Из раздела «Общий доступ» там или через t3 pair", "1e3fee7084791773": "Также привязать {target} в ответ к {source}", "ea34a190b0bd804c": "Тогда агенты на {target} смогут работать и на {source}.", - "ad5ed0ce61b966eb": "Забыть {label}? Агенты отсюда перестанут там работать. Чтобы завершить сеанс и там, отзовите «T3 Code · …» в разделе «Общий доступ» на {label}.", + "974f8c65e8b5f492": "Забыть {label}? Агенты отсюда перестанут там работать, а их сеанс на {label} тоже завершится, если он ответит.", + "6cf9e3083b15614f": "{label} не ответил", + "34ccbdf619b83be3": "Чтобы завершить сеанс и там, отзовите «T3 Code · …» в разделе «Общий доступ» на {label}.", "81c9796bf61b306a": "Не удалось забыть привязку", "130e51beb6cf5aad": "Привязать окружение", "122c3e355699e69d": "После этого агенты отсюда смогут запускать треды там, писать в них и ждать их. Связь появится в разделе «Авторизованные клиенты» в «Общем доступе» того окружения, где её можно отозвать.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index fb02753220b14..a9bfc4cecbe7e 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -8934,7 +8934,9 @@ "fb71127e5746a6bc": "Från Delning och åtkomst där, eller t3 pair", "1e3fee7084791773": "Länka även {target} tillbaka till {source}", "ea34a190b0bd804c": "Agenter på {target} kan då också arbeta på {source}.", - "ad5ed0ce61b966eb": "Glöm {label}? Agenter här slutar arbeta där. Återkalla ”T3 Code · …” under Delning och åtkomst på {label} för att avsluta sessionen där också.", + "974f8c65e8b5f492": "Glöm {label}? Agenter här slutar arbeta där, och deras session på {label} avslutas också om den svarar.", + "6cf9e3083b15614f": "{label} svarade inte", + "34ccbdf619b83be3": "Återkalla ”T3 Code · …” under Delning och åtkomst på {label} för att avsluta sessionen där också.", "81c9796bf61b306a": "Kunde inte glömma länken", "130e51beb6cf5aad": "Länka en miljö", "122c3e355699e69d": "Agenter här kan sedan starta, skicka meddelanden till och vänta på trådar där. Den visas under Auktoriserade klienter i miljöns Delning och åtkomst, där den kan återkallas.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 04044302284b7..2169040ad1c51 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -8944,7 +8944,9 @@ "fb71127e5746a6bc": "从远端“共享与访问”页面或 t3 pair 获取", "1e3fee7084791773": "同时将 {target} 反向关联到 {source}", "ea34a190b0bd804c": "之后 {target} 上的智能体也能在 {source} 上工作。", - "ad5ed0ce61b966eb": "忘记 {label}?此处的智能体将停止在那里工作。在 {label} 的“共享与访问”中撤销“T3 Code · …”,以同时结束那里的连接。", + "974f8c65e8b5f492": "忘记 {label}?此处的代理将不再在那里工作;如果 {label} 有响应,它们在那里的会话也会结束。", + "6cf9e3083b15614f": "{label} 没有响应", + "34ccbdf619b83be3": "在 {label} 的“共享与访问”中撤销“T3 Code · …”,以同时结束那里的连接。", "81c9796bf61b306a": "无法移除关联", "130e51beb6cf5aad": "关联环境", "122c3e355699e69d": "这里的智能体随后就能在该环境中启动会话、发送消息并等待结果。此连接将显示在该环境“共享与访问”的“已授权客户端”中,可在那里撤销。", diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 99255db9ac8cb..051445f03eb07 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -468,8 +468,10 @@ an address you trust: the code is sent there. machine's own threads, projects or settings, and they skip its project setup scripts. - The link shows up in that machine's **Settings → Sharing & access** like any - outside agent. Revoke it there to end it. **Forget** on this machine only - removes it here. + outside agent, and can be revoked there. **Forget** on this machine also ends + it there when that machine confirms it. If it can't, such as when it is + offline or on an older T3 Code, Forget says so; revoke it in that machine's + Sharing & access. - A link stays valid while agents use it. One unused for 30 days expires, as does one to a machine on an older T3 Code after 30 days; link again with a new pairing code. diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 826ffeb6b258e..5a630a6b7abe9 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -554,6 +554,8 @@ export const AuthMcpAuthorizationServerMetadata = Schema.Struct({ authorization_endpoint: Schema.String, token_endpoint: Schema.String, registration_endpoint: Schema.String, + // Older environments do not serve one. + revocation_endpoint: Schema.optionalKey(Schema.String), response_types_supported: Schema.Array(Schema.Literal("code")), grant_types_supported: Schema.Array(Schema.Literal("authorization_code")), code_challenge_methods_supported: Schema.Array(Schema.Literal("S256")), @@ -670,6 +672,13 @@ export const AuthMcpTokenRequest = Schema.Struct({ }).pipe(HttpApiSchema.asFormUrlEncoded()); export type AuthMcpTokenRequest = typeof AuthMcpTokenRequest.Type; +/** RFC 7009: the holder of an access token ends its session. */ +export const AuthMcpRevokeRequest = Schema.Struct({ + token: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)), + token_type_hint: Schema.optionalKey(Schema.String), +}).pipe(HttpApiSchema.asFormUrlEncoded()); +export type AuthMcpRevokeRequest = typeof AuthMcpRevokeRequest.Type; + export const AuthMcpTokenResult = Schema.Struct({ access_token: Schema.String, token_type: Schema.Literal("Bearer"), diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index 9b5cd9a0cb5c1..2a6c0dc43d50c 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -25,6 +25,7 @@ import { AuthMcpRegisteredClient, AuthMcpRegistrationError, AuthMcpTokenError, + AuthMcpRevokeRequest, AuthMcpTokenRequest, AuthMcpTokenResult, AuthPairingCredentialResult, @@ -725,6 +726,12 @@ class EnvironmentMcpOAuthHttpApi extends HttpApiGroup.make("mcpOAuth") success: AuthMcpTokenResult, error: AuthMcpTokenError, }), + ) + .add( + HttpApiEndpoint.post("revoke", "/oauth/mcp/revoke", { + payload: AuthMcpRevokeRequest, + success: HttpApiSchema.Empty(200), + }), ) {} const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({ diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index f84d003ed12e3..49595364ad786 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -965,6 +965,7 @@ export type OrchestratorMcpEnvironmentUnlinkInput = export const OrchestratorMcpEnvironmentUnlinkResult = Schema.Struct({ environmentId: EnvironmentId, removed: Schema.Boolean, + endedThere: Schema.Boolean, }); export type OrchestratorMcpEnvironmentUnlinkResult = typeof OrchestratorMcpEnvironmentUnlinkResult.Type; diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts index 6f33686b4b37b..3ff0fe93228d8 100644 --- a/packages/contracts/src/peerLink.ts +++ b/packages/contracts/src/peerLink.ts @@ -63,7 +63,11 @@ export type PeerLinkCreateInput = typeof PeerLinkCreateInput.Type; export const PeerLinkRemoveInput = Schema.Struct({ environmentId: EnvironmentId }); export type PeerLinkRemoveInput = typeof PeerLinkRemoveInput.Type; -export const PeerLinkRemoveResult = Schema.Struct({ removed: Schema.Boolean }); +export const PeerLinkRemoveResult = Schema.Struct({ + removed: Schema.Boolean, + // Whether the peer ended the link's session. Older servers never ask it to. + endedThere: Schema.optionalKey(Schema.Boolean), +}); export type PeerLinkRemoveResult = typeof PeerLinkRemoveResult.Type; /** Why linking or calling a peer failed, in words a user can act on. */ From 7ed41b7c238dc6e61c750d8fad806811e9fd1b6f Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:57:57 +0100 Subject: [PATCH 097/162] fix(mobile): scope Git result banners to their originating thread (#41015) Co-authored-by: Julius Marminge --- .../features/threads/ThreadRouteScreen.tsx | 9 +- .../use-selected-thread-git-actions.test.ts | 7 +- .../state/use-selected-thread-git-actions.ts | 20 ++- .../src/state/use-vcs-action-state.test.ts | 24 ---- .../src/state/use-vcs-action-state.test.tsx | 123 ++++++++++++++++++ apps/mobile/src/state/use-vcs-action-state.ts | 65 +++++---- apps/mobile/vite.config.ts | 1 + 7 files changed, 187 insertions(+), 62 deletions(-) delete mode 100644 apps/mobile/src/state/use-vcs-action-state.test.ts create mode 100644 apps/mobile/src/state/use-vcs-action-state.test.tsx diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index c4a6ae091a397..8f509de9e674a 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -589,12 +589,11 @@ function ThreadRouteContent( environmentId: selectedThread?.environmentId ?? null, cwd: selectedThreadCwd, }; - const gitActionProgress = useGitActionProgress( - gitActionProgressTarget, + const gitActionThreadRef = selectedThread === null ? null - : { environmentId: selectedThread.environmentId, threadId: selectedThread.id }, - ); + : { environmentId: selectedThread.environmentId, threadId: selectedThread.id }; + const gitActionProgress = useGitActionProgress(gitActionProgressTarget, gitActionThreadRef); const handleOpenGitInspector = () => { navigation.setParams({ inspector: undefined }); @@ -1033,7 +1032,7 @@ function ThreadRouteContent( <> dismissGitActionResult(gitActionThreadRef)} onOpenPullRequest={openPullRequest} /> diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.test.ts b/apps/mobile/src/state/use-selected-thread-git-actions.test.ts index e143c2d032eeb..42953ef7886fe 100644 --- a/apps/mobile/src/state/use-selected-thread-git-actions.test.ts +++ b/apps/mobile/src/state/use-selected-thread-git-actions.test.ts @@ -333,7 +333,12 @@ describe("automatic feature branch refs", () => { ); expect(await useSelectedThreadGitActions().refreshSelectedThreadBranches()).toBeNull(); expect(state.results).toEqual([ - { type: "error", title: "Git action failed", description: "Cannot list refs" }, + { + threadRef: { environmentId: "environment", threadId: "thread" }, + type: "error", + title: "Git action failed", + description: "Cannot list refs", + }, ]); }); }); diff --git a/apps/mobile/src/state/use-selected-thread-git-actions.ts b/apps/mobile/src/state/use-selected-thread-git-actions.ts index 1a40c455ac055..f42b64cf1b3a7 100644 --- a/apps/mobile/src/state/use-selected-thread-git-actions.ts +++ b/apps/mobile/src/state/use-selected-thread-git-actions.ts @@ -36,7 +36,11 @@ import { } from "./use-remote-environment-registry"; import { useAtomCommand } from "./use-atom-command"; import type { GitRepositoryTarget } from "./thread-git-target"; -import { noteRepositoryGitAction, showGitActionResult } from "./use-vcs-action-state"; +import { + noteRepositoryGitAction, + showGitActionResult, + type GitActionResultNotification, +} from "./use-vcs-action-state"; import { useThreadSelection } from "./use-thread-selection"; import { useSelectedThreadWorktree } from "./use-selected-thread-worktree"; @@ -71,6 +75,12 @@ export function useSelectedThreadGitActions(repository?: GitRepositoryTarget) { const createWorktree = useAtomCommand(vcsEnvironment.createWorktree, { reportFailure: false }); const pull = useAtomCommand(vcsEnvironment.pull, { reportFailure: false }); const { selectedThread, selectedThreadProject } = useThreadSelection(); + const threadRef = selectedThread + ? { environmentId: selectedThread.environmentId, threadId: selectedThread.id } + : null; + const reportGitActionResult = (result: GitActionResultNotification) => { + if (threadRef !== null) showGitActionResult({ ...result, threadRef }); + }; const canWriteSourceControl = useEnvironmentScope( selectedThread?.environmentId ?? null, AuthSourceControlWriteScope, @@ -223,7 +233,7 @@ export function useSelectedThreadGitActions(repository?: GitRepositoryTarget) { const error = Cause.squash(result.cause); const message = errorDisplayMessage(error, m) ?? m(msg("Git action failed.")); setPendingConnectionError(message); - showGitActionResult({ + reportGitActionResult({ type: "error", title: m(msg("Git action failed")), description: message, @@ -243,7 +253,7 @@ export function useSelectedThreadGitActions(repository?: GitRepositoryTarget) { const error = Cause.squash(result.cause); const message = errorDisplayMessage(error, m) ?? m(msg("Failed to refresh branches.")); setPendingConnectionError(message); - showGitActionResult({ + reportGitActionResult({ type: "error", title: m(msg("Git action failed")), description: message, @@ -377,7 +387,7 @@ export function useSelectedThreadGitActions(repository?: GitRepositoryTarget) { return result; } await refreshSelectedThreadGitStatus({ quiet: true, cwd }); - showGitActionResult({ + reportGitActionResult({ type: "success", title: result.value.status === "skipped_up_to_date" @@ -424,7 +434,7 @@ export function useSelectedThreadGitActions(repository?: GitRepositoryTarget) { } else { await refreshSelectedThreadGitStatus({ quiet: true, cwd }); } - showGitActionResult({ + reportGitActionResult({ type: "success", title: result.value.toast.title, description: result.value.toast.description, diff --git a/apps/mobile/src/state/use-vcs-action-state.test.ts b/apps/mobile/src/state/use-vcs-action-state.test.ts deleted file mode 100644 index 5d6409bdb1290..0000000000000 --- a/apps/mobile/src/state/use-vcs-action-state.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { describe, expect, it, vi } from "vite-plus/test"; - -const mocks = vi.hoisted(() => ({ - notificationAsync: vi.fn(() => Promise.resolve()), -})); - -vi.mock("expo-haptics", () => ({ - NotificationFeedbackType: { Success: "success", Error: "error" }, - notificationAsync: mocks.notificationAsync, -})); - -vi.mock("./vcs", () => ({ vcsActionManager: {} })); - -import { dismissGitActionResult, showGitActionResult } from "./use-vcs-action-state"; - -describe("showGitActionResult", () => { - it("buzzes once per reported result with the matching feedback type", () => { - showGitActionResult({ type: "success", title: "Pushed" }); - showGitActionResult({ type: "error", title: "Git action failed", description: "rejected" }); - dismissGitActionResult(); - - expect(mocks.notificationAsync.mock.calls).toEqual([["success"], ["error"]]); - }); -}); diff --git a/apps/mobile/src/state/use-vcs-action-state.test.tsx b/apps/mobile/src/state/use-vcs-action-state.test.tsx new file mode 100644 index 0000000000000..32bcb84d351fb --- /dev/null +++ b/apps/mobile/src/state/use-vcs-action-state.test.tsx @@ -0,0 +1,123 @@ +import { RegistryContext } from "@effect/atom-react"; +import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { describe, expect, it, vi } from "vite-plus/test"; + +const mocks = vi.hoisted(() => ({ + notificationAsync: vi.fn(() => Promise.resolve()), +})); + +vi.mock("expo-haptics", () => ({ + NotificationFeedbackType: { Success: "success", Error: "error" }, + notificationAsync: mocks.notificationAsync, +})); + +vi.mock("./vcs", async () => { + const { Atom } = await import("effect/reactivity"); + const idle = Atom.make({ isRunning: false }); + return { vcsActionManager: { stateAtom: () => idle } }; +}); + +import { appAtomRegistry } from "./atom-registry"; +import { + dismissGitActionResult, + showGitActionResult, + useGitActionProgress, +} from "./use-vcs-action-state"; + +const owner = { environmentId: EnvironmentId.make("first"), threadId: ThreadId.make("thread-a") }; +const otherThread = { ...owner, threadId: ThreadId.make("thread-b") }; + +function mountGitBanner() { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + const root = createRoot(container); + + function Banner({ threadRef }: { readonly threadRef: ScopedThreadRef | null }) { + const progress = useGitActionProgress( + { environmentId: threadRef?.environmentId ?? null, cwd: "/repo" }, + threadRef, + ); + return progress.label; + } + + return { + select(threadRef: ScopedThreadRef | null) { + act(() => { + root.render( + + + , + ); + }); + }, + get text() { + return container.textContent; + }, + [Symbol.dispose]() { + act(() => root.unmount()); + vi.unstubAllGlobals(); + }, + }; +} + +describe("showGitActionResult", () => { + it("buzzes once per reported result with the matching feedback type", () => { + showGitActionResult({ threadRef: owner, type: "success", title: "Pushed" }); + showGitActionResult({ + threadRef: owner, + type: "error", + title: "Git action failed", + description: "rejected", + }); + dismissGitActionResult(owner); + + expect(mocks.notificationAsync.mock.calls).toEqual([["success"], ["error"]]); + }); +}); + +describe("thread Git result banners", () => { + it.each([ + { name: "another thread", resultOwner: owner, viewer: otherThread }, + { + name: "the same thread ID in another environment", + resultOwner: owner, + viewer: { ...owner, environmentId: EnvironmentId.make("second") }, + }, + { + name: "a thread whose IDs join to the same string", + resultOwner: { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("a:b") }, + viewer: { environmentId: EnvironmentId.make("env:a"), threadId: ThreadId.make("b") }, + }, + { name: "no selected thread", resultOwner: owner, viewer: null }, + ])("hides a thread's result from $name", ({ resultOwner, viewer }) => { + try { + showGitActionResult({ threadRef: resultOwner, type: "success", title: "Pulled" }); + using banner = mountGitBanner(); + banner.select(resultOwner); + expect(banner.text).toBe("Pulled"); + banner.select(viewer); + expect(banner.text).toBe(""); + } finally { + dismissGitActionResult(resultOwner); + } + }); + + it("keeps each thread's result when another thread reports or dismisses", () => { + try { + using banner = mountGitBanner(); + showGitActionResult({ threadRef: otherThread, type: "error", title: "Rejected" }); + banner.select(otherThread); + act(() => showGitActionResult({ threadRef: owner, type: "success", title: "Pulled" })); + expect(banner.text).toBe("Rejected"); + act(() => dismissGitActionResult(otherThread)); + expect(banner.text).toBe(""); + banner.select(owner); + expect(banner.text).toBe("Pulled"); + } finally { + dismissGitActionResult(owner); + dismissGitActionResult(otherThread); + } + }); +}); diff --git a/apps/mobile/src/state/use-vcs-action-state.ts b/apps/mobile/src/state/use-vcs-action-state.ts index 04838ad200219..d09094df84da7 100644 --- a/apps/mobile/src/state/use-vcs-action-state.ts +++ b/apps/mobile/src/state/use-vcs-action-state.ts @@ -43,43 +43,51 @@ export interface GitActionResultNotification { const RESULT_DISMISS_MS = 5_000; -const gitActionResultAtom = Atom.make(null).pipe( +interface PendingGitActionResult { + readonly notification: GitActionResultNotification; + readonly timer: ReturnType; +} + +const gitActionResultsAtom = Atom.make>(new Map()).pipe( Atom.keepAlive, - Atom.withLabel("mobile:git-action-result"), + Atom.withLabel("mobile:git-action-results"), ); -let dismissTimer: ReturnType | null = null; -function broadcast(result: GitActionResultNotification | null): void { - appAtomRegistry.set(gitActionResultAtom, result); +function gitActionResultKey({ environmentId, threadId }: ScopedThreadRef): string { + return JSON.stringify([environmentId, threadId]); } -export function showGitActionResult(result: GitActionResultNotification): void { +export function showGitActionResult({ + threadRef, + ...notification +}: GitActionResultNotification & { readonly threadRef: ScopedThreadRef }): void { // Best effort: devices without a haptics engine reject. Haptics.notificationAsync( - result.type === "success" + notification.type === "success" ? Haptics.NotificationFeedbackType.Success : Haptics.NotificationFeedbackType.Error, ).catch(() => undefined); - if (dismissTimer) clearTimeout(dismissTimer); - broadcast(result); - dismissTimer = setTimeout(() => { - dismissTimer = null; - broadcast(null); - }, RESULT_DISMISS_MS); -} - -export function dismissGitActionResult(): void { - if (dismissTimer) clearTimeout(dismissTimer); - dismissTimer = null; - broadcast(null); + const key = gitActionResultKey(threadRef); + const results = new Map(appAtomRegistry.get(gitActionResultsAtom)); + const previous = results.get(key); + if (previous !== undefined) clearTimeout(previous.timer); + results.set(key, { + notification, + timer: setTimeout(() => dismissGitActionResult(threadRef), RESULT_DISMISS_MS), + }); + appAtomRegistry.set(gitActionResultsAtom, results); } -function useGitActionResultNotification(): { - readonly result: GitActionResultNotification | null; - readonly dismiss: () => void; -} { - const result = useAtomValue(gitActionResultAtom); - return { result, dismiss: dismissGitActionResult }; +export function dismissGitActionResult(threadRef: ScopedThreadRef | null): void { + if (threadRef === null) return; + const key = gitActionResultKey(threadRef); + const results = appAtomRegistry.get(gitActionResultsAtom); + const entry = results.get(key); + if (entry === undefined) return; + clearTimeout(entry.timer); + const next = new Map(results); + next.delete(key); + appAtomRegistry.set(gitActionResultsAtom, next); } export type GitActionProgressPhase = "idle" | "running" | "success" | "error"; @@ -110,7 +118,7 @@ function formatElapsedSeconds( return resolve(msg("Running for {elapsed}s", { elapsed: String(elapsed) })); } -/** Progress in the thread's own folder, or in the repository the thread last acted on. */ +/** Checkout progress and the selected thread's own Git result. */ export function useGitActionProgress( target: VcsActionTarget, threadRef: ScopedThreadRef | null, @@ -129,7 +137,10 @@ export function useGitActionProgress( cwd: repositoryCwd, }); const actionState = repositoryState.isRunning ? repositoryState : threadFolderState; - const { result } = useGitActionResultNotification(); + const resultKey = threadRef === null ? null : gitActionResultKey(threadRef); + const result = useAtomValue(gitActionResultsAtom, (results) => + resultKey === null ? undefined : results.get(resultKey)?.notification, + ); const resolve = useMessages(); // Only a running action shows elapsed time, so only it subscribes to the second tick. diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 054f219bfa171..ee001a3a5e3d4 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -47,6 +47,7 @@ const reactTests = [ "src/native/useRetryingImageSource.test.tsx", "src/state/queries.debounce.test.tsx", "src/state/use-selected-thread-git-state.test.tsx", + "src/state/use-vcs-action-state.test.tsx", "src/features/terminal/useTerminalExitNavigation.test.tsx", "src/features/threads/use-thread-list-now.test.tsx", "src/features/threads/use-composer-command-menu.select.test.tsx", From 000ba180beef5c9491970b66c2d640032658696e Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:00:16 +0100 Subject: [PATCH 098/162] fix(web): keep the conversation when a pairing tab closes (#41025) Co-authored-by: Julius Marminge --- apps/web/src/state/linkedThreadView.ts | 16 +- ...-thread-stays-closed-during-pairing.e2e.ts | 139 ++++++++++++++++++ 2 files changed, 152 insertions(+), 3 deletions(-) create mode 100644 scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index adeb858c23cab..6f3ec45889a1f 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -11,7 +11,7 @@ import { useNavigate, useRouter } from "@tanstack/react-router"; import { AsyncResult, Atom } from "effect/reactivity"; import type { TurnItemSource } from "../components/chat/timelineRowContext"; -import { useRightPanelStore } from "../rightPanelStore"; +import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore"; import { connectPairing, reachesEnvironment } from "../connection/onboarding"; import { openLinkedThreadRead } from "../lib/sideChatPane"; import type { LinkedThreadSurface } from "../linkedThreadSurface"; @@ -203,8 +203,17 @@ export function useConnectLinkedEnvironment( const connect = async () => { setState({ phase: "connecting" }); const startedOn = router.state.location.href; + let tabClosed = false; + // A tab can close and reopen with the same ID while pairing is in flight. + const stopWatchingTab = + panelRef === null + ? undefined + : useRightPanelStore.subscribe((state) => { + const { surfaces } = selectThreadRightPanelState(state.byThreadKey, panelRef); + if (!surfaces.some((tab) => tab.id === surface.id)) tabClosed = true; + }); // Pairing takes a moment; a user who has gone elsewhere since is not moved again. - const stayed = () => router.state.location.href === startedOn; + const stayed = () => !tabClosed && router.state.location.href === startedOn; const outcome = await connectLinkedEnvironment({ label: surface.label, requestPairing: async () => { @@ -228,13 +237,14 @@ export function useConnectLinkedEnvironment( }); return result._tag === "Success"; }, - }); + }).finally(stopWatchingTab); if (outcome.type === "unreachable") { setState({ phase: "unreachable", label: outcome.label }); return outcome; } if (outcome.type === "connected") { setState({ phase: "idle" }); + if (tabClosed) return outcome; // The thread opens where every thread on a connected environment does, so its tab is done. if (panelRef !== null) useRightPanelStore.getState().closeSurface(panelRef, surface.id); if (!stayed()) return outcome; diff --git a/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts new file mode 100644 index 0000000000000..dbd90361cfe45 --- /dev/null +++ b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts @@ -0,0 +1,139 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodeCredential = Schema.decodeUnknownSync(Schema.Struct({ credential: Schema.String })); + +test( + "A closed linked-thread tab does not take over the conversation when pairing finishes", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("primary"); + const parent = await t3.thread({ + project, + title: "Current work", + messages: ["Keep this conversation open"], + }); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + const second = makeState(SECOND_HOME); + const issued = await runPromise(second.cli(["auth", "session", "issue", "--token-only"])); + // @effect-diagnostics-next-line globalFetch:off -- Seeds the real peer link from the scenario's Node fixture. + const pairing = await fetch(`${host}/api/auth/pairing-token`, { + method: "POST", + headers: { + authorization: `Bearer ${issued.stdout.trim()}`, + "content-type": "application/json", + }, + body: JSON.stringify({ purpose: "peer-link", access: "full-access" }), + }); + if (!pairing.ok) throw new Error(`Could not mint a peer-link code: ${pairing.status}`); + const { credential } = decodeCredential(await pairing.json()); + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "full-access", + }); + }).pipe(Effect.scoped), + ); + + const linkedProject = await second.state.project("linked"); + const linkedTitle = "Remote design notes"; + const linkedPrompt = "Read the remote design notes"; + const remoteThread = await second.state.thread({ + project: linkedProject, + title: linkedTitle, + messages: [linkedPrompt], + }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + await browser.setViewport({ width: 1440, height: 900 }); + + // Restore the same saved tab that opening the delegated thread in the panel would leave. + await browser.addInitScript( + ({ via, linked, parentId, childId, title }) => { + if (location.pathname !== `/${via}/${parentId}`) return; + const id = `linked-thread:${encodeURIComponent(via)}:${encodeURIComponent(linked)}:${encodeURIComponent(childId)}`; + localStorage.setItem( + "t3code:right-panel-state:v2", + JSON.stringify({ + version: 16, + state: { + byThreadKey: { + [`${via}:${parentId}`]: { + isOpen: true, + activeSurfaceId: id, + surfaces: [ + { + kind: "linked-thread", + id, + viaEnvironmentId: via, + environmentId: linked, + threadId: childId, + label: "Scenario", + title, + }, + ], + }, + }, + threadPanelVisibilityByThreadKey: {}, + }, + }), + ); + }, + { + via, + linked, + parentId: parent.threadId, + childId: remoteThread.threadId, + title: linkedTitle, + }, + ); + + const tokenUrl = `${host}/oauth/token`; + const requested = Promise.withResolvers(); + const release = Promise.withResolvers(); + await browser.route(tokenUrl, async (route) => { + if (route.request.method !== "POST") return route.fallback(); + requested.resolve(); + await release.promise; + await route.continue(); + }); + try { + await t3.open(parent); + await screen.getByText(linkedPrompt, { exact: true }).waitFor(); + const originalUrl = await browser.url(); + await screen.getByRole("button", "Connect to interact", { exact: true }).tap(); + await requested.promise; + await screen.getByRole("button", `Close ${linkedTitle}`, { exact: true }).tap(); + + release.resolve(); + await screen + .getByText("This device is paired with it and can use its threads.", { exact: true }) + .waitFor(); + + await app.screenshot("after-pairing-finishes"); + await expect(browser).toHaveURL(originalUrl); + } finally { + release.resolve(); + await browser.unroute(tokenUrl); + } + } finally { + await server.stop(); + } + }, +); From 5bd0616f0524d312e0ee4471ca96f11bbdcb261c Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:02:35 +0100 Subject: [PATCH 099/162] fix: restart linked thread reads when trying again (#41020) Co-authored-by: Julius Marminge --- apps/web/src/state/linkedThreadView.ts | 19 ++-- .../src/state/peerLinks.test.ts | 31 +++++- .../client-runtime/src/state/peerLinks.ts | 17 +-- .../linked-thread-retry-reads-again.e2e.ts | 105 ++++++++++++++++++ 4 files changed, 153 insertions(+), 19 deletions(-) create mode 100644 scripts/scenarios/linked-thread-retry-reads-again.e2e.ts diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index 6f3ec45889a1f..4194e07834811 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -107,14 +107,17 @@ const tabViewAtom = Atom.family((key: string) => { const view = peerLinkEnvironment.threadView( targetOf({ viaEnvironmentId, environmentId, threadId }), ); - return Atom.make((get) => { - const live = get(view); - const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; - if (title && panelRef !== null) { - useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); - } - return live; - }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); + return Atom.readable( + (get) => { + const live = get(view); + const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; + if (title && panelRef !== null) { + useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); + } + return live; + }, + (refresh) => refresh(view), + ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); }); /** diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index 75430e340fbff..dd39162df8a4c 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + PeerLinkThreadReadError, WS_METHODS, type OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadStreamItem, @@ -15,6 +16,7 @@ import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; +import { TestClock } from "effect/testing"; import { EnvironmentRegistry } from "../connection/registry.ts"; import { EnvironmentSupervisor } from "../connection/supervisor.ts"; @@ -25,7 +27,7 @@ import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.t // regression: #40544 earlier messages vanished when a linked thread's view opened again it.effect( - "keeps loaded messages when a linked thread's view opens again on the same snapshot", + "keeps loaded messages when a linked thread retries and reopens on the same snapshot", () => Effect.gen(function* () { const recent = v2MessageRow("Recent message", 2); @@ -38,7 +40,7 @@ it.effect( hasMoreHistory: true, }); const subscriptions = yield* Queue.unbounded<{ - items: Queue.Queue; + items: Queue.Queue; stopped: Deferred.Deferred; }>(); const requested: string[] = []; @@ -46,7 +48,10 @@ it.effect( [WS_METHODS.peerLinksSubscribeThread]: () => Stream.unwrap( Effect.gen(function* () { - const items = yield* Queue.unbounded(); + const items = yield* Queue.unbounded< + OrchestrationV2ThreadStreamItem, + PeerLinkThreadReadError + >(); const stopped = yield* Deferred.make(); yield* Effect.addFinalizer(() => Deferred.succeed(stopped, undefined)); yield* Queue.offer(subscriptions, { items, stopped }); @@ -102,8 +107,26 @@ it.effect( older.sourceItemId, recent.sourceItemId, ]); + const unreachable = new PeerLinkThreadReadError({ + reason: "unreachable", + label: "Linked", + message: "The linked machine is temporarily unreachable.", + }); + yield* Queue.fail(first.items, unreachable); + expect((yield* Queue.take(views)).error).toBe(unreachable); + + registry.refresh(links.threadView(target)); + yield* TestClock.adjust(0); + const retry = yield* Queue.poll(subscriptions); + if (Option.isNone(retry)) throw new Error("Refresh did not start a new linked thread read"); + yield* Queue.offer(retry.value.items, snapshot("before-recent")); + const recovered = yield* Queue.take(views).pipe( + Effect.repeat({ until: (view) => view.error === null }), + ); + expect(visibleMessages(recovered)).toEqual([older.sourceItemId, recent.sourceItemId]); + unmount(); - yield* Deferred.await(first.stopped); + yield* Deferred.await(retry.value.stopped); open(); const reopened = yield* Queue.take(subscriptions); diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index fd9d269bfd726..a7af1ac15b4c9 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -87,13 +87,16 @@ export function createPeerLinkEnvironmentAtoms( ), ) .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-stream:${key}`)); - return Atom.make((get) => { - const live = get(stream); - if (AsyncResult.isSuccess(live)) { - get.set(kept, keepLinkedThreadView(get.once(kept), live.value)); - } - return live; - }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`)); + return Atom.readable( + (get) => { + const live = get(stream); + if (AsyncResult.isSuccess(live)) { + get.set(kept, keepLinkedThreadView(get.once(kept), live.value)); + } + return live; + }, + (refresh) => refresh(stream), + ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`)); }); return { list, diff --git a/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts new file mode 100644 index 0000000000000..fd24c39b74dea --- /dev/null +++ b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts @@ -0,0 +1,105 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodePairing = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), +); + +test( + "Try again immediately reads a linked thread once it is reachable", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("primary"); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + const pairing = yield* makeState(SECOND_HOME).cli([ + "auth", + "pairing", + "create", + "--json", + ]); + const { credential } = yield* decodePairing(pairing.stdout); + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "approval-required", + }); + }).pipe(Effect.scoped), + ); + + const remote = makeState(SECOND_HOME).state; + const project = await remote.project("linked"); + const prompt = "Read the linked design notes"; + const thread = await remote.thread({ project, title: "Design notes", messages: [prompt] }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + + // Drop only the first subscription, as if the linked machine were briefly unreachable. + // Every later request goes to the real server and reads the seeded thread. + await browser.addInitScript(() => { + let failed = false; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (failed || typeof data !== "string") return send.call(this, data); + const parsed = JSON.parse(data); + const messages = Array.isArray(parsed) ? parsed : [parsed]; + const request = messages.find( + (message) => message?._tag === "Request" && message.tag === "peerLinks.subscribeThread", + ); + if (!request) return send.call(this, data); + failed = true; + const others = messages.filter((message) => message !== request); + if (others.length > 0) send.call(this, JSON.stringify(others)); + // @effect-diagnostics-next-line globalTimers:off - This callback is injected into the browser. + setTimeout(() => { + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + _tag: "Exit", + requestId: request.id, + exit: { + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "PeerLinkThreadReadError", + reason: "unreachable", + label: "Scenario", + message: "The linked machine is temporarily unreachable.", + }, + }, + ], + }, + }), + }), + ); + }, 0); + }; + }); + + await t3.open(`/linked/${via}/${linked}/${thread.threadId}`); + await screen.getByRole("button", "Try again", { exact: true }).tap(); + await app.screenshot("after-trying-again"); + // The automatic retry waits 15 seconds. This checks the user's explicit retry. + await expect(screen.getByText(prompt, { exact: true })).toBeVisible({ timeout: 4_000 }); + } finally { + await server.stop(); + } + }, +); From 55880c41b401469225a63e8128f2119290a7ad32 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:02:47 +0100 Subject: [PATCH 100/162] fix(client-runtime): count ambiguous projects in chat file links (#40986) Co-authored-by: Julius Marminge --- .../src/features/threads/ThreadFeed.tsx | 17 +++++---- apps/web/src/components/ChatMarkdown.tsx | 15 ++++---- apps/web/src/workspaceBasenameLookup.test.ts | 15 ++++++++ .../src/workspaceBasenameLookup.ts | 16 ++++---- ...ation-skips-ambiguous-project-files.e2e.ts | 37 +++++++++++++++++++ ...roject-after-ambiguous-local-search.e2e.ts | 34 +++++++++++++++++ 6 files changed, 110 insertions(+), 24 deletions(-) create mode 100644 scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts create mode 100644 scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 1a6d668d9ce50..106e72c2e1203 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -3330,7 +3330,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // A v1 link names no environment, so it falls back to this message's. return scopeThreadRef(props.environmentId, link.threadId); }; - // The file a chat link names: in this workspace, else in the one other project that has it. + // Prefer the thread workspace before looking across projects or in agent directories. const findFileLinkTarget = async ( linkPath: string, path: string, @@ -3348,6 +3348,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { return relativePath ?? path; } const workspaceRoot = props.workspaceRoot; + const basenameLookup = needsWorkspaceBasenameLookup(relativePath); const originalPath = resolveWorkspaceFilePath(workspaceRoot, relativePath); const queryOptions = { signal, reportFailure: false, reportDefect: false }; const searchRoot = (root: string) => @@ -3395,13 +3396,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ? [project.workspaceRoot] : [], ); - match = - otherRoots.length === 0 - ? null - : pickProjectLinkMatch(relativePath, await Promise.all(otherRoots.map(searchRoot))); + if (otherRoots.length > 0) { + const projectSearches = await Promise.all(otherRoots.map(searchRoot)); + match = pickProjectLinkMatch(relativePath, [own, ...projectSearches]); + } } if (match === null && reply !== undefined && !signal.aborted) { - // No project has the file, so it opens where the agent last worked, as written. + // An unresolved project lookup falls back to the agent's working directories. const agentRoots = agentWorkingDirectories( appAtomRegistry.get( environmentThreadDetails.quietThreadAtom( @@ -3420,7 +3421,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { (result) => result._tag === "Success" && result.value?.kind === "file", ); const literal = agentPaths[index]; - if (literal !== undefined || !needsWorkspaceBasenameLookup(relativePath)) { + if (literal !== undefined || !basenameLookup) { return literal ?? relativePath; } return ( @@ -3431,7 +3432,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const metadata = await metadataOf(originalPath); // Another project's file never replaces a thread-local file the search missed. return metadata._tag === "Success" && - (needsWorkspaceBasenameLookup(relativePath) && !otherProject + (basenameLookup && !otherProject ? metadata.value?.kind !== "directory" : metadata.value === null) ? match diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 979d1858cafc1..2edc4be1febcd 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -880,9 +880,10 @@ function useChatMarkdownState( } const query = workspaceLinkLookupQuery(workspaceRelativePath, cwd); if (query === null) return null; + const basenameLookup = needsWorkspaceBasenameLookup(workspaceRelativePath); // Search can be truncated or still scanning, so it cannot rule out the literal // path. A path with a folder opens as written whenever it exists. - if (!needsWorkspaceBasenameLookup(workspaceRelativePath)) { + if (!basenameLookup) { const metadata = await getFilesystemMetadata({ environmentId, input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] }, @@ -917,26 +918,24 @@ function useChatMarkdownState( const agentRoots = (agentDirectories?.() ?? []).filter((root) => root !== cwd); if (otherRoots.length === 0 && agentRoots.length === 0) return null; // Another project's file never replaces a thread-local file the search missed. - if (needsWorkspaceBasenameLookup(workspaceRelativePath)) { + if (basenameLookup) { const metadata = await getFilesystemMetadata({ environmentId, input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] }, }); if (metadata._tag !== "Success" || metadata.value.entries[0] !== null) return null; } - const projectMatch = pickProjectLinkMatch( - workspaceRelativePath, - await Promise.all(otherRoots.map(searchRoot)), - ); + const projectSearches = await Promise.all(otherRoots.map(searchRoot)); + const projectMatch = pickProjectLinkMatch(workspaceRelativePath, [own, ...projectSearches]); if (projectMatch !== null || agentRoots.length === 0) return projectMatch; - // No project has the file, so it opens where the agent last worked, as written. + // An unresolved project lookup falls back to the agent's working directories. const agentPaths = agentRoots.map((root) => resolveWorkspaceFilePath(workspaceRelativePath, root), ); const metadata = await getFilesystemMetadata({ environmentId, input: { paths: agentPaths } }); if (metadata._tag !== "Success") return null; const literal = agentPaths.find((_, index) => metadata.value.entries[index]?.kind === "file"); - if (literal !== undefined || !needsWorkspaceBasenameLookup(workspaceRelativePath)) { + if (literal !== undefined || !basenameLookup) { return literal ?? null; } return findAgentDirectoryMatch(workspaceRelativePath, agentRoots, searchRoot); diff --git a/apps/web/src/workspaceBasenameLookup.test.ts b/apps/web/src/workspaceBasenameLookup.test.ts index 4e11917a0aeff..7c1d17587813e 100644 --- a/apps/web/src/workspaceBasenameLookup.test.ts +++ b/apps/web/src/workspaceBasenameLookup.test.ts @@ -129,6 +129,21 @@ describe("chat file links into another project", () => { ).toBeNull(); }); + it("opens nothing when a project left ambiguous by case also has the name", () => { + expect( + pickProjectLinkMatch("handoff.txt", [ + { root: "/reports", entries: [{ path: "notes/HANDOFF.txt", kind: "file" }] }, + { + root: "/support", + entries: [ + { path: "current/Handoff.txt", kind: "file" }, + { path: "archive/HANDOFF.txt", kind: "file" }, + ], + }, + ]), + ).toBeNull(); + }); + it("opens nothing when overlapping projects also list a second suffix match", () => { expect( pickProjectLinkMatch("docs/handoff.txt", [ diff --git a/packages/client-runtime/src/workspaceBasenameLookup.ts b/packages/client-runtime/src/workspaceBasenameLookup.ts index 6698aed52fb38..ae55263fb2bd4 100644 --- a/packages/client-runtime/src/workspaceBasenameLookup.ts +++ b/packages/client-runtime/src/workspaceBasenameLookup.ts @@ -118,7 +118,7 @@ function pickStrippedWorkspaceMatch( } /** - * The absolute path of the one file a chat link names across other project roots, or null when + * The absolute path of the one file a chat link names across project roots, or null when * no root has it or roots name different files. Agents cite paths relative to their repo. * Nested project roots list the same file more than once, which still names one file. */ @@ -131,6 +131,9 @@ export function pickProjectLinkMatch( ): string | null { const target = relativePath.trim(); const isBasename = needsWorkspaceBasenameLookup(target); + const folded = target.toLowerCase(); + const isFoldedMatch = (entry: WorkspaceEntryCandidate) => + entry.kind === "file" && basenameOfPath(entry.path).toLowerCase() === folded; const matches = new Map(); let rootHits = 0; const addMatch = (path: string) => { @@ -140,10 +143,10 @@ export function pickProjectLinkMatch( }; for (const { root, entries } of searches) { if (isBasename) { - const match = pickWorkspaceBasenameMatch(target, entries); - if (match === null) continue; + if (!entries.some(isFoldedMatch)) continue; rootHits += 1; - addMatch(resolveWorkspaceFilePath(match, root)); + const match = pickWorkspaceBasenameMatch(target, entries); + if (match !== null) addMatch(resolveWorkspaceFilePath(match, root)); } else { for (const match of workspaceQualifiedPathMatches(target, root, entries)) { addMatch(resolveWorkspaceFilePath(match, root)); @@ -152,12 +155,9 @@ export function pickProjectLinkMatch( } if (isBasename && rootHits > 1) { // A root's pick, or a root left ambiguous by case, can hide another file elsewhere. - const folded = target.toLowerCase(); for (const { root, entries } of searches) { for (const entry of entries) { - if (entry.kind === "file" && basenameOfPath(entry.path).toLowerCase() === folded) { - addMatch(resolveWorkspaceFilePath(entry.path, root)); - } + if (isFoldedMatch(entry)) addMatch(resolveWorkspaceFilePath(entry.path, root)); } } } diff --git a/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts new file mode 100644 index 0000000000000..6cfbafc6c49b2 --- /dev/null +++ b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const FILE = "handoff.txt"; + +test( + "A bare citation leaves the file unresolved when other projects contain several matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("planning"); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: [`See :codex-file-citation{path="${FILE}" line_range_start="1"}`], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-handoff-citation"); + } + }, +); diff --git a/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts new file mode 100644 index 0000000000000..22458e6223fbb --- /dev/null +++ b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts @@ -0,0 +1,34 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A bare citation leaves the file unresolved when the thread project has ambiguous matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: ['See :codex-file-citation{path="handoff.txt" line_range_start="1"}'], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-local-handoff-citation"); + } + }, +); From 2e62a7189366a3541329479c7b6b4d40cab2916a Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:03:48 +0100 Subject: [PATCH 101/162] fix(mobile): keep media actions on each sent image page (#41018) Co-authored-by: Julius Marminge --- .../src/features/threads/ThreadFeed.tsx | 37 +++-------- .../features/threads/messageImageGallery.ts | 13 +--- apps/mobile/src/lib/composerImageGallery.ts | 13 +--- apps/mobile/src/lib/contextImageGallery.ts | 15 +---- .../mobile/src/lib/filePreviewGallery.test.ts | 63 ++++++++++++++++++- apps/mobile/src/lib/filePreviewGallery.ts | 21 +++++++ 6 files changed, 97 insertions(+), 65 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 106e72c2e1203..4337d9619ae2f 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -159,7 +159,10 @@ import { useResolveClassNames } from "uniwind"; import { useReduceMotionEnabled } from "../../lib/appState"; import { useFilePreviewGallery, FilePreviewGallery } from "../../components/ui/FilePreviewGallery"; import { assetImageSource } from "../../lib/assetImageSource"; -import { filePreviewSourceIdentifier } from "../../lib/filePreviewGallery"; +import { + filePreviewSourceIdentifier, + remoteAttachmentImageSource, +} from "../../lib/filePreviewGallery"; import { composerImageGallery } from "../../lib/composerImageGallery"; import { isFileBackedComposerAttachment, @@ -617,17 +620,9 @@ function MessageAttachmentImage(props: { }) { const gt = useGT(); const withGallery = useFilePreviewGallery(); - const resource = { - _tag: "attachment" as const, - attachmentId: props.attachmentId, - fileName: props.name, - mimeType: props.mimeType, - }; - const sourceIdentifier = filePreviewSourceIdentifier({ - kind: "image", - environmentId: props.environmentId, - resource, - }); + const previewSource = remoteAttachmentImageSource(props.environmentId, props.attachmentId, props); + const { resource } = previewSource; + const sourceIdentifier = filePreviewSourceIdentifier(previewSource); const uri = useAssetUrl(props.environmentId, resource); const refreshAssetUrl = useRefreshAssetUrl(props.environmentId, resource); const retriedImage = useRef(false); @@ -666,23 +661,7 @@ function MessageAttachmentImage(props: { height={props.height} accessibilityLabel={gt("Open {name}", { name: props.name })} {...handoffProps(handoff)} - onPress={() => - props.onPressPreview( - withGallery({ - kind: "image", - environmentId: props.environmentId, - resource, - name: props.name, - sourceIdentifier, - actionsSource: { - name: props.name, - mimeType: props.mimeType, - environmentId: props.environmentId, - resource, - }, - }), - ) - } + onPress={() => props.onPressPreview(withGallery({ ...previewSource, sourceIdentifier }))} onLoad={(size) => { retriedImage.current = false; if (handoff) diff --git a/apps/mobile/src/features/threads/messageImageGallery.ts b/apps/mobile/src/features/threads/messageImageGallery.ts index fb8fc3de67b78..c18592c67f43a 100644 --- a/apps/mobile/src/features/threads/messageImageGallery.ts +++ b/apps/mobile/src/features/threads/messageImageGallery.ts @@ -1,6 +1,7 @@ import type { ChatAttachment, EnvironmentId, ThreadId } from "@t3tools/contracts"; import { imageMimeType } from "@t3tools/shared/image"; import type { FilePreviewItem } from "../../components/ui/FilePreviewModal.types"; +import { remoteAttachmentImageSource } from "../../lib/filePreviewGallery"; import { markdownImageSources } from "../../lib/markdownImageSources"; import { resolveMarkdownMediaPreview } from "../../lib/markdownMedia"; @@ -15,17 +16,7 @@ export function messageImageGallery( const images: FilePreviewItem[] = []; for (const attachment of message.attachments ?? []) { if (attachment.type !== "image" && imageMimeType(attachment) === null) continue; - images.push({ - kind: "image", - name: attachment.name, - environmentId: context.environmentId, - resource: { - _tag: "attachment", - attachmentId: attachment.id, - fileName: attachment.name, - mimeType: attachment.mimeType, - }, - }); + images.push(remoteAttachmentImageSource(context.environmentId, attachment.id, attachment)); } for (const href of markdownImageSources(message.text)) { const preview = resolveMarkdownMediaPreview(href, { ...context, imageEmbed: true }); diff --git a/apps/mobile/src/lib/composerImageGallery.ts b/apps/mobile/src/lib/composerImageGallery.ts index ffc6167e8b50d..080ef20f2866c 100644 --- a/apps/mobile/src/lib/composerImageGallery.ts +++ b/apps/mobile/src/lib/composerImageGallery.ts @@ -2,6 +2,7 @@ import { imageMimeType } from "@t3tools/shared/image"; import type { EnvironmentId } from "@t3tools/contracts"; import type { FilePreviewItem } from "../components/ui/FilePreviewModal.types"; import { isFileBackedComposerAttachment, type DraftComposerAttachment } from "./composerImages"; +import { remoteAttachmentImageSource } from "./filePreviewGallery"; export function composerImageGallery( attachments: readonly DraftComposerAttachment[], @@ -11,17 +12,7 @@ export function composerImageGallery( if (attachment.type !== "image" && imageMimeType(attachment) === null) return []; if (environmentId !== undefined && attachment.uploadedAttachmentId) { return [ - { - kind: "image", - name: attachment.name, - environmentId, - resource: { - _tag: "attachment", - attachmentId: attachment.uploadedAttachmentId, - fileName: attachment.name, - mimeType: attachment.mimeType, - }, - }, + remoteAttachmentImageSource(environmentId, attachment.uploadedAttachmentId, attachment), ]; } if (isFileBackedComposerAttachment(attachment)) { diff --git a/apps/mobile/src/lib/contextImageGallery.ts b/apps/mobile/src/lib/contextImageGallery.ts index 335554b0565c5..c119ad856fd91 100644 --- a/apps/mobile/src/lib/contextImageGallery.ts +++ b/apps/mobile/src/lib/contextImageGallery.ts @@ -3,6 +3,7 @@ import { imageMimeType } from "@t3tools/shared/image"; import type { FilePreviewItem } from "../components/ui/FilePreviewModal.types"; import { composerImageGallery } from "./composerImageGallery"; import type { DraftComposerAttachment } from "./composerImages"; +import { remoteAttachmentImageSource } from "./filePreviewGallery"; export function contextImageGallery( records: readonly ComposerContextRecord[], @@ -15,19 +16,7 @@ export function contextImageGallery( const local = attachments.find((item) => item.id === record.attachmentId); if (local) return composerImageGallery([local]); return environmentId - ? [ - { - kind: "image", - name: record.name, - environmentId, - resource: { - _tag: "attachment", - attachmentId: record.attachmentId, - fileName: record.name, - mimeType: record.mimeType, - }, - }, - ] + ? [remoteAttachmentImageSource(environmentId, record.attachmentId, record)] : []; }); } diff --git a/apps/mobile/src/lib/filePreviewGallery.test.ts b/apps/mobile/src/lib/filePreviewGallery.test.ts index f85e33c851f07..d8def9cc125d8 100644 --- a/apps/mobile/src/lib/filePreviewGallery.test.ts +++ b/apps/mobile/src/lib/filePreviewGallery.test.ts @@ -1,8 +1,9 @@ import { describe, expect, it, vi } from "vite-plus/test"; -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { ComposerContextId, EnvironmentId, ThreadId } from "@t3tools/contracts"; import type { FilePreviewItem } from "../components/ui/FilePreviewModal.types"; import type { DraftComposerAttachment } from "./composerImages"; import { composerImageGallery } from "./composerImageGallery"; +import { contextImageGallery } from "./contextImageGallery"; import { messageImageGallery } from "../features/threads/messageImageGallery"; import { filePreviewGallery, filePreviewKey } from "./filePreviewGallery"; @@ -67,6 +68,66 @@ describe("image preview groups", () => { }, ); + it("gives every remote image page its own media actions", () => { + const environmentId = EnvironmentId.make("test"); + const ids = ["a", "b"]; + const galleries = [ + messageImageGallery( + { + text: "", + attachments: ids.map((id) => ({ + type: "image" as const, + id: `uploaded-${id}`, + name: `${id}.png`, + mimeType: "image/png", + sizeBytes: 3, + })), + }, + { environmentId, threadId: ThreadId.make("thread"), workspaceRoot: null }, + ), + composerImageGallery( + ids.map((id) => ({ + id, + type: "image", + name: `${id}.png`, + mimeType: "image/png", + sizeBytes: 3, + previewUri: `data:image/png;base64,${id}`, + uploadedAttachmentId: `uploaded-${id}`, + })), + environmentId, + ), + contextImageGallery( + ids.map((id) => ({ + version: 1, + kind: "image", + contextId: ComposerContextId.make(`context-${id}`), + label: `Screenshot ${id}`, + attachmentId: `uploaded-${id}`, + name: `${id}.png`, + mimeType: "image/png", + sizeBytes: 3, + })), + [], + environmentId, + ), + ]; + + for (const gallery of galleries) { + expect(filePreviewGallery(gallery[0]!, gallery)[1]?.actionsSource).toEqual({ + name: "b.png", + mimeType: "image/png", + environmentId, + resource: { + _tag: "attachment", + attachmentId: "uploaded-b", + fileName: "b.png", + mimeType: "image/png", + }, + }); + } + }); + it("matches remote originals despite metadata and property order differences", () => { const environmentId = EnvironmentId.make("test"); const a: FilePreviewItem = { diff --git a/apps/mobile/src/lib/filePreviewGallery.ts b/apps/mobile/src/lib/filePreviewGallery.ts index e8b2f4e19f838..26f16ec03cdc0 100644 --- a/apps/mobile/src/lib/filePreviewGallery.ts +++ b/apps/mobile/src/lib/filePreviewGallery.ts @@ -1,5 +1,26 @@ +import type { EnvironmentId } from "@t3tools/contracts"; import type { FilePreviewItem, FilePreviewSource } from "../components/ui/FilePreviewModal.types"; +export function remoteAttachmentImageSource( + environmentId: EnvironmentId, + attachmentId: string, + { name, mimeType }: { readonly name: string; readonly mimeType: string }, +) { + const resource = { + _tag: "attachment" as const, + attachmentId, + fileName: name, + mimeType, + }; + return { + kind: "image", + name, + environmentId, + resource, + actionsSource: { name, mimeType, environmentId, resource }, + } satisfies FilePreviewItem; +} + export function filePreviewKey(source: FilePreviewItem): string { if ("resource" in source) return JSON.stringify([ From 024dba275d9e5ade1b29a0a240c5f8661cdbdb51 Mon Sep 17 00:00:00 2001 From: Navid Nadali Date: Sun, 22 Nov 2026 20:11:54 +0000 Subject: [PATCH 102/162] perf(server): a run's provider turn lookup is linear, not quadratic (#38791) Co-authored-by: Claude Opus 5.5 Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- .../Orchestrator.control-reads.test.ts | 100 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 20 ++-- 2 files changed, 111 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 027c65011dc94..ac7cb9c714d88 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -7,6 +7,9 @@ import { EventId, NodeId, type OrchestrationV2DomainEvent, + type OrchestrationV2ProviderTurn, + type OrchestrationV2Run, + type OrchestrationV2RunAttempt, PlanId, ProjectId, ProviderDriverKind, @@ -3184,3 +3187,100 @@ it.effect( assert.equal(yield* captureReads, quietParent); }).pipe(Effect.provide(layerTest)), ); + +/** A copy of `value` whose `id` getter counts its reads. */ +const countingIdReads = ( + value: T, + reads: { count: number }, +): T => + Object.defineProperty({ ...value }, "id", { + enumerable: true, + get: () => { + reads.count += 1; + return value.id; + }, + }); + +// The owner's active attempt is the newest and no provider turn is tagged with it, so the lookup +// falls back to the turn the attempt names. The last two turns are untagged and share one id. +it.each([ + { ownerAttempt: "names no provider turn", providerTurnId: null, findsFirstLegacy: false }, + { + ownerAttempt: "names a provider turn listed twice", + providerTurnId: "legacy", + findsFirstLegacy: true, + }, + { ownerAttempt: "is missing", providerTurnId: null, findsFirstLegacy: false }, +] as const)( + "finds a run's provider turn in at most 2·(T + A) id reads when its attempt $ownerAttempt", + ({ ownerAttempt, providerTurnId, findsFirstLegacy }) => { + const size = 2_000; + const reads = { count: 0 }; + const providerThreadId = ProviderThreadId.make("provider-thread:lookup"); + const attempts = Array.from({ length: size }, (_, index) => + countingIdReads( + { + id: RunAttemptId.make(`attempt:lookup:${index}`), + runId: RunId.make(`run:lookup:${index}`), + attemptOrdinal: 1, + rootNodeId: NodeId.make(`node:lookup:${index}`), + providerInstanceId: instanceId, + providerThreadId, + providerTurnId: + index < size - 1 + ? ProviderTurnId.make(`provider-turn:lookup:${index}`) + : providerTurnId === null + ? null + : ProviderTurnId.make(`provider-turn:lookup:${providerTurnId}`), + reason: "initial", + status: index < size - 1 ? "completed" : "pending", + startedAt: null, + completedAt: null, + }, + reads, + ), + ); + const providerTurns = Array.from({ length: size }, (_, index) => { + const untagged = index >= size - 2; + return countingIdReads( + { + id: ProviderTurnId.make(`provider-turn:lookup:${untagged ? "legacy" : index}`), + providerThreadId, + nodeId: NodeId.make(`node:lookup:${index}`), + runAttemptId: untagged ? null : RunAttemptId.make(`attempt:lookup:${index}`), + nativeTurnRef: null, + ordinal: index + 1, + status: "completed", + startedAt: null, + completedAt: null, + }, + reads, + ); + }); + const owner: OrchestrationV2Run = { + id: RunId.make(`run:lookup:${size - 1}`), + threadId: ThreadId.make("thread:lookup"), + ordinal: size, + providerInstanceId: instanceId, + modelSelection, + providerThreadId, + userMessageId: MessageId.make("message:lookup"), + rootNodeId: NodeId.make(`node:lookup:${size - 1}`), + activeAttemptId: + ownerAttempt === "is missing" + ? RunAttemptId.make("attempt:lookup:missing") + : RunAttemptId.make(`attempt:lookup:${size - 1}`), + status: "starting", + requestedAt: DateTime.makeUnsafe(0), + startedAt: null, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }; + + const turn = Orchestrator.providerTurnForRun({ attempts, providerTurns }, owner); + + assert.strictEqual(turn, findsFirstLegacy ? providerTurns[size - 2] : undefined); + assert.isAtMost(reads.count, 2 * (size + size)); + }, +); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5936f57ad5014..e8dfe6df4634d 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1352,21 +1352,23 @@ function providerThreadForRun( : projection.providerThreads.find((candidate) => candidate.id === run.providerThreadId); } -function providerTurnForRun( +export function providerTurnForRun( projection: Pick, run: OrchestrationV2Run, ): OrchestrationV2ProviderTurn | undefined { if (run.activeAttemptId === null) { return undefined; } - - return ( - latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId) ?? - projection.providerTurns.find((turn) => { - const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId); - return attempt?.providerTurnId === turn.id; - }) - ); + const latest = latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId); + if (latest !== undefined) { + return latest; + } + const namedTurnId = projection.attempts.find( + (candidate) => candidate.id === run.activeAttemptId, + )?.providerTurnId; + return namedTurnId === undefined || namedTurnId === null + ? undefined + : projection.providerTurns.find((turn) => turn.id === namedTurnId); } function contextSourcePointForRun( From c7df7004af5e5d086da00d556479efa0de4e8d2c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 12:15:28 -0800 Subject: [PATCH 103/162] fix(web): a photo picked on a phone attaches even when the composer collapses (#41021) --- .../src/components/ChatView.browser.test.tsx | 37 ++++++++ apps/web/src/components/chat/ChatComposer.tsx | 14 ++- .../chat/ComposerAttachmentStrip.tsx | 88 ++++++++++--------- apps/web/test/fakeEnvironment.ts | 7 +- 4 files changed, 100 insertions(+), 46 deletions(-) diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index 60c3c24ce5c2d..e721c46d48ec4 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -547,6 +547,43 @@ it.each(["new", "existing"] as const)( }, ); +it("a file picked after the phone composer collapses still attaches", async () => { + const thread = threadWithHistory("thread-40993", 1); + using _environment = installFakeEnvironment([thread]); + await page.viewport(390, 844); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + using _uploads = acceptAttachmentUploads(); + const editor = page.getByTestId("composer-editor"); + await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible(); + await userEvent.click(editor); + await expect.element(page.getByRole("button", { name: "Attach files" })).toBeVisible(); + const input = document.querySelector( + 'form[data-chat-composer-form] input[type="file"]', + ); + expect(input).not.toBeNull(); + + // Opening the native picker blurs the editor, which collapses the phone composer. + (editor.element() as HTMLElement).blur(); + await expect.element(page.getByRole("button", { name: "Attach files" })).not.toBeInTheDocument(); + const files = new DataTransfer(); + files.items.add(new File([PNG], "picked.png", { type: "image/png" })); + input!.files = files.files; + input!.dispatchEvent(new Event("change", { bubbles: true })); + + await expect.element(page.getByRole("img", { name: "picked.png" })).toBeVisible(); +}); + it("opens the thread actions menu for an older settled thread the shell leaves out", async () => { const thread = { ...threadWithHistory("older-settled", 1), olderSettled: true as const }; using _environment = installFakeEnvironment([thread]); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 85a7f6173bf96..5b540f48c483e 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -216,6 +216,7 @@ import { } from "./ComposerCommandMenu"; import { ComposerAttachButton, + ComposerAttachInput, ComposerAttachmentFileList, ComposerAttachmentMediaRow, ComposerFilePreviewDialog, @@ -1119,6 +1120,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerEditorRef = useRef(null); const pasteAsTextShortcutUntilRef = useRef(0); const composerFormRef = useRef(null); + const composerAttachInputRef = useRef(null); const composerSurfaceRef = useRef(null); const providerInputRejectedRef = useRef(false); const composerSelectLockRef = useRef(false); @@ -3614,10 +3616,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) /> ) : null; const composerAttachButton = showComposerAttachAction ? ( - + composerAttachInputRef.current?.click()} /> ) : null; return ( + {showComposerAttachAction ? ( + + ) : null}
    ; readonly addComposerAttachments: (files: File[]) => Promise; readonly focusComposer: () => void; }) { + return ( + { + const files = Array.from(event.currentTarget.files ?? []); + event.currentTarget.value = ""; + // Inserting a chip refocuses the editor after the draft renders; + // focusing synchronously here would report the editor's stale text + // over the prompt that was just written. + void addComposerAttachments(files).then((inserted) => { + if (!inserted) focusComposer(); + }); + }} + /> + ); +} + +export function ComposerAttachButton({ onOpenPicker }: { readonly onOpenPicker: () => void }) { const gt = useGT(); - const inputRef = useRef(null); return ( - <> - { - const files = Array.from(event.currentTarget.files ?? []); - event.currentTarget.value = ""; - // Inserting a chip refocuses the editor after the draft renders; - // focusing synchronously here would report the editor's stale text - // over the prompt that was just written. - void addComposerAttachments(files).then((inserted) => { - if (!inserted) focusComposer(); - }); - }} - /> - - event.preventDefault()} - onClick={() => inputRef.current?.click()} - aria-label={gt("Attach files")} - /> - } - > - {/* The clip's weight sits in its upper loop; 1px down reads as centered on the row. */} - - - - Attach files - - - + + event.preventDefault()} + onClick={onOpenPicker} + aria-label={gt("Attach files")} + /> + } + > + {/* The clip's weight sits in its upper loop; 1px down reads as centered on the row. */} + + + + Attach files + + ); } diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index 71e8875bb56db..734fe38dad33b 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -67,7 +67,12 @@ const descriptor = { // A matching version, since a mismatch adds an update banner a typical user never sees. serverVersion: APP_VERSION, orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, - capabilities: { repositoryIdentity: true, sideChats: true, freshContext: true }, + capabilities: { + repositoryIdentity: true, + sideChats: true, + freshContext: true, + fileAttachments: { maxUploadBytes: 10_000_000 }, + }, }; const auth = { policy: "loopback-browser", From 02a4c18d644e1b4af2dfa558c95e68e827042215 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:20:42 +0100 Subject: [PATCH 104/162] fix(mobile): cancel pending media actions when swiping gallery pages (#41027) Co-authored-by: Julius Marminge --- .../ui/FilePreviewModal.android.tsx | 32 +++- .../components/ui/FilePreviewSession.test.tsx | 169 +++++++++++++++++- apps/mobile/src/state/mediaActions.ts | 13 +- 3 files changed, 197 insertions(+), 17 deletions(-) diff --git a/apps/mobile/src/components/ui/FilePreviewModal.android.tsx b/apps/mobile/src/components/ui/FilePreviewModal.android.tsx index 017dbdb1456fb..d9f732853dddd 100644 --- a/apps/mobile/src/components/ui/FilePreviewModal.android.tsx +++ b/apps/mobile/src/components/ui/FilePreviewModal.android.tsx @@ -2,7 +2,7 @@ import { T, useGT } from "gt-react-native"; import { Button } from "./Button"; import * as Dialog from "./Dialog"; -import { createContext, useContext, useEffect, useEffectEvent } from "react"; +import { createContext, useContext, useEffect, useEffectEvent, useRef } from "react"; import { Modal, View } from "react-native"; import ImageViewing from "react-native-image-viewing"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -133,14 +133,23 @@ type ImagePreviewProps = { readonly onRequestClose: () => void; }; -const ImagePreviewContext = createContext(null); +const ImagePreviewContext = createContext< + (ImagePreviewProps & { readonly getSaveImageSignal: () => AbortSignal }) | null +>(null); +// Keyed by page so swiping away clears the busy state and aborts pending share preparation. function ImagePreviewHeader(header: { readonly imageIndex: number }) { + return ; +} + +function ImagePreviewPageHeader(header: { readonly imageIndex: number }) { const props = useContext(ImagePreviewContext)!; const source = props.source.images[header.imageIndex]; const gt = useGT(); const insets = useSafeAreaInsets(); - const mediaActions = useMediaActions(source?.actionsSource, props.onRequestClose); + const mediaActions = useMediaActions(source?.actionsSource, props.onRequestClose, { + getSaveImageSignal: props.getSaveImageSignal, + }); return ( (null); + const getSaveImageSignal = () => { + if (saveController.current === null) { + saveController.current = new AbortController(); + } + return saveController.current.signal; + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- saves survive a page change but stop when the gallery unmounts + useEffect( + () => () => { + saveController.current?.abort(); + saveController.current = null; + }, + [], + ); return ( - + ({ refreshAssetUrl: vi.fn<(environmentId: string, resource: { url: string }) => Promise>(), alert: vi.fn(), + share: vi.fn(), + download: vi.fn(), previews: [] as unknown[], mounts: 0, presentationFinished: false, })); -vi.mock("../../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl })); +vi.mock("../../state/assets", () => ({ + refreshAssetUrl: harness.refreshAssetUrl, + useRefreshAssetUrl: (environmentId: string, resource: { url: string }) => () => + harness.refreshAssetUrl(environmentId, resource), +})); vi.mock("../../lib/localAttachmentPreview", () => ({ loadLocalAttachmentPreview: vi.fn() })); vi.mock("../../lib/attachmentDownload", () => ({ - downloadAndShareAttachment: vi.fn(), + downloadAndShareAttachment: harness.share, + downloadAttachmentForPreview: harness.download, nativeViewerErrorMessage: () => "", shareLocalAttachment: vi.fn(), })); @@ -30,14 +46,46 @@ vi.mock("./Button", () => ({ Button: () => null })); vi.mock("./SheetHeader", () => ({ SheetHeader: () => null })); vi.mock("./AppText", () => ({ AppText: () => null })); vi.mock("../PdfPreview", () => ({ PdfPreview: () => null })); -vi.mock("../MediaPreviewHeader", () => ({ MediaPreviewHeader: () => null })); -vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) })); -vi.mock("react-native", () => ({ Modal: () => null, View: () => null })); +vi.mock("../MediaPreviewHeader", () => ({ + MediaPreviewHeader: ({ media }: { media: ReturnType }) => + media.actions + .filter(({ id }) => id === "save" || id === "save-image") + .map(({ id, disabled, run, title }) => ( + + )), +})); +vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({ navigate: vi.fn() }) })); +vi.mock("../../state/session", () => ({ + environmentSession: { sessionStateAtom: (environmentId: string) => environmentId }, +})); +const grant = { authenticated: true, scopes: [AuthFilesystemReadScope] }; +vi.mock("../../state/query", () => ({ + useEnvironmentQuery: () => ({ data: grant, error: null }), +})); +vi.mock("../../state/atom-registry", () => ({ + appAtomRegistry: { get: () => AsyncResult.success(grant) }, +})); +vi.mock("expo", () => ({ requireNativeModule: vi.fn() })); +vi.mock("expo-clipboard", () => ({ setStringAsync: vi.fn() })); +vi.mock("expo-haptics", () => ({ notificationAsync: vi.fn() })); +vi.mock("react-native", () => ({ + Modal: () => null, + Platform: { OS: "android", Version: 35 }, + View: ({ children }: { children: ReactNode }) => children, +})); vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0 }) })); vi.mock("react-native-image-viewing", () => ({ default: function ImageViewing(props: { images: readonly { uri?: string }[]; imageIndex: number; + HeaderComponent?: ComponentType<{ imageIndex: number }>; }) { useState(() => harness.mounts++); harness.previews.push({ @@ -45,7 +93,17 @@ vi.mock("react-native-image-viewing", () => ({ images: props.images, selectedIndex: props.imageIndex, }); - return null; + const [index, setIndex] = useState(props.imageIndex); + const Header = props.HeaderComponent; + if (!Header) return null; + return ( + <> +
    + {props.images.map(({ uri }, imageIndex) => ( +
    - {hasProjects ? ( - <> - {projectScope} - - - - - ) : null} + {hasProjects ? projectScope : null} Date: Sun, 22 Nov 2026 15:44:40 -0500 Subject: [PATCH 108/162] feat(mobile): favorites only is its own model filter, not a provider (#32887) Co-authored-by: Julius Marminge --- .../features/threads/ThreadSettingsSheet.tsx | 45 ++++++++++++------- apps/mobile/src/i18n/translations/de.json | 2 +- apps/mobile/src/i18n/translations/en.json | 2 +- apps/mobile/src/i18n/translations/es.json | 2 +- apps/mobile/src/i18n/translations/fr.json | 2 +- apps/mobile/src/i18n/translations/ja.json | 2 +- apps/mobile/src/i18n/translations/ko.json | 2 +- apps/mobile/src/i18n/translations/pt-BR.json | 2 +- apps/mobile/src/i18n/translations/ru.json | 2 +- apps/mobile/src/i18n/translations/sv.json | 2 +- apps/mobile/src/i18n/translations/zh.json | 2 +- 11 files changed, 38 insertions(+), 27 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx index f90416a70b8b4..51fe125bf087e 100644 --- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx @@ -146,7 +146,6 @@ const EMPTY_MODEL_FAVORITES: ReadonlyArray<{ readonly provider: ProviderInstanceId; readonly model: string; }> = []; -const FAVORITES_PROVIDER_FILTER = "@favorites"; // Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites. const attemptedMigrationGenerations = new Map(); function ProviderHeader(props: { @@ -333,6 +332,7 @@ type ThreadSettingsSessionValue = { readonly providerExpansionOverrides: ReadonlySet; readonly hasLegacyModels: boolean; readonly pendingModel: ModelOption | null; + readonly favoritesOnly: boolean; readonly providerFilter: string | null; readonly searchQuery: string; readonly showLegacy: boolean; @@ -341,6 +341,7 @@ type ThreadSettingsSessionValue = { readonly isApplied: (option: ModelOption) => boolean; readonly isDisplayed: (option: ModelOption) => boolean; readonly pressModel: (option: ModelOption) => void; + readonly setFavoritesOnly: (favoritesOnly: boolean) => void; readonly setProviderFilter: (providerKey: string | null) => void; readonly setSearchQuery: (query: string) => void; readonly setShowLegacy: (showLegacy: boolean) => void; @@ -507,6 +508,7 @@ function ThreadSettingsSessionProvider( }); }; const [showLegacyToggle, setShowLegacyToggle] = useState(false); + const [favoritesOnly, setFavoritesOnly] = useState(false); const [providerFilter, setProviderFilter] = useState(null); const [searchQuery, setSearchQuery] = useState(""); const [providerExpansionOverrides, setProviderExpansionOverrides] = useState>( @@ -630,9 +632,7 @@ function ThreadSettingsSessionProvider( const environmentId = props.environmentId; // Like the web picker's open tab: scanning every provider would spawn a probe per provider. const scannedInstanceId = - providerFilter !== null && providerFilter !== FAVORITES_PROVIDER_FILTER - ? ProviderInstanceId.make(providerFilter) - : props.providerInstanceId; + providerFilter !== null ? ProviderInstanceId.make(providerFilter) : props.providerInstanceId; const workspaceScan = props.cwd && scannedInstanceId ? { instanceId: scannedInstanceId, cwd: props.cwd } : null; @@ -656,6 +656,7 @@ function ThreadSettingsSessionProvider( providerExpansionOverrides, hasLegacyModels, pendingModel, + favoritesOnly, providerFilter, searchQuery, showLegacy: showLegacyToggle, @@ -664,6 +665,7 @@ function ThreadSettingsSessionProvider( isApplied, isDisplayed, pressModel, + setFavoritesOnly, setProviderFilter, setSearchQuery, setShowLegacy: setShowLegacyToggle, @@ -842,7 +844,7 @@ function subProviderCatalogItems( if ( !group.subProviders?.length || session.searchQuery.trim().length > 0 || - session.providerFilter === FAVORITES_PROVIDER_FILTER + session.favoritesOnly ) { return null; } @@ -887,11 +889,7 @@ function buildThreadSettingsCatalogItems( locale: string, ): ReadonlyArray { return session.providerGroups.flatMap((group) => { - if ( - session.providerFilter !== null && - session.providerFilter !== FAVORITES_PROVIDER_FILTER && - group.providerKey !== session.providerFilter - ) { + if (session.providerFilter !== null && group.providerKey !== session.providerFilter) { return []; } const driver = group.models[0]?.providerDriver ?? group.providerKey; @@ -900,12 +898,12 @@ function buildThreadSettingsCatalogItems( providerLabel: group.providerLabel, query: session.searchQuery, favoriteKeys: session.favoriteKeys, - favoritesOnly: session.providerFilter === FAVORITES_PROVIDER_FILTER, + favoritesOnly: session.favoritesOnly, showLegacy: session.manageHidden || session.showLegacy, isDisplayed: session.isDisplayed, }); const updateRequiredNotice = - group.updateRequired && session.providerFilter !== FAVORITES_PROVIDER_FILTER + group.updateRequired && !session.favoritesOnly ? formatProviderUpdateRequiredNotice( group.updateRequired, session.searchQuery, @@ -918,7 +916,10 @@ function buildThreadSettingsCatalogItems( } const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver); const containsAppliedSelection = group.models.some(session.isApplied); - const isNarrowed = session.providerFilter !== null || session.searchQuery.trim().length > 0; + const isNarrowed = + session.favoritesOnly || + session.providerFilter !== null || + session.searchQuery.trim().length > 0; const collapsible = !isNarrowed; const collapsed = providerSectionIsCollapsed({ defaultExpanded: isPrimary || containsAppliedSelection, @@ -1111,7 +1112,9 @@ function ThreadSettingsMainContent(props: { const animationsReady = listLoaded && !reducedMotion && !reduceMotionEnabled; const catalogItems = buildThreadSettingsCatalogItems(session, m, locale); const hasActiveCatalogFilter = - session.providerFilter !== null || session.searchQuery.trim().length > 0; + session.favoritesOnly || + session.providerFilter !== null || + session.searchQuery.trim().length > 0; const listItems = [ ...(catalogItems.length === 0 ? ([{ kind: "empty", key: "empty" }] as const) : catalogItems), { kind: "options", key: "options" }, @@ -1138,7 +1141,8 @@ function ThreadSettingsMainContent(props: { content = ( - {session.providerFilter === FAVORITES_PROVIDER_FILTER && + {session.favoritesOnly && + session.providerFilter === null && session.searchQuery.trim().length === 0 ? gt("No favorite models") : hasActiveCatalogFilter @@ -1331,7 +1335,8 @@ function ThreadSettingsModelsScreen() { const session = useThreadSettingsSession(); const presentation = useThreadSettingsPickerPresentation(); const navigation = useNavigation>(); - const hasCustomCatalogFilter = session.providerFilter !== null || session.showLegacy; + const hasCustomCatalogFilter = + session.favoritesOnly || session.providerFilter !== null || session.showLegacy; const commitAndClose = useEffectEvent(() => { if (!session.commitPendingModel()) return; presentation.onClose(); @@ -1347,7 +1352,6 @@ function ThreadSettingsModelsScreen() { const searchToolbarInset = useSearchToolbarInset(search); const providerFilters = [ { id: "all-providers", title: gt("All providers"), value: null }, - { id: "favorites", title: gt("Favorites"), value: FAVORITES_PROVIDER_FILTER }, ...session.providerGroups.map((group) => ({ id: `provider:${group.providerKey}`, title: group.providerLabel, @@ -1369,6 +1373,12 @@ function ThreadSettingsModelsScreen() { ? "line.3.horizontal.decrease.circle.fill" : "line.3.horizontal.decrease", items: [ + { + id: "favorites-only", + title: gt("Favorites only"), + selected: session.favoritesOnly, + onPress: () => session.setFavoritesOnly(!session.favoritesOnly), + }, { id: "provider", title: gt("Provider"), @@ -1393,6 +1403,7 @@ function ThreadSettingsModelsScreen() { }, ]} optionsVersion={[ + session.favoritesOnly, session.providerFilter, session.providerGroups.map((group) => group.providerKey), session.showLegacy, diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 5adf7cae2b1f0..8b31a8b3c4344 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -4720,7 +4720,7 @@ "c11a66f71057f074": "Dein Prompt enthält „ultrathink“ im Text. Entferne es, um diese Option zu ändern.", "b589c01784b9a88c": "Modell suchen", "9b0277205d8a9b04": "Alle Anbieter", - "4314e052a3524c51": "Favoriten", + "72ae7e7c5ca1c5fc": "Nur Favoriten", "279ab25bdca98778": "Thread-Einstellungen", "0ef86daa831dde67": "Thread-Einstellungen abbrechen", "cb27bc9ea63671c0": "Modellfilter", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 44804860b704d..ca29f2163889b 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -4722,7 +4722,7 @@ "c11a66f71057f074": "Your prompt contains \"ultrathink\" in the text. Remove it to change this option.", "b589c01784b9a88c": "Find a model", "9b0277205d8a9b04": "All providers", - "4314e052a3524c51": "Favorites", + "72ae7e7c5ca1c5fc": "Favorites only", "279ab25bdca98778": "Thread settings", "0ef86daa831dde67": "Cancel thread settings", "cb27bc9ea63671c0": "Model filters", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index b89e4cd636b2e..95c353b708461 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -4713,7 +4713,7 @@ "c11a66f71057f074": "Tu prompt contiene \"ultrathink\" en el texto. Quítalo para cambiar esta opción.", "b589c01784b9a88c": "Buscar un modelo", "9b0277205d8a9b04": "Todos los proveedores", - "4314e052a3524c51": "Favoritos", + "72ae7e7c5ca1c5fc": "Solo favoritos", "279ab25bdca98778": "Ajustes del hilo", "0ef86daa831dde67": "Cancelar ajustes del hilo", "cb27bc9ea63671c0": "Filtros de modelos", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 75e6c8ed3b83f..606119293ca58 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -4714,7 +4714,7 @@ "c11a66f71057f074": "Votre prompt contient « ultrathink ». Retirez-le pour modifier cette option.", "b589c01784b9a88c": "Trouver un modèle", "9b0277205d8a9b04": "Tous les fournisseurs", - "4314e052a3524c51": "Favoris", + "72ae7e7c5ca1c5fc": "Favoris uniquement", "279ab25bdca98778": "Paramètres du fil", "0ef86daa831dde67": "Annuler les paramètres du fil", "cb27bc9ea63671c0": "Filtres de modèles", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index ade01f9a68ae8..12279cacfe082 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -4694,7 +4694,7 @@ "c11a66f71057f074": "プロンプトのテキストに \"ultrathink\" が含まれています。このオプションを変更するには削除してください。", "b589c01784b9a88c": "モデルを検索", "9b0277205d8a9b04": "すべてのプロバイダー", - "4314e052a3524c51": "お気に入り", + "72ae7e7c5ca1c5fc": "お気に入りのみ", "279ab25bdca98778": "スレッドの設定", "0ef86daa831dde67": "スレッドの設定をキャンセル", "cb27bc9ea63671c0": "モデルのフィルター", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index e55249e7c76d5..6105dbbff9700 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -4699,7 +4699,7 @@ "c11a66f71057f074": "프롬프트 텍스트에 \"ultrathink\"가 포함되어 있습니다. 이 옵션을 변경하려면 제거하세요.", "b589c01784b9a88c": "모델 찾기", "9b0277205d8a9b04": "모든 제공자", - "4314e052a3524c51": "즐겨찾기", + "72ae7e7c5ca1c5fc": "즐겨찾기만", "279ab25bdca98778": "스레드 설정", "0ef86daa831dde67": "스레드 설정 취소", "cb27bc9ea63671c0": "모델 필터", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index e373faf86a051..346d3a17f8d1c 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -4714,7 +4714,7 @@ "c11a66f71057f074": "Seu prompt contém \"ultrathink\" no texto. Remova para mudar esta opção.", "b589c01784b9a88c": "Encontrar um modelo", "9b0277205d8a9b04": "Todos os provedores", - "4314e052a3524c51": "Favoritos", + "72ae7e7c5ca1c5fc": "Somente favoritos", "279ab25bdca98778": "Configurações da thread", "0ef86daa831dde67": "Cancelar configurações da thread", "cb27bc9ea63671c0": "Filtros de modelos", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index c56ae7ca47388..24f1f02d8282c 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -4792,7 +4792,7 @@ "c11a66f71057f074": "В тексте промпта есть «ultrathink». Удалите его, чтобы изменить этот параметр.", "b589c01784b9a88c": "Найти модель", "9b0277205d8a9b04": "Все провайдеры", - "4314e052a3524c51": "Избранное", + "72ae7e7c5ca1c5fc": "Только избранное", "279ab25bdca98778": "Настройки треда", "0ef86daa831dde67": "Отменить настройки треда", "cb27bc9ea63671c0": "Фильтры моделей", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7887ac576fc11..e9df1ae43bff3 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -4720,7 +4720,7 @@ "c11a66f71057f074": "Din prompt innehåller ”ultrathink” i texten. Ta bort det för att ändra det här alternativet.", "b589c01784b9a88c": "Hitta en modell", "9b0277205d8a9b04": "Alla leverantörer", - "4314e052a3524c51": "Favoriter", + "72ae7e7c5ca1c5fc": "Endast favoriter", "279ab25bdca98778": "Trådinställningar", "0ef86daa831dde67": "Avbryt trådinställningar", "cb27bc9ea63671c0": "Modellfilter", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 5b3d7f7841bfd..88cb17551721b 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -4703,7 +4703,7 @@ "c11a66f71057f074": "你的提示词中包含“ultrathink”。删除它才能修改这个选项。", "b589c01784b9a88c": "查找模型", "9b0277205d8a9b04": "所有提供方", - "4314e052a3524c51": "收藏", + "72ae7e7c5ca1c5fc": "仅收藏", "279ab25bdca98778": "会话设置", "0ef86daa831dde67": "取消会话设置", "cb27bc9ea63671c0": "模型筛选", From f9fbb004ac0c09ca178279ea84f336d2a8de81a5 Mon Sep 17 00:00:00 2001 From: JoshuaRileyDev <59296334+JoshuaRileyDev@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:45:29 +0000 Subject: [PATCH 109/162] feat(devices): double-tap Home opens the app switcher (#29459) Co-authored-by: Julius Marminge --- .../client-runtime/src/device/stream.test.ts | 29 +++++++++++++++++++ packages/client-runtime/src/device/stream.ts | 10 +++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/device/stream.test.ts b/packages/client-runtime/src/device/stream.test.ts index ad930680fbeb5..9050e6c18504f 100644 --- a/packages/client-runtime/src/device/stream.test.ts +++ b/packages/client-runtime/src/device/stream.test.ts @@ -140,6 +140,35 @@ describe("native device stream transport", () => { }, ); + it.each([ + ["ios", { button: "home" }, { button: "app_switcher" }], + ["android", { type: "home" }, { type: "recents" }], + ] as const)( + "opens the %s app switcher on a double-tapped home button", + async (platform, home, switcher) => { + const { client, opened } = setup(platform); + client.start(); + const socket = await opened; + socket.onopen?.(); + if (platform === "ios") socket.onmessage?.({ data: Uint8Array.of(0x83).buffer }); + socket.send.mockClear(); + + client.pressButton("home"); + client.pressButton("home"); + client.pressButton("home"); + vi.advanceTimersByTime(1000); + client.pressButton("home"); + + const sent = socket.send.mock.calls.map(([payload]) => + JSON.parse( + typeof payload === "string" ? payload : new TextDecoder().decode(payload.subarray(1)), + ), + ); + expect(sent).toEqual([home, switcher, home, home]); + client.stop(); + }, + ); + it.each(["ios", "android"] as const)( "does not renew credentials or reconnect a stopped %s stream", async (platform) => { diff --git a/packages/client-runtime/src/device/stream.ts b/packages/client-runtime/src/device/stream.ts index c570ee107ad55..45824149a8c66 100644 --- a/packages/client-runtime/src/device/stream.ts +++ b/packages/client-runtime/src/device/stream.ts @@ -1,4 +1,4 @@ -// @effect-diagnostics globalFetch:off globalTimers:off - This browser and WebView transport runs without an Effect runtime. +// @effect-diagnostics globalFetch:off globalTimers:off globalDate:off - This browser and WebView transport runs without an Effect runtime. import { createDuoControl, @@ -157,6 +157,7 @@ const SOFT_DECODE_QUEUE = 8; const ANDROID_MAX_TEXT_BYTES = 300; // The pinned hub queue depth is 128; the client does not read queue rejections. const ANDROID_MAX_TEXT_CHUNKS = 64; +const HOME_DOUBLE_TAP_MS = 400; const IOS_MSG_TOUCH = 0x03; const IOS_MSG_BUTTON = 0x04; @@ -428,6 +429,7 @@ export function createDeviceStreamClient( isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg && !serveSimOnly); let stopped = true; + let lastHomePress = -Infinity; let socket: WebSocket | null = null; let controller: AbortController | null = null; const retryTimers = new Map<"video" | "input", ReturnType>(); @@ -1460,7 +1462,11 @@ export function createDeviceStreamClient( } if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk })); }, - pressButton: (button) => { + pressButton: (pressed) => { + const now = Date.now(); + const doubleHome = pressed === "home" && now - lastHomePress < HOME_DOUBLE_TAP_MS; + lastHomePress = pressed === "home" && !doubleHome ? now : -Infinity; + const button = doubleHome ? "appSwitcher" : pressed; if (avcc) { const name = button === "home" From 735c1e74012248f47056953e91c7059949b2c2f6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 12:48:31 -0800 Subject: [PATCH 110/162] test(desktop): AppImage shim test's fake server ignores a second stop signal (#41062) --- apps/desktop/src/app/DesktopCliShim.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index 929148fdbb32f..dda8e058b7179 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -66,10 +66,11 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { return { root, image, appImage, shim }; }; -// Stays up after a signal until the test lets it finish, like a server shutting down. +// Stays up after a signal until the test lets it finish, like a server shutting down. A group +// signal and the launcher's forwarded one can both arrive; a re-run trap would read stdin's EOF. const SLOW_SERVER = [ "#!/bin/sh", - "trap 'echo stopping >&3; read go; echo \"stopped $go\" >&3; exit 7' TERM HUP", + 'trap \'trap "" TERM HUP; echo stopping >&3; read go; echo "stopped $go" >&3; exit 7\' TERM HUP', "echo ready", "while :; do sleep 0.05; done", "", From 7e3a9ba1b9b1551d379dddf7d109d8a98121036d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 12:49:30 -0800 Subject: [PATCH 111/162] fix(server): a task folder creation that loses a branch race no longer deletes the winner's branch (#41061) --- apps/server/src/workspace/TaskFolders.test.ts | 51 +++++++------- apps/server/src/workspace/TaskFolders.ts | 67 +++++++++++++------ 2 files changed, 74 insertions(+), 44 deletions(-) diff --git a/apps/server/src/workspace/TaskFolders.test.ts b/apps/server/src/workspace/TaskFolders.test.ts index c156f190e0049..2be3e39c09817 100644 --- a/apps/server/src/workspace/TaskFolders.test.ts +++ b/apps/server/src/workspace/TaskFolders.test.ts @@ -248,32 +248,35 @@ it.effect("finds no common folder for two Windows drives instead of climbing for }).pipe(Effect.provide(NodePath.layerWin32)), ); -it.live("gives two creations on one branch a folder each", () => - withState((state) => - Effect.gen(function* () { - const { fileSystem, path, tmp, repository } = yield* fixture; - const api = yield* repository("shop/api"); - state.workspaceRoot = path.join(tmp, "shop"); - state.trackedFolders = tracked(api); +it.live.each([{ projectIsRepository: false }, { projectIsRepository: true }])( + "gives two creations on one branch a folder each, project is a repository=$projectIsRepository", + ({ projectIsRepository }) => + withState((state) => + Effect.gen(function* () { + const { fileSystem, path, tmp, repository } = yield* fixture; + const shop = projectIsRepository ? yield* repository("shop") : path.join(tmp, "shop"); + const api = yield* repository("shop/api"); + state.workspaceRoot = shop; + state.trackedFolders = tracked(api); - // Git gives the branch to one of them; the other's rollback must leave that one's folder. - const exits = yield* Effect.all( - [Effect.exit(create("feature")), Effect.exit(create("feature"))], - { - concurrency: 2, - }, - ); + // Git gives the branch to one of them; the other's rollback must leave that one's folder. + const exits = yield* Effect.all( + [Effect.exit(create("feature")), Effect.exit(create("feature"))], + { + concurrency: 2, + }, + ); - const created = exits.flatMap((exit) => - Exit.isSuccess(exit) ? [exit.value.taskFolder] : [], - ); - assert.isAtLeast(created.length, 1); - assert.equal(new Set(created.map((taskFolder) => taskFolder.root)).size, created.length); - for (const taskFolder of created) { - assert.isTrue(yield* fileSystem.exists(path.join(taskFolder.root, "api", "README.md"))); - } - }), - ), + const created = exits.flatMap((exit) => + Exit.isSuccess(exit) ? [exit.value.taskFolder] : [], + ); + assert.isAtLeast(created.length, 1); + assert.equal(new Set(created.map((taskFolder) => taskFolder.root)).size, created.length); + for (const taskFolder of created) { + assert.isTrue(yield* fileSystem.exists(path.join(taskFolder.root, "api", "README.md"))); + } + }), + ), ); it.live.each([{ projectIsRepository: true }, { projectIsRepository: false }])( diff --git a/apps/server/src/workspace/TaskFolders.ts b/apps/server/src/workspace/TaskFolders.ts index 4911065118ce4..75c12d8a7409b 100644 --- a/apps/server/src/workspace/TaskFolders.ts +++ b/apps/server/src/workspace/TaskFolders.ts @@ -1,4 +1,5 @@ import { + GitCommandError, type ProjectId, type ProjectTrackedFolder, TASK_FOLDER_DEFAULT_REPOSITORIES_MAX, @@ -15,6 +16,7 @@ import { flattenTemporaryWorktreeBranchName, isTemporaryWorktreeBranch } from "@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; @@ -224,6 +226,8 @@ export const layoutAnchor = ( return { anchor, unreachable }; }; +const isGitCommandError = Schema.is(GitCommandError); + const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -863,6 +867,7 @@ const make = Effect.gen(function* () { branch: string, startFromOrigin: boolean, baseBranch: string | undefined, + recordBranch: (exit: Exit.Exit) => Effect.Effect, ) { const worktreePath = mapped(taskFolder, repository.path); // The project's own checkout (a post-checkout hook, say) already provided this repository. @@ -874,13 +879,15 @@ const make = Effect.gen(function* () { return null; yield* fileSystem.makeDirectory(path.dirname(worktreePath), { recursive: true }); const start = yield* repositoryStart(repository.path, startFromOrigin, baseBranch); - yield* git.createWorktree({ - cwd: repository.path, - refName: start.refName, - newRefName: branch, - baseRefName: start.baseRefName, - path: worktreePath, - }); + yield* git + .createWorktree({ + cwd: repository.path, + refName: start.refName, + newRefName: branch, + baseRefName: start.baseRefName, + path: worktreePath, + }) + .pipe(Effect.onExit(recordBranch)); return { repository: { repositoryPath: repository.path, @@ -933,15 +940,32 @@ const make = Effect.gen(function* () { // A layout command may check out a branch that was already there; a rollback leaves it. const hadBranch = new Set(); let layoutStarted = false; - // Where this attempt makes the branch: a checkout that fails halfway leaves it behind. - let branchMadeIn = [ + // Where this attempt may make the branch: none of them had it when listed. + const branchMissingIn = new Set([ ...taskPlan.repositories .filter((_, index) => !names[index]!.includes(branch)) .map((repository) => repository.path), ...(taskPlan.projectIsRepository && !projectNames.includes(branch) ? [taskPlan.projectRoot] : []), - ]; + ]); + // Where this attempt made the branch: a checkout that fails halfway leaves it behind. Only + // a checkout it ran counts, and not one Git refused because another creation made it first. + let branchMadeIn: string[] = []; + const recordBranch = + (cwd: string) => + (exit: Exit.Exit) => + Effect.sync(() => { + const refused = + Exit.isFailure(exit) && + exit.cause.reasons.some( + (reason) => + Cause.isFailReason(reason) && + isGitCommandError(reason.error) && + reason.error.operation === "GitVcsDriver.createWorktree.createBranch", + ); + if (branchMissingIn.has(cwd) && !refused) branchMadeIn.push(cwd); + }); return yield* Effect.gen(function* () { yield* fileSystem.makeDirectory(root, { recursive: true }); // Recorded before any checkout, so an interrupted creation is still found and removed. @@ -1010,16 +1034,18 @@ const make = Effect.gen(function* () { } if (taskPlan.projectIsRepository) { yield* fileSystem.makeDirectory(path.dirname(empty.projectPath), { recursive: true }); - yield* git.createWorktree( - { - cwd: taskPlan.projectRoot, - refName: input.projectStart.refName, - newRefName: branch, - baseRefName: input.projectStart.baseRefName, - path: empty.projectPath, - }, - input.projectProgress === undefined ? {} : { progress: input.projectProgress }, - ); + yield* git + .createWorktree( + { + cwd: taskPlan.projectRoot, + refName: input.projectStart.refName, + newRefName: branch, + baseRefName: input.projectStart.baseRefName, + path: empty.projectPath, + }, + input.projectProgress === undefined ? {} : { progress: input.projectProgress }, + ) + .pipe(Effect.onExit(recordBranch(taskPlan.projectRoot))); } else { yield* linkFolder(taskPlan.projectRoot, empty.projectPath, taskPlan.trackedRepositories); } @@ -1049,6 +1075,7 @@ const make = Effect.gen(function* () { branch, input.startFromOrigin, input.baseBranch, + recordBranch(repository.path), ) ).pipe( Effect.tap((worktree) => From e213da2a32236cd932687351a0694be8935d92b0 Mon Sep 17 00:00:00 2001 From: Tameem Bin Haider Date: Mon, 23 Nov 2026 02:57:01 +0600 Subject: [PATCH 112/162] fix(client-runtime): refresh stale server clock offset after host sleep (#41037) Co-authored-by: Julius Marminge --- apps/server/src/ws.ts | 3 +- packages/client-runtime/src/clock.test.ts | 28 +++++++++++- packages/client-runtime/src/clock.ts | 23 ++++++++++ .../client-runtime/src/rpc/session.test.ts | 43 +++++++++++++++++++ packages/client-runtime/src/rpc/session.ts | 15 ++++++- packages/client-runtime/src/state/shell.ts | 12 ++++++ .../src/state/threads-sync.test.ts | 12 ++++++ packages/client-runtime/src/state/threads.ts | 28 ++++++++++-- packages/contracts/src/rpc.ts | 6 ++- 9 files changed, 160 insertions(+), 10 deletions(-) diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index b5faaaa16f97c..fc04ad68e46cd 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2396,7 +2396,8 @@ export const layerWsRpc = ( Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe( Effect.andThen(scheduledTasks.getWebhookDelivery(input)), ), - [WS_METHODS.serverProbe]: (_input) => Effect.succeed({}), + [WS_METHODS.serverProbe]: (_input) => + Effect.map(DateTime.now, (now) => ({ serverTime: DateTime.formatIso(now) })), [WS_METHODS.serverGetConfig]: (_input) => loadServerConfig({ usageLimitsCommand: false, diff --git a/packages/client-runtime/src/clock.test.ts b/packages/client-runtime/src/clock.test.ts index 1f45860addf7c..f26f830d5b88c 100644 --- a/packages/client-runtime/src/clock.test.ts +++ b/packages/client-runtime/src/clock.test.ts @@ -1,6 +1,12 @@ import { EnvironmentId } from "@t3tools/contracts"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { deadlineStore, recordServerClock, secondTick, toServerClock } from "./clock.ts"; +import { + deadlineStore, + observeServerTime, + recordServerClock, + secondTick, + toServerClock, +} from "./clock.ts"; describe("deadlineStore", () => { afterEach(() => { @@ -172,4 +178,24 @@ describe("server clock", () => { }); expect(toServerClock(environmentId, 12_345)).toBe(12_345); }); + + it("raises a stale negative offset when a host timestamp arrives ahead of it", () => { + const environmentId = EnvironmentId.make("caught-up"); + recordServerClock(environmentId, { + serverTimeMs: 1_000, + requestedAtMs: 2 * HOUR + 900, + receivedAtMs: 2 * HOUR + 1_050, + }); + expect(toServerClock(environmentId, 2 * HOUR + 10_050)).toBe(10_150); + + observeServerTime(environmentId, 2 * HOUR + 10_000, 2 * HOUR + 10_050); + expect(toServerClock(environmentId, 2 * HOUR + 20_050)).toBe(2 * HOUR + 20_000); + + observeServerTime(environmentId, 5_000, 2 * HOUR + 20_100); + expect(toServerClock(environmentId, 2 * HOUR + 20_050)).toBe(2 * HOUR + 20_000); + + const unrecorded = EnvironmentId.make("unrecorded"); + observeServerTime(unrecorded, HOUR, 1_000); + expect(toServerClock(unrecorded, 1_000)).toBe(1_000); + }); }); diff --git a/packages/client-runtime/src/clock.ts b/packages/client-runtime/src/clock.ts index f8f1290730084..67693220883b8 100644 --- a/packages/client-runtime/src/clock.ts +++ b/packages/client-runtime/src/clock.ts @@ -104,6 +104,29 @@ export function recordServerClock( ); } +/** + * A timestamp stamped by the host is never in its own future, so it gives a + * lower bound on the host's clock. Raises a stale negative offset (for example + * when a VM or WSL clock catches up after host sleep) without shifting a clock + * that already agrees. + */ +export function observeServerTime( + environmentId: EnvironmentId, + serverTimeMs: number, + receivedAtMs: number, +): void { + const currentOffset = serverClockOffsets.get(environmentId); + if ( + currentOffset === undefined || + !Number.isFinite(serverTimeMs) || + !Number.isFinite(receivedAtMs) + ) { + return; + } + if (receivedAtMs + currentOffset >= serverTimeMs) return; + serverClockOffsets.set(environmentId, serverTimeMs - receivedAtMs); +} + /** Converts client epoch milliseconds to the environment's clock. */ export function toServerClock(environmentId: EnvironmentId, clientMs: number): number { return clientMs + (serverClockOffsets.get(environmentId) ?? 0); diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index ebd4780ba5064..27bb60f567e10 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -1152,6 +1152,49 @@ describe("RpcSessionFactory", () => { }), ); + it.effect("refreshes the host clock when a liveness probe returns serverTime", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const ready = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket, { + ...ENCODED_SERVER_CONFIG, + serverTime: "1970-01-01T01:00:00.000Z", + }); + yield* Fiber.join(ready); + expect(toServerClock(PREPARED.environmentId, 0)).toBe(3_600_000); + + const legacyProbe = yield* Effect.forkChild(session.probe); + const legacyRequest = yield* awaitRequest(socket, 1); + socket.serverMessage( + encodeJson({ + _tag: "Exit", + requestId: legacyRequest.id, + exit: { _tag: "Success", value: {} }, + }), + ); + yield* Fiber.join(legacyProbe); + expect(toServerClock(PREPARED.environmentId, 0)).toBe(3_600_000); + + const probe = yield* Effect.forkChild(session.probe); + const probeRequest = yield* awaitRequest(socket, 2); + socket.serverMessage( + encodeJson({ + _tag: "Exit", + requestId: probeRequest.id, + exit: { + _tag: "Success", + value: { serverTime: "1970-01-01T00:00:00.000Z" }, + }, + }), + ); + yield* Fiber.join(probe); + expect(toServerClock(PREPARED.environmentId, 0)).toBe(0); + }), + ); + it.effect("reaches ready when a newer server sends unknown config members", () => Effect.gen(function* () { const { factory, sockets } = yield* makeFactory(); diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 91160a60941db..148005df2124d 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -515,9 +515,20 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ); const probe = initialConfig.pipe( Effect.flatMap(() => - protocolClient[WS_METHODS.serverProbe]({}).pipe(Effect.mapError(mapRpcError)), + Effect.gen(function* () { + const requestedAtMs = yield* Clock.currentTimeMillis; + const result = yield* protocolClient[WS_METHODS.serverProbe]({}).pipe( + Effect.mapError(mapRpcError), + ); + if (result.serverTime !== undefined) { + recordServerClock(connection.environmentId, { + serverTimeMs: Date.parse(result.serverTime), + requestedAtMs, + receivedAtMs: yield* Clock.currentTimeMillis, + }); + } + }), ), - Effect.asVoid, Effect.withSpan("clientRuntime.connection.rpcSession.probe"), ); diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts index 9fdd1898cc1cf..24fe257d58285 100644 --- a/packages/client-runtime/src/state/shell.ts +++ b/packages/client-runtime/src/state/shell.ts @@ -13,6 +13,7 @@ import { } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -25,6 +26,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef"; import * as SynchronizedRef from "effect/SynchronizedRef"; import { AsyncResult, Atom } from "effect/reactivity"; +import { observeServerTime } from "../clock.ts"; import * as EnvironmentRegistry from "../connection/registry.ts"; import { connectionProjectionPhase, type PreparedConnection } from "../connection/model.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; @@ -324,6 +326,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") let receivedAuthoritativeSnapshot = false; let snapshotRequired = false; let deltas: Array = []; + const receivedAtMs = yield* Clock.currentTimeMillis; const flushDeltas = () => { if (deltas.length > 0 && Option.isSome(next.snapshot)) { let sequence = next.snapshot.value.snapshotSequence; @@ -336,6 +339,15 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") removedAt.set(delta.threadId, delta.sequence); break; case "thread.updated": + // Replayed catch-up deltas may predate a backward host clock correction. + if (!waiting) { + observeServerTime( + environmentId, + DateTime.toEpochMillis(delta.thread.updatedAt), + receivedAtMs, + ); + } + break; case "project.updated": case "project.removed": break; diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 9fff726cd6ab8..d14b8a66c40cd 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -39,6 +39,7 @@ import { type PreparedConnection, type SupervisorConnectionState, } from "../connection/model.ts"; +import { recordServerClock, toServerClock } from "../clock.ts"; import * as ConnectionWakeups from "../connection/wakeups.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import * as Persistence from "../platform/persistence.ts"; @@ -2546,6 +2547,13 @@ describe("EnvironmentThreads", () => { it.effect("publishes a 20-event catch-up as one state change at its marker", () => Effect.gen(function* () { + // Replayed events can predate a backward host clock correction, so only live ones + // may raise the recorded offset. + recordServerClock(PREPARED.environmentId, { + serverTimeMs: 0, + requestedAtMs: 0, + receivedAtMs: 0, + }); const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); yield* awaitSubscriptionCount(harness, 1); expect(yield* Ref.get(harness.lastRequestCompletionMarker)).toBe(true); @@ -2564,10 +2572,14 @@ describe("EnvironmentThreads", () => { const live = yield* Queue.take(harness.observed); expect(live.status).toBe("live"); expect(Option.getOrThrow(live.data).thread.title).toBe("Title 20"); + expect(toServerClock(PREPARED.environmentId, 0)).toBe(0); yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 21)); const next = yield* Queue.take(harness.observed); expect(Option.getOrThrow(next.data).thread.title).toBe("Live title"); + expect(toServerClock(PREPARED.environmentId, 0)).toBe( + DateTime.toEpochMillis(Option.getOrThrow(next.data).thread.updatedAt), + ); }), ); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index 4882df1a6836e..c0921417ba5cf 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -13,6 +13,8 @@ import { import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; import { pendingBackgroundTurnItems } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Scope from "effect/Scope"; @@ -26,6 +28,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef"; import { HttpClient } from "effect/http"; import { Atom } from "effect/reactivity"; +import { observeServerTime } from "../clock.ts"; import * as RemoteEnvironmentAuthorization from "../authorization/service.ts"; import * as EnvironmentRegistry from "../connection/registry.ts"; import { connectionProjectionPhase } from "../connection/model.ts"; @@ -541,7 +544,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make { kind: "event" | "unknown-event" } >; // Per-batch streaming spans add trace volume without a useful timing boundary. - const applyEventsLocked = Effect.fnUntraced(function* (items: ReadonlyArray) { + const applyEventsLocked = Effect.fnUntraced(function* ( + items: ReadonlyArray, + // Replayed catch-up events may predate a backward host clock correction. + live: boolean, + ) { const appliedSequence = yield* SubscriptionRef.get(lastSequence); let sequence = appliedSequence; const fresh: EventItem[] = []; @@ -565,6 +572,17 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make yield* SubscriptionRef.set(lastSequence, sequence); if (fresh.length === 0) return; + if (live) { + const receivedAtMs = yield* Clock.currentTimeMillis; + for (const item of fresh) { + observeServerTime( + environmentId, + DateTime.toEpochMillis(item.event.occurredAt), + receivedAtMs, + ); + } + } + const waiting = yield* Ref.get(awaitingCompletion); // Apply against the latest projection/history in one update so a concurrent // loadEarlier merge (or history-meta patch) cannot be clobbered by a stale @@ -701,7 +719,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make return; } - yield* applyEventsLocked([item]); + yield* applyEventsLocked([item], false); }); // Items held until the completion marker apply together, so a replay-only resume renders once. @@ -739,6 +757,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } const items = catchUp; catchUp = []; + let live = !(yield* Ref.get(awaitingCompletion)); let events: SequencedItem[] = []; for (const item of items) { if ( @@ -751,11 +770,12 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make // Clearing the flag first lets the events before the marker publish // "live", so a catch-up ending in the marker is one state change. if (item.kind === "synchronized") yield* Ref.set(awaitingCompletion, false); - yield* applyEventsLocked(events); + yield* applyEventsLocked(events, live); events = []; yield* applyItemLocked(item); + if (item.kind === "synchronized") live = true; } - yield* applyEventsLocked(events); + yield* applyEventsLocked(events, live); yield* remember; }), ); diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index e30bf9af2937c..8a8fe05efb4da 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -45,7 +45,7 @@ import * as Schema from "effect/Schema"; import * as Rpc from "effect/rpc/Rpc"; import * as RpcGroup from "effect/rpc/RpcGroup"; import * as RpcMiddleware from "effect/rpc/RpcMiddleware"; -import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { IsoDateTime, NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { SecretSourceCheckResult } from "./settingsSecretValue.ts"; import { SecretReference } from "./secretReference.ts"; import { @@ -725,7 +725,9 @@ const WsServerRemoveKeybindingRpc = Rpc.make(WS_METHODS.serverRemoveKeybinding, const WsServerProbeRpc = Rpc.make(WS_METHODS.serverProbe, { payload: Schema.Struct({}), - success: Schema.Struct({}), + success: Schema.Struct({ + serverTime: Schema.optionalKey(IsoDateTime), + }), error: EnvironmentAuthorizationError, }); From 68e81cd1450fac2e150e01cad8c96525316b209c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 13:02:28 -0800 Subject: [PATCH 113/162] fix(server): settled-subagent check reads run status from runs_run_status_idx (#37902) Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> --- .../orchestration-v2/ProjectionStore.test.ts | 19 +++++- .../src/orchestration-v2/ProjectionStore.ts | 67 ++++++++++++------- 2 files changed, 59 insertions(+), 27 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 8df11001e241a..f13f3f05409ba 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -2520,6 +2520,18 @@ const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { subagents.length, ); // Both reads stay inside their indexes: no scan of the thread's nodes or provider threads. + // A dispatcher's statistics: the mostly NULL owner and session indexes match every row. + yield* sql`ANALYZE orchestration_v2_projection_provider_threads`; + yield* sql`DELETE FROM sqlite_stat1 WHERE tbl = 'orchestration_v2_projection_provider_threads'`; + for (const [index, stat] of [ + ["sqlite_autoindex_orchestration_v2_projection_provider_threads_1", "5531 1"], + ["orchestration_v2_projection_provider_threads_thread_idx", "5531 1"], + ["orchestration_v2_projection_provider_threads_owner_idx", "5531 5531"], + ["orchestration_v2_projection_provider_threads_session_idx", "5531 2766"], + ] as const) { + yield* sql`INSERT INTO sqlite_stat1 VALUES ('orchestration_v2_projection_provider_threads', ${index}, ${stat})`; + } + yield* sql`ANALYZE sqlite_schema`; for (const [table, seeks] of [ [ "nodes", @@ -2528,11 +2540,16 @@ const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { "SEARCH settled USING COVERING INDEX", "SEARCH settled_node USING COVERING INDEX", "subagents_settled_idx (thread_id=?)", + "SEARCH run USING COVERING INDEX orchestration_v2_projection_runs_run_status_idx", ], ], [ "provider_threads", - ["MULTI-INDEX OR", "provider_threads_session_idx (provider_session_id=?)"], + [ + "SEARCH orchestration_v2_projection_provider_threads USING INTEGER PRIMARY KEY", + "provider_threads_session_idx (provider_session_id=?)", + "SEARCH run USING COVERING INDEX orchestration_v2_projection_runs_run_status_idx", + ], ], ] as const) { const query = commandTrace.statements.find((statement) => diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e930fa67e3836..e10bc5340d646 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -2363,6 +2363,7 @@ export const layer: Layer.Layer = AND COALESCE(${row}.completion_delivery_state, '') IN ('acknowledged', 'delivered', 'disposed') AND NOT EXISTS ( SELECT 1 FROM orchestration_v2_projection_runs AS run + INDEXED BY orchestration_v2_projection_runs_run_status_idx WHERE run.run_id = ${row}.run_id AND run.status IN ('preparing', 'queued', 'starting', 'running', 'waiting') ) @@ -2383,6 +2384,7 @@ export const layer: Layer.Layer = const todoListOfSettledRun = (row: Statement.Fragment) => sql`( ${row}.kind = 'todo_list' AND ${row}.run_id IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM orchestration_v2_projection_runs AS todo_run + INDEXED BY orchestration_v2_projection_runs_run_status_idx WHERE todo_run.run_id = ${row}.run_id AND todo_run.status IN ('queued','preparing','starting','running','waiting') ))`; @@ -4388,37 +4390,50 @@ export const layer: Layer.Layer = ? sql` SELECT payload_json FROM orchestration_v2_projection_provider_threads - WHERE (thread_id = ${threadId} + WHERE ${ + filter?.omitSettledSubagentRecords === true + ? // A dispatcher's settled tasks' provider threads belong to the child threads; + // only a session this thread also uses is probed when it detaches. Most rows + // lack an owner or session, so ANALYZE rates those indexes as matching every + // row and SQLite scans for an OR of them; each union branch seeks instead. + sql`rowid IN ( + SELECT rowid FROM orchestration_v2_projection_provider_threads + WHERE thread_id = ${threadId} + UNION + SELECT rowid FROM orchestration_v2_projection_provider_threads + INDEXED BY orchestration_v2_projection_provider_threads_owner_idx + WHERE owner_node_id IN (${nodesOwningProviderThreads(threadId)}) + UNION + SELECT rowid FROM orchestration_v2_projection_provider_threads + WHERE provider_thread_id IN ( + SELECT provider_thread_id + FROM orchestration_v2_projection_subagents + WHERE rowid IN (${unsettledSubagentRowids(threadId)}) + AND provider_thread_id IS NOT NULL + ) + UNION + SELECT rowid FROM orchestration_v2_projection_provider_threads AS shared + INDEXED BY orchestration_v2_projection_provider_threads_session_idx + WHERE provider_session_id IN ( + SELECT provider_session_id + FROM orchestration_v2_projection_provider_session_bindings + WHERE thread_id = ${threadId} + ) + AND EXISTS ( + SELECT 1 FROM orchestration_v2_projection_subagents AS owner + WHERE owner.provider_thread_id = shared.provider_thread_id + AND owner.thread_id = ${threadId} + ) + )` + : sql`(thread_id = ${threadId} OR owner_node_id IN (${nodesOwningProviderThreads(threadId)}) - OR ${ - filter?.omitSettledSubagentRecords === true - ? // A dispatcher thread holds thousands of settled tasks. Their provider - // threads belong to the child threads; only a session this thread also - // uses is probed for background work when the thread detaches it. - sql`provider_thread_id IN ( - SELECT provider_thread_id - FROM orchestration_v2_projection_subagents - WHERE rowid IN (${unsettledSubagentRowids(threadId)}) - AND provider_thread_id IS NOT NULL - ) - OR (provider_session_id IN ( - SELECT provider_session_id - FROM orchestration_v2_projection_provider_session_bindings - WHERE thread_id = ${threadId} - ) - AND EXISTS ( - SELECT 1 FROM orchestration_v2_projection_subagents AS owner - WHERE owner.provider_thread_id = - orchestration_v2_projection_provider_threads.provider_thread_id - AND owner.thread_id = ${threadId} - ))` - : sql`provider_thread_id IN ( + OR provider_thread_id IN ( SELECT provider_thread_id FROM orchestration_v2_projection_subagents WHERE thread_id = ${threadId} AND provider_thread_id IS NOT NULL - )` - }) + ))` + } ${filter?.providerThreadIds === undefined ? sql`` : sql`AND provider_thread_id IN (SELECT value FROM json_each(${encodeIdList(filter.providerThreadIds)}))`} ORDER BY COALESCE(first_run_ordinal, 0), provider_thread_id ASC ` From 324ac49c5e6bf245778a2e578e075fbbc0525b65 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 13:02:39 -0800 Subject: [PATCH 114/162] fix(server): fresh-session scheduled runs release every idle Codex thread (#41055) --- .../ProviderSessionManager.test.ts | 89 ++++++++++++ .../ProviderSessionManager.ts | 136 +++++++++++------- 2 files changed, 177 insertions(+), 48 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index fcee608e3013f..4f67c42bb6d76 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -5572,6 +5572,95 @@ it.effect.each([ }), ); +it.effect( + "ProviderSessionManagerV2 unloads each idle native thread a fresh session replaced in the same app thread", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-fresh-rounds"); + const providerSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + yield* eventSink.write({ + events: [yield* makeThreadCreatedEvent({ idAllocator, threadId, now })], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + // Each scheduled "fresh session" round opens a new native thread in the same app thread. + for (const round of [1, 2]) { + const runId = idAllocator.derive.run({ threadId, ordinal: round }); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + nativeThreadId: `native-round-${round}`, + }); + yield* runtime.startTurn({ + appThread: (yield* projectionStore.getThreadProjection(threadId)).thread, + threadId, + runId, + runOrdinal: round, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId }), + providerThread, + message: { + createdBy: "user", + creationSource: "server", + messageId: yield* idAllocator.allocate.message({ threadId, ordinal: round }), + text: "Reply with OK.", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const subscription = yield* runtime.subscribeEvents!; + yield* Queue.offer((yield* Ref.get(state)).eventQueues.get(String(providerSessionId))!, { + type: "turn.terminal", + driver: CODEX_DRIVER, + providerThreadId: providerThread.id, + providerTurnId: idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: `native-turn-${round}`, + }), + runOrdinal: round, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* subscription.events.pipe(Stream.runHead); + } + + yield* TestClock.adjust("1 second"); + assert.sameMembers( + [...(yield* Ref.get(state)).unloadedNativeThreadIds], + ["native-round-1", "native-round-2"], + ); + }); + + yield* effect.pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 1000, + // Keep the shared app-server open, as other conversations do. + hasPendingBackgroundWork: Effect.succeed(true), + }), + ), + ); + }), +); it.effect( "ProviderSessionManagerV2 re-attaching a thread waits for its in-flight unload, then reloads it", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index dd573acb1fe17..463bcb5088b2f 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -342,10 +342,12 @@ interface LiveSessionEntry { readonly busyTurns: ReadonlySet; readonly idleFiber: Fiber.Fiber | null; readonly pinnedSinceMs: number | null; - readonly idleThreadUnloads: ReadonlyMap; + /** Keyed by native thread: a fresh session leaves the replaced one to unload on its own timer. */ + readonly idleThreadUnloads: ReadonlyMap; } interface IdleThreadUnload { + readonly threadId: ThreadId; readonly providerThread: OrchestrationV2ProviderThread; readonly generation: number; readonly fiber: Fiber.Fiber | null; @@ -417,6 +419,17 @@ function providerThreadRuntimeKey( : `${nativeThreadRef.driver}:${nativeThreadRef.nativeId}`; } +function isLoadKeyFor( + loadKey: string | undefined, + providerThread: Parameters[0], +): boolean { + return ( + loadKey === undefined || + (JSON.parse(loadKey) as { providerThread: string }).providerThread === + providerThreadRuntimeKey(providerThread) + ); +} + function providerThreadLoadKey(input: { readonly runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime; readonly providerThread: Parameters< @@ -1636,7 +1649,7 @@ export const layerWithOptions = ( )) || // Closing now would skip the archive of a child whose parent has not taken its result. Option.isSome( - yield* Effect.findFirst(entry.idleThreadUnloads.keys(), (threadId) => + yield* Effect.findFirst(entry.idleThreadUnloads.values(), ({ threadId }) => delegatedChildArchive(threadId).pipe( Effect.map((child) => child === "awaiting_delivery"), ), @@ -1679,10 +1692,11 @@ export const layerWithOptions = ( // Closing skips the threads' own idle unloads, so archive delivered children first. yield* Effect.forEach( entry.idleThreadUnloads, - ([threadId, pending]) => + ([providerThreadId, pending]) => unloadIdleThread({ providerSessionId: input.providerSessionId, - threadId, + threadId: pending.threadId, + providerThreadId, generation: pending.generation, archiveOnly: true, }), @@ -2049,18 +2063,18 @@ export const layerWithOptions = ( const updateIdleThreadUnload = ( providerSessionId: ProviderSessionId, - threadId: ThreadId, + providerThreadId: ProviderThreadId, update: (current: IdleThreadUnload | undefined) => IdleThreadUnload | undefined, ) => Ref.modify(sessions, (current) => { const key = sessionKey(providerSessionId); const entry = current.get(key); if (entry === undefined) return [undefined, current] as const; - const previous = entry.idleThreadUnloads.get(threadId); + const previous = entry.idleThreadUnloads.get(providerThreadId); const next = update(previous); const idleThreadUnloads = new Map(entry.idleThreadUnloads); - if (next === undefined) idleThreadUnloads.delete(threadId); - else idleThreadUnloads.set(threadId, next); + if (next === undefined) idleThreadUnloads.delete(providerThreadId); + else idleThreadUnloads.set(providerThreadId, next); const updated = new Map(current); updated.set(key, { ...entry, idleThreadUnloads }); return [previous, updated] as const; @@ -2088,8 +2102,9 @@ export const layerWithOptions = ( } const previous = yield* updateIdleThreadUnload( input.providerSessionId, - input.threadId, + input.providerThread.id, (current) => ({ + threadId: input.threadId, providerThread: input.providerThread, generation: (current?.generation ?? 0) + 1, fiber: null, @@ -2103,20 +2118,27 @@ export const layerWithOptions = ( function* (providerSessionId: ProviderSessionId, providerThreadId: ProviderThreadId) { const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId)); if (entry === undefined || hasBusyTurn(entry, providerThreadId)) return; - const tracked = Array.from(entry.idleThreadUnloads).find( - ([, pending]) => pending.providerThread.id === providerThreadId, - ); - if (tracked === undefined) return; - const [threadId, pending] = tracked; + const pending = entry.idleThreadUnloads.get(providerThreadId); + if (pending === undefined) return; const generation = pending.generation + 1; const fiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( - Effect.andThen(unloadIdleThread({ providerSessionId, threadId, generation })), + Effect.andThen( + unloadIdleThread({ + providerSessionId, + threadId: pending.threadId, + providerThreadId, + generation, + }), + ), Effect.forkIn(layerScope), ); - const previous = yield* updateIdleThreadUnload(providerSessionId, threadId, (current) => - current?.generation === pending.generation - ? { ...current, generation, fiber } - : current, + const previous = yield* updateIdleThreadUnload( + providerSessionId, + providerThreadId, + (current) => + current?.generation === pending.generation + ? { ...current, generation, fiber } + : current, ); yield* cancelIdleFiber( previous?.generation === pending.generation ? previous.fiber : fiber, @@ -2159,6 +2181,7 @@ export const layerWithOptions = ( function* (input: { readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; + readonly providerThreadId: ProviderThreadId; readonly generation: number; /** Session release unloads only the threads it would archive, and never waits. */ readonly archiveOnly?: boolean; @@ -2168,7 +2191,7 @@ export const layerWithOptions = ( Effect.gen(function* () { const key = sessionKey(input.providerSessionId); const entry = (yield* Ref.get(sessions)).get(key); - const pending = entry?.idleThreadUnloads.get(input.threadId); + const pending = entry?.idleThreadUnloads.get(input.providerThreadId); const unloadThread = entry?.exposedRuntime.unloadThread; if ( entry === undefined || @@ -2193,29 +2216,39 @@ export const layerWithOptions = ( if (child === "awaiting_delivery") return "deferred" as const; const archive = child === "ready"; if (input.archiveOnly === true && !archive) return "skipped" as const; - const unloading = yield* Ref.modify(sessions, (current) => { - const latest = current.get(key); - if ( - latest?.runtime !== entry.runtime || - latest.idleThreadUnloads.get(input.threadId)?.generation !== input.generation - ) { - return [false, current] as const; - } - const loadedProviderThreadKeyByThread = new Map( - latest.loadedProviderThreadKeyByThread, - ); - loadedProviderThreadKeyByThread.delete(input.threadId); - const idleThreadUnloads = new Map(latest.idleThreadUnloads); - idleThreadUnloads.delete(input.threadId); - const updated = new Map(current); - updated.set(key, { - ...latest, - loadedProviderThreadKeyByThread, - idleThreadUnloads, - }); - return [true, updated] as const; - }); - if (!unloading) return "skipped" as const; + // null when skipped, otherwise whether this native thread is the app thread's loaded one. + const unloadsLoadedThread = yield* Ref.modify( + sessions, + (current): readonly [boolean | null, Map] => { + const latest = current.get(key); + if ( + latest?.runtime !== entry.runtime || + latest.idleThreadUnloads.get(input.providerThreadId)?.generation !== + input.generation + ) { + return [null, current]; + } + const idleThreadUnloads = new Map(latest.idleThreadUnloads); + idleThreadUnloads.delete(input.providerThreadId); + // A native thread a fresh session replaced is not what the app thread has loaded. + const isCurrent = isLoadKeyFor( + latest.loadedProviderThreadKeyByThread.get(input.threadId), + pending.providerThread, + ); + const loadedProviderThreadKeyByThread = new Map( + latest.loadedProviderThreadKeyByThread, + ); + if (isCurrent) loadedProviderThreadKeyByThread.delete(input.threadId); + const updated = new Map(current); + updated.set(key, { + ...latest, + loadedProviderThreadKeyByThread, + idleThreadUnloads, + }); + return [isCurrent, updated]; + }, + ); + if (unloadsLoadedThread === null) return "skipped" as const; const unload = (archiveThread: boolean) => unloadThread({ providerThread: pending.providerThread, @@ -2236,7 +2269,7 @@ export const layerWithOptions = ( Effect.tap(() => Ref.update(sessions, (current) => { const latest = current.get(key); - if (latest?.runtime !== entry.runtime) return current; + if (latest?.runtime !== entry.runtime || !unloadsLoadedThread) return current; const linkedEnvironmentsByThread = new Map(latest.linkedEnvironmentsByThread); linkedEnvironmentsByThread.delete(input.threadId); return new Map(current).set(key, { ...latest, linkedEnvironmentsByThread }); @@ -3502,7 +3535,7 @@ export const layerWithOptions = ( return [ Option.none<{ readonly entry: LiveSessionEntry; - readonly idleUnloadFiber: Fiber.Fiber | null; + readonly idleUnloadFibers: ReadonlyArray>; }>(), current, ] as const; @@ -3524,7 +3557,12 @@ export const layerWithOptions = ( })() : entry.mcpCredentialIdByThread; const idleThreadUnloads = new Map(entry.idleThreadUnloads); - idleThreadUnloads.delete(input.threadId); + const idleUnloadFibers: Array> = []; + for (const [providerThreadId, pending] of entry.idleThreadUnloads) { + if (pending.threadId !== input.threadId) continue; + idleThreadUnloads.delete(providerThreadId); + if (pending.fiber !== null) idleUnloadFibers.push(pending.fiber); + } const updatedEntry = { ...entry, attachedThreadIds, @@ -3538,13 +3576,15 @@ export const layerWithOptions = ( return [ Option.some({ entry: updatedEntry, - idleUnloadFiber: entry.idleThreadUnloads.get(input.threadId)?.fiber ?? null, + idleUnloadFibers, }), updated, ] as const; }); if (Option.isSome(detachResult)) { - yield* cancelIdleFiber(detachResult.value.idleUnloadFiber); + yield* Effect.forEach(detachResult.value.idleUnloadFibers, cancelIdleFiber, { + discard: true, + }); } const detached = Option.map(detachResult, (result) => result.entry); // Plain detaches preserve credentials held by live shared providers across workspace handoffs. From fe9c98c98fce20af75b2e7745554922a2e3714b2 Mon Sep 17 00:00:00 2001 From: Gabriel De Andrade <30420087+gabrielelpidio@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:07:34 -0400 Subject: [PATCH 115/162] feat: agents can report T3 Code problems when you turn feedback on (#35871) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks --- .../settings/ThreadSettingsSections.tsx | 87 +- .../src/features/settings/settings-search.ts | 1 + .../features/threads/FeedbackRequestCard.tsx | 214 ++++ .../src/features/threads/ThreadFeed.tsx | 12 + apps/mobile/src/i18n/translations/de.json | 45 +- apps/mobile/src/i18n/translations/en.json | 45 +- apps/mobile/src/i18n/translations/es.json | 45 +- apps/mobile/src/i18n/translations/fr.json | 45 +- apps/mobile/src/i18n/translations/ja.json | 45 +- apps/mobile/src/i18n/translations/ko.json | 45 +- apps/mobile/src/i18n/translations/pt-BR.json | 45 +- apps/mobile/src/i18n/translations/ru.json | 45 +- apps/mobile/src/i18n/translations/sv.json | 45 +- apps/mobile/src/i18n/translations/zh.json | 45 +- apps/mobile/src/lib/threadActivity.ts | 14 + apps/server/src/auth/RpcAuthorization.test.ts | 7 + apps/server/src/auth/RpcAuthorization.ts | 1 + apps/server/src/binCli.ts | 2 + apps/server/src/cli/feedback.test.ts | 222 ++++ apps/server/src/cli/feedback.ts | 153 +++ apps/server/src/cli/thread.ts | 44 +- .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/feedback/FeedbackList.ts | 62 + apps/server/src/feedback/FeedbackReport.ts | 222 ++++ .../src/feedback/FeedbackService.test.ts | 1042 +++++++++++++++++ apps/server/src/feedback/FeedbackService.ts | 221 ++++ apps/server/src/feedback/FeedbackStore.ts | 371 ++++++ apps/server/src/feedback/FeedbackTrace.ts | 157 +++ .../server/src/feedback/scrubFeedback.test.ts | 225 ++++ apps/server/src/feedback/scrubFeedback.ts | 130 ++ .../src/guest/GuestShareService.test.ts | 4 +- apps/server/src/mcp/AcpMcpStdioBridge.test.ts | 27 + apps/server/src/mcp/AcpMcpStdioBridge.ts | 13 +- apps/server/src/mcp/McpHttpServer.test.ts | 133 +++ apps/server/src/mcp/McpHttpServer.ts | 44 +- apps/server/src/mcp/McpInvocationContext.ts | 10 + apps/server/src/mcp/OrchestratorMcpService.ts | 2 + apps/server/src/mcp/toolkits/core.test.ts | 6 +- .../mcp/toolkits/environment/handlers.test.ts | 12 + .../src/mcp/toolkits/feedback/handlers.ts | 47 + .../server/src/mcp/toolkits/feedback/tools.ts | 34 + .../src/observability/RpcInstrumentation.ts | 1 + .../Adapters/ClaudeAdapterV2.test.ts | 39 +- .../Adapters/ClaudeAdapterV2.ts | 5 + .../Adapters/CodexAdapterV2.ts | 9 +- .../src/orchestration-v2/Orchestrator.ts | 96 ++ .../ProviderRuntimeRecoveryService.test.ts | 217 ++-- .../ProviderRuntimeRecoveryService.ts | 2 + .../ProviderSessionManager.ts | 14 +- .../SteeringCompletion.integration.test.ts | 36 + .../src/orchestration-v2/runtimeLayer.ts | 6 + apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/108_AgentFeedback.ts | 15 + .../reconcileV2PreviewMigration.test.ts | 2 + .../src/provider/AgentContextBudget.test.ts | 6 + .../src/provider/CodexChatGptAuth.test.ts | 1 + .../provider/CodexDeveloperInstructions.ts | 2 + .../src/provider/agentContextBudget.json | 2 +- .../src/serverRuntimeStartup.autoPull.test.ts | 2 +- apps/server/src/serverSettings.test.ts | 16 + apps/server/src/serverSettings.ts | 86 +- apps/server/src/telemetry/AnalyticsService.ts | 8 +- .../telemetry/ProviderUsageAnalytics.test.ts | 5 +- apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 3 + .../components/chat/FeedbackRequestCard.tsx | 218 ++++ .../components/chat/TimelineV2EventRow.tsx | 10 + .../components/settings/LabsSettingsPanel.tsx | 81 +- .../settings/settingsSearch.test.ts | 1 + .../src/components/settings/settingsSearch.ts | 14 + .../useAvailableSettingsSearchItems.ts | 7 + apps/web/src/i18n/translations/de.json | 45 +- apps/web/src/i18n/translations/en.json | 45 +- apps/web/src/i18n/translations/es.json | 45 +- apps/web/src/i18n/translations/fr.json | 45 +- apps/web/src/i18n/translations/ja.json | 45 +- apps/web/src/i18n/translations/ko.json | 45 +- apps/web/src/i18n/translations/pt-BR.json | 45 +- apps/web/src/i18n/translations/ru.json | 45 +- apps/web/src/i18n/translations/sv.json | 45 +- apps/web/src/i18n/translations/zh.json | 45 +- apps/web/src/routes/_chat.settings.tsx | 31 +- apps/web/src/session-logic.ts | 2 + docs/internals/product-analytics.md | 20 +- docs/user/telemetry.md | 51 +- .../mcp-tool-use/cases/agent-feedback.ndjson | 18 + evals/mcp-tool-use/run.ts | 95 +- packages/client-runtime/package.json | 4 + .../src/feedbackRequest.test.ts | 79 ++ .../client-runtime/src/feedbackRequest.ts | 145 +++ .../src/state/commandPermissions.test.ts | 15 + packages/client-runtime/src/state/server.ts | 9 + packages/contracts/src/agentFeedback.ts | 84 ++ .../contracts/src/clientRpcPermissions.ts | 2 + packages/contracts/src/environment.ts | 2 + packages/contracts/src/index.ts | 1 + packages/contracts/src/orchestrationV2.ts | 38 + packages/contracts/src/rpc.ts | 8 + packages/contracts/src/settings.ts | 8 + packages/provider-acp/src/server/adapter.ts | 1 + .../src/server/ProviderAdapter.ts | 2 + .../src/server/runtimeInstructions.test.ts | 32 + .../src/server/runtimeInstructions.ts | 22 +- .../provider-cursor/src/server/adapter.ts | 3 +- .../provider-muse/src/server/adapter.test.ts | 15 +- packages/provider-muse/src/server/adapter.ts | 3 + .../provider-opencode/src/server/adapter.ts | 5 + .../src/server/v2/adapter.ts | 1 + 108 files changed, 5727 insertions(+), 297 deletions(-) create mode 100644 apps/mobile/src/features/threads/FeedbackRequestCard.tsx create mode 100644 apps/server/src/cli/feedback.test.ts create mode 100644 apps/server/src/cli/feedback.ts create mode 100644 apps/server/src/feedback/FeedbackList.ts create mode 100644 apps/server/src/feedback/FeedbackReport.ts create mode 100644 apps/server/src/feedback/FeedbackService.test.ts create mode 100644 apps/server/src/feedback/FeedbackService.ts create mode 100644 apps/server/src/feedback/FeedbackStore.ts create mode 100644 apps/server/src/feedback/FeedbackTrace.ts create mode 100644 apps/server/src/feedback/scrubFeedback.test.ts create mode 100644 apps/server/src/feedback/scrubFeedback.ts create mode 100644 apps/server/src/mcp/toolkits/feedback/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/feedback/tools.ts create mode 100644 apps/server/src/persistence/Migrations/108_AgentFeedback.ts create mode 100644 apps/web/src/components/chat/FeedbackRequestCard.tsx create mode 100644 evals/mcp-tool-use/cases/agent-feedback.ndjson create mode 100644 packages/client-runtime/src/feedbackRequest.test.ts create mode 100644 packages/client-runtime/src/feedbackRequest.ts create mode 100644 packages/contracts/src/agentFeedback.ts diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index 55c45eae31f01..f2ce0ca47cb75 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -1,6 +1,7 @@ -import { T, useGT } from "gt-react-native"; +import { T, useGT, msg, useMessages } from "gt-react-native"; import { Button } from "../../components/ui/Button"; import { + type AgentFeedbackMode, AuthSettingsWriteScope, isManagedSettingPath, type ServerSettingsPatch, @@ -21,6 +22,7 @@ import { useEnvironments } from "../../state/environments"; import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; import { serverEnvironment } from "../../state/server"; import { useAtomCommand } from "../../state/use-atom-command"; +import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow"; import { SettingsSection } from "./components/SettingsSection"; import { SettingsSwitchRow } from "./components/SettingsSwitchRow"; import { SettingsScreen } from "./components/SettingsScreen"; @@ -63,6 +65,7 @@ export function SettingsLabsRouteScreen() { "On a Mac, clone new worktrees from a checkout cached in the T3 home folder instead of writing every file. Uses Git’s normal checkout when it can’t. Turning it off deletes the cache.", )} /> + ); @@ -263,6 +266,88 @@ export function NewThreadSettingsSection() { type MachineBetaSetting = "linkedEnvironmentsEnabled" | "fastWorktreeCheckout"; +const AGENT_FEEDBACK_CHOICES: ReadonlyArray<{ + readonly mode: AgentFeedbackMode; + readonly label: string; + readonly description: string; +}> = [ + { mode: "off", label: msg("Off"), description: msg("Agents send no feedback to the T3 team.") }, + { + mode: "on-request", + label: msg("When I ask"), + description: msg("When you ask, you see a short report and send it if you approve."), + }, + { + mode: "auto", + label: msg("Automatic"), + description: msg("Agents also report T3 Code problems they hit on their own."), + }, +]; + +/** One choice list per connected machine that offers it, since each machine's own setting decides. */ +function AgentFeedbackSection() { + const gt = useGT(); + const m = useMessages(); + const { environments } = useEnvironments(); + const supported = environments.filter( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ); + const writable = useEnvironmentsWithScope(supported, AuthSettingsWriteScope); + const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { + label: "agentFeedback beta update", + reportFailure: true, + }); + if (supported.length === 0) return null; + return ( + + {supported.map((environment) => { + const policy = environment.serverConfig?.managedPolicy; + const managed = isManagedSettingPath(policy, "agentFeedback"); + const mode = environment.serverConfig?.settings.agentFeedback.mode; + return ( + + {AGENT_FEEDBACK_CHOICES.map((choice, index) => ( + 0} + disabled={managed || !writable.has(environment.environmentId)} + onPress={() => + void updateSettings({ + environmentId: environment.environmentId, + input: { patch: { agentFeedback: { mode: choice.mode } } }, + }) + } + /> + ))} + + ); + })} + + + Reports go to the T3 team. A report you ask for is shown to you first in a card, with an + outline of recent turns. Turn on Include the conversation there to add the messages of the + turns the report is about. + + + + ); +} + /** One switch per connected machine that offers the beta, since each machine's own setting decides. */ function MachineBetaSection({ title, diff --git a/apps/mobile/src/features/settings/settings-search.ts b/apps/mobile/src/features/settings/settings-search.ts index 9b8334641290d..6814475323db0 100644 --- a/apps/mobile/src/features/settings/settings-search.ts +++ b/apps/mobile/src/features/settings/settings-search.ts @@ -159,6 +159,7 @@ const SETTINGS_SEARCH_TERMS = { msg("link machine", { $context: "settings search keyword" }), msg("fast worktree checkout", { $context: "settings search keyword" }), msg("clone cache", { $context: "settings search keyword" }), + msg("agent feedback", { $context: "settings search keyword" }), ], SettingsEnvironmentMaintenance: [ msg("updates", { $context: "settings search keyword" }), diff --git a/apps/mobile/src/features/threads/FeedbackRequestCard.tsx b/apps/mobile/src/features/threads/FeedbackRequestCard.tsx new file mode 100644 index 0000000000000..5475e15d94e34 --- /dev/null +++ b/apps/mobile/src/features/threads/FeedbackRequestCard.tsx @@ -0,0 +1,214 @@ +import { T, msg, useMessages, useGT } from "gt-react-native"; +import { pipe } from "effect/Function"; +import { + feedbackCardPreview, + feedbackConversationHint, + feedbackPreviewFields, + feedbackRequestDisplay, + feedbackRequestFailureMessage, + type FeedbackRequestItem, + feedbackTraceLines, + feedbackTraceSummary, +} from "@t3tools/client-runtime/feedback-request"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { + AgentFeedbackPreview, + EnvironmentId, + OrchestrationV2ProjectedTurnItem, +} from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import { useRef, useState } from "react"; +import { Pressable, View, type ColorValue } from "react-native"; + +import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol"; +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { ThemedSwitch } from "../../components/ui/ThemedSwitch"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; + +const TITLE = msg("Feedback for the T3 team"); +const LOCK_SYMBOL: AppSymbolName = { ios: "lock", android: "lock" }; + +export function FeedbackRequestCard(props: { + readonly environmentId: EnvironmentId; + readonly projectedItem: OrchestrationV2ProjectedTurnItem; + readonly iconColor: ColorValue; +}) { + const m = useMessages(); + const { item, visibility } = props.projectedItem; + const [open, setOpen] = useState(false); + if (item.type !== "feedback_request") return null; + const display = feedbackRequestDisplay(item, visibility, m); + if (display.kind === "pending") { + return ; + } + const icon: AppSymbolName = + display.kind === "pending-elsewhere" + ? LOCK_SYMBOL + : display.outcome === "sent" + ? "checkmark" + : "minus"; + return ( + + setOpen((value) => !value)} + className="min-h-9 flex-row items-center gap-2" + > + + + {m(TITLE)} · {display.label} + + + {open ? : null} + + ); +} + +function PendingFeedbackRequest(props: { + readonly environmentId: EnvironmentId; + readonly item: FeedbackRequestItem; +}) { + const m = useMessages(); + const gt = useGT(); + const answer = useAtomCommand(serverEnvironment.answerFeedbackRequest, { + label: "answer feedback request", + reportFailure: false, + }); + const canAnswer = useAtomValue( + serverEnvironment.answerFeedbackRequest.permissionAtom(props.environmentId), + ); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(null); + const [includeConversation, setIncludeConversation] = useState(false); + // Two taps can land before a re-render; this guard is synchronous. + const inFlight = useRef(false); + + const send = async (reply: "send" | "decline") => { + if (inFlight.current) return; + inFlight.current = true; + setSubmitting(true); + setError(null); + const result = await answer({ + environmentId: props.environmentId, + input: { + threadId: props.item.threadId, + turnItemId: props.item.id, + answer: reply, + includeConversation, + }, + }).finally(() => { + inFlight.current = false; + setSubmitting(false); + }); + if (result._tag === "Success" || isAtomCommandInterrupted(result)) return; + pipe( + squashAtomCommandFailure(result), + (failure) => feedbackRequestFailureMessage(failure, m), + setError, + ); + }; + + return ( + + + + Send this report to the T3 team? + + + This is everything that leaves your machine. Nothing is sent unless you tap Send. + + + {props.item.conversationTrace !== undefined ? ( + + + + Include the conversation + + + {feedbackConversationHint(props.item.conversationTrace, m)} + + + + + ) : null} + + {error !== null ? ( + + {error} + + ) : !canAnswer ? ( + + Only someone who can run agents on this machine can send or decline it. + + ) : null} + + +
    + + ); +} + +function FeedbackPreview({ preview }: { readonly preview: AgentFeedbackPreview }) { + const m = useMessages(); + + return ( +
    +
    + {feedbackPreviewFields(preview, m).map((field) => ( +
    +
    {field.label}
    +
    {field.value}
    +
    + ))} +
    + {preview.trace !== null ? ( + + + + {feedbackTraceSummary(preview.trace, m)} + + +
      + {feedbackTraceLines(preview.trace, m).map((entry) => ( +
    1. + {entry.line} + {entry.text !== undefined ? ( +

      + {entry.text} +

      + ) : null} +
    2. + ))} +
    +
    +
    + ) : null} +
    + ); +} diff --git a/apps/web/src/components/chat/TimelineV2EventRow.tsx b/apps/web/src/components/chat/TimelineV2EventRow.tsx index 5ea743025444f..588bcaa3b4266 100644 --- a/apps/web/src/components/chat/TimelineV2EventRow.tsx +++ b/apps/web/src/components/chat/TimelineV2EventRow.tsx @@ -12,6 +12,7 @@ import { ChevronDownIcon } from "lucide-react"; import { cn } from "~/lib/utils"; import { Collapsible, CollapsibleTrigger, CollapsiblePanel } from "../ui/collapsible"; import { EnvironmentSubagentAvatar, SubagentElapsed, V2LifecycleRow } from "./V2LifecycleRow"; +import { FeedbackRequestCard } from "./FeedbackRequestCard"; import { LinkRequestCard } from "./LinkRequestCard"; import { SecretRequestCard } from "./SecretRequestCard"; import { TimelineRowCtx, type TimelineRow } from "./timelineRowContext"; @@ -32,6 +33,15 @@ export function V2EventTimelineRow({ row }: { row: Extract ); } + if (item.type === "feedback_request") { + return ( + + ); + } if (item.type === "link_request") { return ( + ); @@ -291,3 +299,74 @@ function FastWorktreeCheckoutRow() { /> ); } + +/** Shows only when every machine in scope honors it; older servers drop the setting. */ +const AGENT_FEEDBACK_MODES = AgentFeedbackMode.literals; +const AGENT_FEEDBACK_MODE_LABELS: Record = { + off: msg("Off"), + "on-request": msg("When I ask"), + auto: msg("Automatic"), +}; +const AGENT_FEEDBACK_MODE_DESCRIPTIONS: Record = { + off: msg("Agents send no feedback to the T3 team."), + "on-request": msg( + "When you ask, agents show you a short report about T3 Code and send it to the T3 team if you approve.", + ), + auto: msg( + "Agents also report T3 Code problems they hit on their own, such as a T3 tool that failed.", + ), +}; + +function AgentFeedbackRow() { + const searchableSetting = useSearchableSetting(); + const { scope, connectedEnvironments } = useSettingsScope(); + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + const gt = useGT(); + const m = useMessages(); + const mixed = useScopedSettingsMixed(["agentFeedback"]); + if ( + scope.kind === "project" || + scope.kind === "checkout" || + connectedEnvironments.length === 0 || + connectedEnvironments.some( + (environment) => environment.serverConfig?.environment.capabilities.agentFeedback !== true, + ) + ) + return null; + return ( + { + if (mode !== null) updateSettings({ agentFeedback: { mode } }); + }} + > + + + {(mode: AgentFeedbackMode | null) => + mode === null ? gt("Mixed") : m(AGENT_FEEDBACK_MODE_LABELS[mode]) + } + + + + {AGENT_FEEDBACK_MODES.map((mode) => ( + + {m(AGENT_FEEDBACK_MODE_LABELS[mode])} + + ))} + + + } + /> + ); +} diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index 4bc2c2a6317e5..3249b67624234 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -168,6 +168,7 @@ describe("searchSettings", () => { "auto-settle-merged-threads", "days-before-auto-settle", "linked-environments", + "agent-feedback", ]); expect(available.map((item) => item.id).filter((id) => gatedIds.has(id))).toEqual([]); }); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 4252fccc9c7d0..4f57b8d730842 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -72,6 +72,7 @@ export interface SettingsSearchItem { readonly managedTunnelOnly?: boolean; readonly peerLinksOnly?: boolean; readonly fastWorktreeCheckoutOnly?: boolean; + readonly agentFeedbackOnly?: boolean; readonly textGeneratorsOnly?: boolean; readonly secondary?: boolean; readonly requiresThreadAutoSettlement?: boolean; @@ -88,6 +89,7 @@ export interface SettingsSearchAvailability { readonly managedTunnelActive?: boolean; readonly hasPeerLinkHost?: boolean; readonly hasFastWorktreeCheckoutEnvironment?: boolean; + readonly hasAgentFeedbackEnvironment?: boolean; /** An environment without a provider allow-list, which hides text generators. */ readonly hasTextGeneratorsEnvironment?: boolean; readonly hasPrimaryEnvironment?: boolean; @@ -998,6 +1000,16 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/maintenance", searchTerms: [msg("logs traces processes resource history failures spans cpu memory")], }, + { + id: "agent-feedback", + title: msg("Agent feedback"), + to: "/settings/labs", + scope: "environment-defaults", + agentFeedbackOnly: true, + searchTerms: [ + msg("report bug problem t3 team send feedback agents tools automatic when i ask"), + ], + }, { id: "open-source-licenses", title: msg("Open source licenses"), @@ -1564,6 +1576,7 @@ export function getSettingsSearchTargetScope(targetId: string) { title: item.title, scope: item.scope ?? SETTINGS_CATEGORY_SCOPES[item.to], ...(item.requiresThreadAutoSettlement ? { requiresThreadAutoSettlement: true } : {}), + ...(item.agentFeedbackOnly ? { agentFeedbackOnly: true } : {}), } : null; } @@ -1656,6 +1669,7 @@ export function filterAvailableSettingsSearchItems( (!item.peerLinksOnly || availability.hasPeerLinkHost === true) && (!item.fastWorktreeCheckoutOnly || availability.hasFastWorktreeCheckoutEnvironment === true) && + (!item.agentFeedbackOnly || availability.hasAgentFeedbackEnvironment === true) && (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true) && (!item.secretProvidersOnly || availability.hasSecretProvidersEnvironment === true), ); diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts index beb5e3c85c52c..279dbd39d51e3 100644 --- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts +++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts @@ -45,6 +45,12 @@ export function useAvailableSettingsSearchItems() { environment.connection.phase === "connected" && environment.serverConfig?.environment.capabilities.fastWorktreeCheckout === true, ) === true; + const hasAgentFeedbackEnvironment = + environments.some( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ) === true; const hasTextGeneratorsEnvironment = environments.some( (environment) => @@ -83,6 +89,7 @@ export function useAvailableSettingsSearchItems() { managedTunnelActive, hasPeerLinkHost, hasFastWorktreeCheckoutEnvironment, + hasAgentFeedbackEnvironment, hasTextGeneratorsEnvironment, hasPrimaryEnvironment: primaryEnvironmentId !== null, hasSecretProvidersEnvironment, diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0b3ce24ca4fe3..16f3d83c8b2e6 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installiere {fj} 0.6 oder neuer von {fjUrl} und führe {fjLogin} aus, oder installiere {tea} 0.16 oder neuer von {teaUrl} und führe {teaLogin} für jeden Forgejo- oder Gitea-Server aus.", "d026a85e2e50e675": "Installiere die GitCafe CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", "22d3c0c48a34b5b3": "Installiere die TanStack Source CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", + "756c80ad262ef315": "Wartet im ursprünglichen Thread", + "d8df14f9905f38eb": "Gesendet", + "e7c59185f8ab3987": "Nicht gesendet", + "b54ddec9084fa955": "Ohne Senden geschlossen", + "fbaa7ab5da716e50": "Fehler", + "01bac997ea55272e": "Unverständlich", + "0f53bc8f74dfe56a": "Fehlende Funktion", + "055560f307e15e30": "Falsche Dokumentation", + "78344b60f407928e": "Sonstiges", + "f653846a95cd6e8f": "Art", + "f41ea186c275b56e": "Info", + "2f6e4f7cd364da73": "Erwartet", + "9d11c93d4035de3e": "Tatsächlich passiert", + "c87d0595693704f9": "Stattdessen getan", + "d7a4ea6ce5af44e0": "{speaker} · {count} Zeichen", + "f5114fb9c40fd929": "Du", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Runde {turn} · {what}", + "dfdaa6255a416140": "Übersicht über {turns, plural, one {{turns} letzte Runde} other {{turns} letzte Runden}}, {textTurns, plural, =0 {ohne Nachrichtentext} one {mit dem Nachrichtentext der letzten Runde} other {mit den Nachrichtentexten der letzten {textTurns} Runden}}{truncated, select, yes {, passend gekürzt} other {}}", + "afac52a5cc2dc801": "Deine Antwort konnte nicht gesendet werden. Versuche es erneut.", "79d776428f4d0650": "Die Datei konnte nicht geladen werden. Verbinde dich erneut und versuch es noch einmal.", "3ea34cbb1ca5ba9b": "Vorschau abgebrochen.", "7c0af279ecb3da3a": "Streamende Dateivorschauen sind in dieser Laufzeitumgebung nicht verfügbar.", @@ -3582,6 +3602,14 @@ "c53bc5a4b0314342": "Nächstes Medium", "2950b1424a3cddf5": "Verbinde dich erneut mit dieser Umgebung und öffne das Medium noch einmal.", "ef638bf1479a5461": "Die Umgebung hat eine ungültige Medien-URL zurückgegeben.", + "3ccfbf7e86868c35": "Feedback für das T3-Team", + "4e0710d19dfc2e7e": "Diesen Bericht an das T3-Team senden?", + "87d0ae0723ba75d1": "Das ist alles, was deinen Rechner verlässt. Erst wenn du auf Senden klickst, wird etwas gesendet.", + "bf19826f81484328": "Unterhaltung mitsenden", + "260c6b45f52d2f27": "Fügt den Text deiner Nachrichten und der Antworten des Agenten aus {textTurns, plural, one {der letzten Runde} other {den letzten {textTurns} Runden}} hinzu.", + "ddb7e6f8ce99e657": "Nur wer auf diesem Rechner Agenten ausführen kann, kann den Bericht senden oder ablehnen.", + "03c1eb603c112f47": "Nicht senden", + "653405e4ed498d9f": "Senden", "262955d6eb632f9b": "Die Zwischenablage-API ist beim Kopieren des Gast-Links nicht verfügbar.", "f1a4f2b04cdbb4ef": "Der Gast-Link konnte nicht in die Zwischenablage kopiert werden.", "cf3490a604e44d31": "Gastlink konnte nicht erstellt werden.", @@ -3602,7 +3630,6 @@ "abd89e9eefedf11b": "Fertig", "18d166056c1ab6ff": "Freigabe beenden", "7a2d510eac9e4587": "Gastlink abgelaufen", - "653405e4ed498d9f": "Senden", "21888e302219891d": "Vergrößerte Vorschau von {title}", "419719298a7acaea": "Verkleinern", "ed8d5db95359cff4": "Zoom zurücksetzen", @@ -5806,7 +5833,6 @@ "0061fff77e36bd4f": "Der Server ist nicht erreichbar.", "04dfdd46e3dd4a2e": "Etwas ist schiefgelaufen. Versuche es erneut.", "084bb2d8127a508d": "Gesendet", - "e7c59185f8ab3987": "Nicht gesendet", "77c01a15bd36d17c": "Dieser Link ist abgelaufen oder ungültig", "e0e736810f3cbef2": "Bitte den Besitzer um einen neuen Link. Jeder Link funktioniert in einem Browser.", "c3c53aa46f7330e5": "Dieser Link ist abgelaufen", @@ -8831,6 +8857,12 @@ "d3866ead082d14e5": "Tastenkürzel hinzufügen", "d4345c90894a3220": "keybindings.json öffnen", "e56a8d51219efaa0": "Keine Tastenkürzel entsprechen deiner Suche.", + "90a258fff61fd77e": "Aus", + "4060244a7079a0d2": "Wenn ich darum bitte", + "e88c9d8769544731": "Automatisch", + "f29d1dade4dde8aa": "Agenten senden kein Feedback an das T3-Team.", + "93c4c53562d30a98": "Wenn du darum bittest, zeigen Agenten dir einen kurzen Bericht über T3 Code und senden ihn mit deiner Zustimmung an das T3-Team.", + "cd9ee803e8727017": "Agenten melden auch selbstständig Probleme mit T3 Code, auf die sie stoßen, etwa ein fehlgeschlagenes T3-Tool.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Threads in der Seitenleiste in Projektordnern gruppieren. Angeheftete Threads bleiben oben, Zurückgestellte und Erledigte bleiben unter den Ordnern.", "e4e91d155cb6a9b4": "Schlichte Seitenleiste (nach Projekt gruppieren)", @@ -8844,6 +8876,9 @@ "298c7150a7621c80": "Simlock-Geräte-Hosts", "67937aa49179285e": "Auf einem Mac neue Worktrees aus einem im T3-Home-Ordner zwischengespeicherten Checkout klonen, statt jede Datei zu schreiben. Verwendet den normalen Git-Checkout, wenn das nicht geht. Beim Ausschalten wird der Cache gelöscht.", "f9904f78d3003f58": "Schneller Worktree-Checkout", + "9c2f647882522302": "Die ausgewählten Rechner verwenden unterschiedliche Modi für Agenten-Feedback.", + "31bbf7bf8c0a5279": "Agenten-Feedback", + "d52b3d6bf9f2a013": "Gemischt", "ec7623deed751c05": [ "Teile einen Thread mit einem Gast, der ihn live im Browser verfolgt und Nachrichten sendet, die du genehmigst. Erfordert T3 Connect: Melde dich an und verknüpfe diesen Rechner unter", " ", @@ -9158,7 +9193,6 @@ "0b4779a1825c85bc": "Der gemeinsame Name dieser Projektgruppe in der Seitenleiste und in Thread-Listen.", "f68cbda4df83d739": "Projektname auf Standard zurücksetzen", "56e37b85027e8431": "Projektsymbol", - "e88c9d8769544731": "Automatisch", "c99736317da5b1fa": "Projektsymbol auf Standard zurücksetzen", "6afaa3e3739dc570": "Projektsymbol auswählen", "51651ce45d481a20": "Datei für Projektsymbol auswählen", @@ -10133,7 +10167,6 @@ "16bdc70b858c223f": "Proaktive Panels auf Standard zurücksetzen", "c5424f09d77138ff": "Wann ein inaktiver Claude-Thread über 200.000 Tokens komprimiert wird: nach deiner Rückkehr, kurz bevor sein Prompt-Cache abläuft, oder nie. Jeder Claude-Anbieter kann das überschreiben.", "3e99c5c14f4939c8": "Inaktive Threads komprimieren auf Standard zurücksetzen", - "d52b3d6bf9f2a013": "Gemischt", "cd72fe451ba0d6aa": "Neue Projekte", "394c3bd0a1782c8e": "Leer lassen, um „~/“ zu verwenden, wenn sich der Dialog „Projekt hinzufügen“ öffnet.", "f9b912a818bd869d": "Basisverzeichnis für neue Projekte auf Standard zurücksetzen", @@ -11035,7 +11068,6 @@ "4a237f41ce592b7f": "Die Worktrees dieses Projekts behalten, bis du sie manuell löschst.", "00b8ffd8ea6e6a93": "Diese Regeln für dieses Projekt verwenden.", "72c279824d15a999": "Die Worktree-Bereinigungseinstellungen jedes Rechners verwenden.", - "90a258fff61fd77e": "Aus", "b5702d0b64866b08": "Benutzerdefiniert", "c009c901f3eefe78": "Worktrees gelöschter Threads löschen", "431c7cd6d50102b7": "Ungenutzte Worktrees entfernen, wenn aktive oder archivierte Threads gelöscht werden. Worktrees mit lokalen Änderungen bleiben erhalten.", @@ -11732,7 +11764,6 @@ "4c70e3e7b3e6c493": "Geheimnisse", "79b768229c9ef672": "Wartung", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Info", "af4b7734da1d5ce7": "Spracheingabe", "4ec62c39ca3192bf": "Versionskontrolle & Issues", "f2bf529f85e05494": "Freigabe & Zugriff", @@ -11858,6 +11889,7 @@ "901a823214edc8c4": "telemetrie analyse nutzungsdaten tracking rechtliches deaktivieren", "82136480255a5106": "OTel OTLP telemetrie export endpunkte logs traces metriken Grafana", "659d081051faf7ff": "logs traces prozesse ressourcenverlauf fehler spans cpu speicher", + "5eaeacfa9f82051a": "bericht fehler problem t3 team senden feedback agenten tools automatisch wenn ich darum bitte", "f537f91e1ee41d47": "tastenkürzel hotkeys befehle tastenzuweisungen json", "1ba01e7ceed64b95": "fenster aufnahme bildschirmfoto", "279b1cceb779ff38": "App-Text einbeziehen", @@ -12327,7 +12359,6 @@ "0bd41ff995d36a66": "Cache-Lesen", "3f0dfe0cb15a3272": "Cache-Schreiben", "1c9d860be42b1c02": "Ausgabe", - "78344b60f407928e": "Sonstiges", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Schnell", "66796576034c18ea": "Ultraschnell", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 9f369e8bd102e..c4534c680b95f 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Install {fj} 0.6 or later from {fjUrl} and run {fjLogin}, or install {tea} 0.16 or later from {teaUrl} and run {teaLogin} for each Forgejo or Gitea server.", "d026a85e2e50e675": "Install the GitCafe CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", "22d3c0c48a34b5b3": "Install the TanStack Source CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", + "756c80ad262ef315": "Waiting in the original thread", + "d8df14f9905f38eb": "Sent", + "e7c59185f8ab3987": "Not sent", + "b54ddec9084fa955": "Closed without sending", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Confusing", + "0f53bc8f74dfe56a": "Missing capability", + "055560f307e15e30": "Wrong docs", + "78344b60f407928e": "Other", + "f653846a95cd6e8f": "Kind", + "f41ea186c275b56e": "About", + "2f6e4f7cd364da73": "Expected", + "9d11c93d4035de3e": "Happened", + "c87d0595693704f9": "Did instead", + "d7a4ea6ce5af44e0": "{speaker} · {count} characters", + "f5114fb9c40fd929": "You", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Turn {turn} · {what}", + "dfdaa6255a416140": "Outline of {turns, plural, one {{turns} recent turn} other {{turns} recent turns}}, {textTurns, plural, =0 {no message text} one {message text of the last turn} other {message text of the last {textTurns} turns}}{truncated, select, yes {, shortened to fit} other {}}", + "afac52a5cc2dc801": "Could not send your answer. Try again.", "79d776428f4d0650": "The file could not be loaded. Reconnect and try again.", "3ea34cbb1ca5ba9b": "Preview cancelled.", "7c0af279ecb3da3a": "Streaming file previews are unavailable in this runtime.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Next media", "2950b1424a3cddf5": "Reconnect to this environment and open the media again.", "ef638bf1479a5461": "The environment returned an invalid media URL.", + "3ccfbf7e86868c35": "Feedback for the T3 team", + "4e0710d19dfc2e7e": "Send this report to the T3 team?", + "87d0ae0723ba75d1": "This is everything that leaves your machine. Nothing is sent unless you press Send.", + "bf19826f81484328": "Include the conversation", + "260c6b45f52d2f27": "Adds the text of your messages and the agent's replies in the last {textTurns, plural, one {turn} other {{textTurns} turns}}.", + "ddb7e6f8ce99e657": "Only someone who can run agents on this machine can send or decline it.", + "03c1eb603c112f47": "Don't send", + "653405e4ed498d9f": "Send", "262955d6eb632f9b": "Clipboard API is unavailable while copying guest link.", "f1a4f2b04cdbb4ef": "Failed to copy guest link to the clipboard.", "cf3490a604e44d31": "Could not create a guest link.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Done", "18d166056c1ab6ff": "Stop sharing", "7a2d510eac9e4587": "Guest link expired", - "653405e4ed498d9f": "Send", "21888e302219891d": "Expanded {title} preview", "419719298a7acaea": "Zoom out", "ed8d5db95359cff4": "Reset zoom", @@ -5807,7 +5834,6 @@ "0061fff77e36bd4f": "Could not reach the server.", "04dfdd46e3dd4a2e": "Something went wrong. Try again.", "084bb2d8127a508d": "Sent", - "e7c59185f8ab3987": "Not sent", "77c01a15bd36d17c": "This link has ended or is not valid", "e0e736810f3cbef2": "Ask the owner for a new link. Each link works in one browser.", "c3c53aa46f7330e5": "This link has ended", @@ -8839,6 +8865,12 @@ "d3866ead082d14e5": "Add keybinding", "d4345c90894a3220": "Open keybindings.json", "e56a8d51219efaa0": "No keybindings match your search.", + "90a258fff61fd77e": "Off", + "4060244a7079a0d2": "When I ask", + "e88c9d8769544731": "Automatic", + "f29d1dade4dde8aa": "Agents send no feedback to the T3 team.", + "93c4c53562d30a98": "When you ask, agents show you a short report about T3 Code and send it to the T3 team if you approve.", + "cd9ee803e8727017": "Agents also report T3 Code problems they hit on their own, such as a T3 tool that failed.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Group sidebar threads into project folders. Pinned threads stay on top, and Snoozed and Settled stay below the folders.", "e4e91d155cb6a9b4": "Boring sidebar (group by project)", @@ -8852,6 +8884,9 @@ "298c7150a7621c80": "Simlock device hosts", "67937aa49179285e": "On a Mac, clone new worktrees from a checkout cached in the T3 home folder instead of writing every file. Uses Git’s normal checkout when it can’t. Turning it off deletes the cache.", "f9904f78d3003f58": "Fast worktree checkout", + "9c2f647882522302": "The selected machines use different agent feedback modes.", + "31bbf7bf8c0a5279": "Agent feedback", + "d52b3d6bf9f2a013": "Mixed", "ec7623deed751c05": [ "Share a thread with a guest who watches it live in a browser and sends messages you approve. Needs T3 Connect: sign in and link this machine in", " ", @@ -9166,7 +9201,6 @@ "0b4779a1825c85bc": "The shared name for this project group in the sidebar and thread lists.", "f68cbda4df83d739": "Reset project name to default", "56e37b85027e8431": "Project icon", - "e88c9d8769544731": "Automatic", "c99736317da5b1fa": "Reset project icon to default", "6afaa3e3739dc570": "Choose a project icon", "51651ce45d481a20": "Choose a project icon file", @@ -10142,7 +10176,6 @@ "16bdc70b858c223f": "Reset proactive panels to default", "c5424f09d77138ff": "When to compact an idle Claude thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Each Claude provider can override this.", "3e99c5c14f4939c8": "Reset compact idle threads to default", - "d52b3d6bf9f2a013": "Mixed", "cd72fe451ba0d6aa": "New projects", "394c3bd0a1782c8e": "Leave empty to use \"~/\" when the Add Project browser opens.", "f9b912a818bd869d": "Reset add project base directory to default", @@ -11044,7 +11077,6 @@ "4a237f41ce592b7f": "Keep this project's worktrees until you delete them manually.", "00b8ffd8ea6e6a93": "Use these rules for this project.", "72c279824d15a999": "Use each machine's worktree cleanup settings.", - "90a258fff61fd77e": "Off", "b5702d0b64866b08": "Custom", "c009c901f3eefe78": "Delete worktrees with deleted threads", "431c7cd6d50102b7": "Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept.", @@ -11740,7 +11772,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "About", "af4b7734da1d5ce7": "Voice", "4ec62c39ca3192bf": "Source control & issues", "f2bf529f85e05494": "Sharing & access", @@ -11866,6 +11897,7 @@ "901a823214edc8c4": "telemetry analytics usage data tracking legal opt out", "82136480255a5106": "OTel OTLP telemetry export endpoints logs traces metrics Grafana", "659d081051faf7ff": "logs traces processes resource history failures spans cpu memory", + "5eaeacfa9f82051a": "report bug problem t3 team send feedback agents tools automatic when i ask", "f537f91e1ee41d47": "keyboard shortcuts hotkeys commands bindings json", "1ba01e7ceed64b95": "window capture screenshot", "279b1cceb779ff38": "Include app text", @@ -12335,7 +12367,6 @@ "0bd41ff995d36a66": "Cache read", "3f0dfe0cb15a3272": "Cache write", "1c9d860be42b1c02": "Output", - "78344b60f407928e": "Other", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Fast", "66796576034c18ea": "Ultrafast", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index bd4ec607512c9..ff83b277dc0d6 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Instala {fj} 0.6 o posterior desde {fjUrl} y ejecuta {fjLogin}, o instala {tea} 0.16 o posterior desde {teaUrl} y ejecuta {teaLogin} para cada servidor de Forgejo o Gitea.", "d026a85e2e50e675": "Instala la CLI de GitCafe con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", "22d3c0c48a34b5b3": "Instala la CLI de TanStack Source con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", + "756c80ad262ef315": "En espera en el hilo original", + "d8df14f9905f38eb": "Enviado", + "e7c59185f8ab3987": "No enviado", + "b54ddec9084fa955": "Cerrado sin enviar", + "fbaa7ab5da716e50": "Error", + "01bac997ea55272e": "Confuso", + "0f53bc8f74dfe56a": "Función ausente", + "055560f307e15e30": "Documentación incorrecta", + "78344b60f407928e": "Otros", + "f653846a95cd6e8f": "Tipo", + "f41ea186c275b56e": "Acerca de", + "2f6e4f7cd364da73": "Resultado esperado", + "9d11c93d4035de3e": "Lo que ocurrió", + "c87d0595693704f9": "Alternativa utilizada", + "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "f5114fb9c40fd929": "Tú", + "cd03eb1b84271c02": "Agente", + "bfe1a60f3f9c60fb": "Turno {turn} · {what}", + "dfdaa6255a416140": "Resumen de {turns, plural, one {{turns} turno reciente} other {{turns} turnos recientes}}, {textTurns, plural, =0 {sin texto de mensajes} one {con el texto de los mensajes del último turno} other {con el texto de los mensajes de los últimos {textTurns} turnos}}{truncated, select, yes {, acortado para ajustarse} other {}}", + "afac52a5cc2dc801": "No se pudo enviar tu respuesta. Inténtalo de nuevo.", "79d776428f4d0650": "No se pudo cargar el archivo. Vuelve a conectarte e inténtalo de nuevo.", "3ea34cbb1ca5ba9b": "Vista previa cancelada.", "7c0af279ecb3da3a": "Las vistas previas de archivos en streaming no están disponibles en este entorno de ejecución.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Elemento siguiente", "2950b1424a3cddf5": "Vuelve a conectarte a este entorno y abre de nuevo el contenido.", "ef638bf1479a5461": "El entorno devolvió una URL de contenido no válida.", + "3ccfbf7e86868c35": "Comentarios para el equipo de T3", + "4e0710d19dfc2e7e": "¿Enviar este informe al equipo de T3?", + "87d0ae0723ba75d1": "Esto es todo lo que sale de tu máquina. No se envía nada hasta que pulses Enviar.", + "bf19826f81484328": "Incluir la conversación", + "260c6b45f52d2f27": "Añade el texto de tus mensajes y de las respuestas del agente en {textTurns, plural, one {el último turno} other {los últimos {textTurns} turnos}}.", + "ddb7e6f8ce99e657": "Solo quien pueda ejecutar agentes en esta máquina puede enviarlo o rechazarlo.", + "03c1eb603c112f47": "No enviar", + "653405e4ed498d9f": "Enviar", "262955d6eb632f9b": "La API del portapapeles no está disponible al copiar el enlace de invitado.", "f1a4f2b04cdbb4ef": "No se pudo copiar el enlace de invitado al portapapeles.", "cf3490a604e44d31": "No se pudo crear un enlace de invitado.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Listo", "18d166056c1ab6ff": "Dejar de compartir", "7a2d510eac9e4587": "El enlace de invitado caducó", - "653405e4ed498d9f": "Enviar", "21888e302219891d": "Vista previa ampliada de {title}", "419719298a7acaea": "Alejar", "ed8d5db95359cff4": "Restablecer zoom", @@ -5805,7 +5832,6 @@ "0061fff77e36bd4f": "No se pudo acceder al servidor.", "04dfdd46e3dd4a2e": "Algo salió mal. Vuelve a intentarlo.", "084bb2d8127a508d": "Enviado", - "e7c59185f8ab3987": "No enviado", "77c01a15bd36d17c": "Este enlace terminó o no es válido", "e0e736810f3cbef2": "Pide un enlace nuevo al propietario. Cada enlace funciona en un navegador.", "c3c53aa46f7330e5": "Este enlace terminó", @@ -8829,6 +8855,12 @@ "d3866ead082d14e5": "Añadir atajo de teclado", "d4345c90894a3220": "Abrir keybindings.json", "e56a8d51219efaa0": "Ningún atajo de teclado coincide con tu búsqueda.", + "90a258fff61fd77e": "Desactivado", + "4060244a7079a0d2": "Cuando lo pida", + "e88c9d8769544731": "Automático", + "f29d1dade4dde8aa": "Los agentes no envían comentarios al equipo de T3.", + "93c4c53562d30a98": "Cuando lo pides, los agentes te muestran un breve informe sobre T3 Code y lo envían al equipo de T3 si lo apruebas.", + "cd9ee803e8727017": "Los agentes también informan por su cuenta de los problemas que encuentran en T3 Code, como una herramienta de T3 que falla.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Agrupa los hilos de la barra lateral en carpetas de proyecto. Los hilos fijados quedan arriba, y Pospuestos y Resueltos quedan debajo de las carpetas.", "e4e91d155cb6a9b4": "Barra lateral simple (agrupar por proyecto)", @@ -8842,6 +8874,9 @@ "298c7150a7621c80": "Hosts de dispositivos Simlock", "67937aa49179285e": "En un Mac, clona los nuevos worktrees desde un checkout en caché en la carpeta de inicio de T3 en lugar de escribir cada archivo. Usa el checkout normal de Git cuando no puede. Al desactivarlo se elimina la caché.", "f9904f78d3003f58": "Checkout rápido de worktrees", + "9c2f647882522302": "Las máquinas seleccionadas usan distintos modos de comentarios de agentes.", + "31bbf7bf8c0a5279": "Comentarios de agentes", + "d52b3d6bf9f2a013": "Mixto", "ec7623deed751c05": [ "Comparte un hilo con un invitado que lo ve en directo en un navegador y envía mensajes que tú apruebas. Requiere T3 Connect: inicia sesión y vincula esta máquina en", " ", @@ -9156,7 +9191,6 @@ "0b4779a1825c85bc": "El nombre compartido de este grupo de proyectos en la barra lateral y en las listas de hilos.", "f68cbda4df83d739": "Restablecer el nombre del proyecto al valor predeterminado", "56e37b85027e8431": "Icono del proyecto", - "e88c9d8769544731": "Automático", "c99736317da5b1fa": "Restablecer el icono del proyecto al valor predeterminado", "6afaa3e3739dc570": "Elige un icono para el proyecto", "51651ce45d481a20": "Elige un archivo de icono para el proyecto", @@ -10130,7 +10164,6 @@ "16bdc70b858c223f": "Restablecer los paneles proactivos al valor predeterminado", "c5424f09d77138ff": "Cuándo compactar un hilo inactivo de Claude con más de 200 000 tokens: al volver, justo antes de que caduque su caché de prompts o nunca. Cada proveedor de Claude puede anularlo.", "3e99c5c14f4939c8": "Restablecer la compactación de hilos inactivos al valor predeterminado", - "d52b3d6bf9f2a013": "Mixto", "cd72fe451ba0d6aa": "Proyectos nuevos", "394c3bd0a1782c8e": "Déjalo vacío para usar \"~/\" cuando se abra el explorador de Añadir proyecto.", "f9b912a818bd869d": "Restablecer el directorio base para añadir proyectos al valor predeterminado", @@ -11029,7 +11062,6 @@ "4a237f41ce592b7f": "Conserva los worktrees de este proyecto hasta que los elimines manualmente.", "00b8ffd8ea6e6a93": "Usa estas reglas para este proyecto.", "72c279824d15a999": "Usa los ajustes de limpieza de worktrees de cada máquina.", - "90a258fff61fd77e": "Desactivado", "b5702d0b64866b08": "Personalizado", "c009c901f3eefe78": "Eliminar los worktrees de hilos eliminados", "431c7cd6d50102b7": "Quita los worktrees sin uso cuando se eliminan hilos activos o archivados. Se conservan los worktrees con cambios locales.", @@ -11725,7 +11757,6 @@ "4c70e3e7b3e6c493": "Secretos", "79b768229c9ef672": "Mantenimiento", "54b188d65247e42f": "Experimentos", - "f41ea186c275b56e": "Acerca de", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versiones e issues", "f2bf529f85e05494": "Compartir y acceso", @@ -11851,6 +11882,7 @@ "901a823214edc8c4": "telemetría analítica datos de uso seguimiento legal desactivar", "82136480255a5106": "OTel OTLP telemetría exportar endpoints registros trazas métricas Grafana", "659d081051faf7ff": "registros trazas procesos historial de recursos fallos spans cpu memoria", + "5eaeacfa9f82051a": "informe error problema t3 equipo enviar comentarios agentes herramientas automático cuando lo pida", "f537f91e1ee41d47": "atajos de teclado teclas rápidas comandos combinaciones json", "1ba01e7ceed64b95": "ventana captura captura de pantalla", "279b1cceb779ff38": "Incluir el texto de la app", @@ -12320,7 +12352,6 @@ "0bd41ff995d36a66": "Lectura de caché", "3f0dfe0cb15a3272": "Escritura de caché", "1c9d860be42b1c02": "Salida", - "78344b60f407928e": "Otros", "684e516076de81fe": "Estándar", "3bbcc1b826fef537": "Rápida", "66796576034c18ea": "Ultrarrápida", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index bf19baf9814e0..939d36465b041 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installez {fj} 0.6 ou version ultérieure depuis {fjUrl} et exécutez {fjLogin}, ou installez {tea} 0.16 ou version ultérieure depuis {teaUrl} et exécutez {teaLogin} pour chaque serveur Forgejo ou Gitea.", "d026a85e2e50e675": "Installez la CLI GitCafe avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", "22d3c0c48a34b5b3": "Installez la CLI TanStack Source avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", + "756c80ad262ef315": "En attente dans le fil d'origine", + "d8df14f9905f38eb": "Envoyé", + "e7c59185f8ab3987": "Non envoyé", + "b54ddec9084fa955": "Fermé sans envoi", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Peu clair", + "0f53bc8f74dfe56a": "Fonctionnalité manquante", + "055560f307e15e30": "Documentation incorrecte", + "78344b60f407928e": "Autre", + "f653846a95cd6e8f": "Type", + "f41ea186c275b56e": "À propos", + "2f6e4f7cd364da73": "Résultat attendu", + "9d11c93d4035de3e": "Résultat obtenu", + "c87d0595693704f9": "Solution de repli", + "d7a4ea6ce5af44e0": "{speaker} · {count} caractères", + "f5114fb9c40fd929": "Vous", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Tour {turn} · {what}", + "dfdaa6255a416140": "Résumé de {turns, plural, one {{turns} tour récent} other {{turns} tours récents}}, {textTurns, plural, =0 {sans texte des messages} one {avec le texte des messages du dernier tour} other {avec le texte des messages des {textTurns} derniers tours}}{truncated, select, yes {, raccourci pour tenir dans la limite} other {}}", + "afac52a5cc2dc801": "Impossible d'envoyer votre réponse. Réessayez.", "79d776428f4d0650": "Le fichier n’a pas pu être chargé. Reconnectez-vous et réessayez.", "3ea34cbb1ca5ba9b": "Aperçu annulé.", "7c0af279ecb3da3a": "Les aperçus de fichiers en streaming ne sont pas disponibles dans cet environnement d’exécution.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Média suivant", "2950b1424a3cddf5": "Reconnectez-vous à cet environnement et ouvrez à nouveau le média.", "ef638bf1479a5461": "L’environnement a renvoyé une URL de média non valide.", + "3ccfbf7e86868c35": "Retour pour l'équipe T3", + "4e0710d19dfc2e7e": "Envoyer ce rapport à l'équipe T3 ?", + "87d0ae0723ba75d1": "Voici tout ce qui quitte votre machine. Rien n'est envoyé tant que vous ne cliquez pas sur Envoyer.", + "bf19826f81484328": "Inclure la conversation", + "260c6b45f52d2f27": "Ajoute le texte de vos messages et des réponses de l'agent dans {textTurns, plural, one {le dernier tour} other {les {textTurns} derniers tours}}.", + "ddb7e6f8ce99e657": "Seule une personne autorisée à exécuter des agents sur cette machine peut l'envoyer ou le refuser.", + "03c1eb603c112f47": "Ne pas envoyer", + "653405e4ed498d9f": "Envoyer", "262955d6eb632f9b": "L’API Presse-papiers n’est pas disponible pour copier le lien invité.", "f1a4f2b04cdbb4ef": "Impossible de copier le lien invité dans le presse-papiers.", "cf3490a604e44d31": "Impossible de créer un lien invité.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Terminé", "18d166056c1ab6ff": "Arrêter le partage", "7a2d510eac9e4587": "Lien invité expiré", - "653405e4ed498d9f": "Envoyer", "21888e302219891d": "Aperçu agrandi de {title}", "419719298a7acaea": "Zoom arrière", "ed8d5db95359cff4": "Réinitialiser le zoom", @@ -5806,7 +5833,6 @@ "0061fff77e36bd4f": "Impossible de joindre le serveur.", "04dfdd46e3dd4a2e": "Une erreur s’est produite. Réessayez.", "084bb2d8127a508d": "Envoyé", - "e7c59185f8ab3987": "Non envoyé", "77c01a15bd36d17c": "Ce lien a expiré ou n’est pas valide", "e0e736810f3cbef2": "Demandez un nouveau lien au propriétaire. Chaque lien fonctionne dans un seul navigateur.", "c3c53aa46f7330e5": "Ce lien a expiré", @@ -8830,6 +8856,12 @@ "d3866ead082d14e5": "Ajouter un raccourci clavier", "d4345c90894a3220": "Ouvrir keybindings.json", "e56a8d51219efaa0": "Aucun raccourci clavier ne correspond à votre recherche.", + "90a258fff61fd77e": "Désactivé", + "4060244a7079a0d2": "À ma demande", + "e88c9d8769544731": "Automatique", + "f29d1dade4dde8aa": "Les agents n'envoient aucun retour à l'équipe T3.", + "93c4c53562d30a98": "À votre demande, les agents vous présentent un court rapport sur T3 Code et l'envoient à l'équipe T3 si vous l'approuvez.", + "cd9ee803e8727017": "Les agents signalent aussi spontanément les problèmes qu'ils rencontrent dans T3 Code, comme un outil T3 qui échoue.", "45fa271ea0e1ac8e": "Bêta", "3a678332fc7142f7": "Regroupe les fils de la barre latérale dans des dossiers de projet. Les fils épinglés restent en haut, les fils reportés et clos restent sous les dossiers.", "e4e91d155cb6a9b4": "Barre latérale classique (regrouper par projet)", @@ -8843,6 +8875,9 @@ "298c7150a7621c80": "Hôtes d’appareils Simlock", "67937aa49179285e": "Sur Mac, clone les nouveaux worktrees depuis une copie en cache dans le dossier T3 home au lieu d’écrire chaque fichier. Utilise le checkout Git normal quand ce n’est pas possible. La désactivation supprime le cache.", "f9904f78d3003f58": "Checkout rapide des worktrees", + "9c2f647882522302": "Les machines sélectionnées utilisent des modes de retour des agents différents.", + "31bbf7bf8c0a5279": "Retours des agents", + "d52b3d6bf9f2a013": "Mixte", "ec7623deed751c05": [ "Partagez un fil avec un invité qui le suit en direct dans un navigateur et envoie des messages que vous approuvez. Nécessite T3 Connect : connectez-vous et associez cette machine dans", " ", @@ -9158,7 +9193,6 @@ "0b4779a1825c85bc": "Le nom commun de ce groupe de projets dans la barre latérale et les listes de fils.", "f68cbda4df83d739": "Réinitialiser le nom du projet à la valeur par défaut", "56e37b85027e8431": "Icône du projet", - "e88c9d8769544731": "Automatique", "c99736317da5b1fa": "Réinitialiser l’icône du projet à la valeur par défaut", "6afaa3e3739dc570": "Choisir une icône de projet", "51651ce45d481a20": "Choisir un fichier d’icône de projet", @@ -10132,7 +10166,6 @@ "16bdc70b858c223f": "Réinitialiser les panneaux proactifs à la valeur par défaut", "c5424f09d77138ff": "Quand compacter un fil Claude inactif de plus de 200 000 tokens : à votre retour, juste avant l’expiration de son cache de prompt, ou jamais. Chaque fournisseur Claude peut remplacer ce paramètre.", "3e99c5c14f4939c8": "Réinitialiser le compactage des fils inactifs à la valeur par défaut", - "d52b3d6bf9f2a013": "Mixte", "cd72fe451ba0d6aa": "Nouveaux projets", "394c3bd0a1782c8e": "Laissez vide pour utiliser « ~/ » à l’ouverture du navigateur Ajouter un projet.", "f9b912a818bd869d": "Réinitialiser le répertoire de base pour l’ajout de projets à la valeur par défaut", @@ -11034,7 +11067,6 @@ "4a237f41ce592b7f": "Conserve les worktrees de ce projet jusqu’à ce que vous les supprimiez manuellement.", "00b8ffd8ea6e6a93": "Utilise ces règles pour ce projet.", "72c279824d15a999": "Utilise les paramètres de nettoyage des worktrees de chaque machine.", - "90a258fff61fd77e": "Désactivé", "b5702d0b64866b08": "Personnalisé", "c009c901f3eefe78": "Supprimer les worktrees des fils supprimés", "431c7cd6d50102b7": "Supprime les worktrees inutilisés quand des fils actifs ou archivés sont supprimés. Les worktrees avec des modifications locales sont conservés.", @@ -11730,7 +11762,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "À propos", "af4b7734da1d5ce7": "Voix", "4ec62c39ca3192bf": "Versions et tickets", "f2bf529f85e05494": "Partage et accès", @@ -11856,6 +11887,7 @@ "901a823214edc8c4": "télémétrie analytique données d’utilisation suivi mentions légales refuser", "82136480255a5106": "OTel OTLP télémétrie export points de terminaison journaux traces métriques Grafana", "659d081051faf7ff": "journaux traces processus historique des ressources échecs spans cpu mémoire", + "5eaeacfa9f82051a": "rapport bug problème t3 équipe envoyer retour agents outils automatique à ma demande", "f537f91e1ee41d47": "raccourcis clavier touches commandes associations json", "1ba01e7ceed64b95": "fenêtre capture capture d’écran", "279b1cceb779ff38": "Inclure le texte de l’app", @@ -12325,7 +12357,6 @@ "0bd41ff995d36a66": "Lecture du cache", "3f0dfe0cb15a3272": "Écriture du cache", "1c9d860be42b1c02": "Sortie", - "78344b60f407928e": "Autre", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Rapide", "66796576034c18ea": "Ultrarapide", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index b7a4aa42d3750..51fe276edc353 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Forgejo または Gitea のサーバーごとに、{fjUrl} から {fj} 0.6 以降をインストールして {fjLogin} を実行するか、{teaUrl} から {tea} 0.16 以降をインストールして {teaLogin} を実行してください。", "d026a85e2e50e675": "{install} で GitCafe CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", "22d3c0c48a34b5b3": "{install} で TanStack Source CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", + "756c80ad262ef315": "元のスレッドで待機中", + "d8df14f9905f38eb": "送信済み", + "e7c59185f8ab3987": "未送信", + "b54ddec9084fa955": "送信せずに閉じました", + "fbaa7ab5da716e50": "不具合", + "01bac997ea55272e": "分かりにくい", + "0f53bc8f74dfe56a": "機能の不足", + "055560f307e15e30": "ドキュメントの誤り", + "78344b60f407928e": "その他", + "f653846a95cd6e8f": "種類", + "f41ea186c275b56e": "情報", + "2f6e4f7cd364da73": "期待した動作", + "9d11c93d4035de3e": "実際の動作", + "c87d0595693704f9": "代わりに行ったこと", + "d7a4ea6ce5af44e0": "{speaker} · {count} 文字", + "f5114fb9c40fd929": "あなた", + "cd03eb1b84271c02": "エージェント", + "bfe1a60f3f9c60fb": "ターン {turn} · {what}", + "dfdaa6255a416140": "{turns, plural, one {直近 {turns} ターン} other {直近 {turns} ターン}}の概要、{textTurns, plural, =0 {メッセージ本文なし} one {最後のターンのメッセージ本文} other {直近 {textTurns} ターンのメッセージ本文}}{truncated, select, yes {、収まる長さに短縮済み} other {}}", + "afac52a5cc2dc801": "回答を送信できませんでした。もう一度お試しください。", "79d776428f4d0650": "ファイルを読み込めませんでした。再接続してもう一度お試しください。", "3ea34cbb1ca5ba9b": "プレビューをキャンセルしました。", "7c0af279ecb3da3a": "このランタイムではファイルのストリーミングプレビューを利用できません。", @@ -3577,6 +3597,14 @@ "c53bc5a4b0314342": "次のメディア", "2950b1424a3cddf5": "この環境に再接続してから、もう一度メディアを開いてください。", "ef638bf1479a5461": "環境から無効なメディア URL が返されました。", + "3ccfbf7e86868c35": "T3 チームへのフィードバック", + "4e0710d19dfc2e7e": "このレポートを T3 チームに送信しますか?", + "87d0ae0723ba75d1": "この内容だけがこのマシンから送信されます。「送信」を押すまで何も送信されません。", + "bf19826f81484328": "会話を含める", + "260c6b45f52d2f27": "直近 {textTurns} ターンでのあなたのメッセージとエージェントの返信の本文を追加します。", + "ddb7e6f8ce99e657": "このマシンでエージェントを実行できる人だけが、送信または拒否できます。", + "03c1eb603c112f47": "送信しない", + "653405e4ed498d9f": "送信", "262955d6eb632f9b": "ゲストリンクをコピーする際にクリップボード API を利用できませんでした。", "f1a4f2b04cdbb4ef": "ゲストリンクをクリップボードにコピーできませんでした。", "cf3490a604e44d31": "ゲストリンクを作成できませんでした。", @@ -3597,7 +3625,6 @@ "abd89e9eefedf11b": "完了", "18d166056c1ab6ff": "共有を停止", "7a2d510eac9e4587": "ゲストリンクの期限が切れました", - "653405e4ed498d9f": "送信", "21888e302219891d": "拡大した {title} のプレビュー", "419719298a7acaea": "縮小", "ed8d5db95359cff4": "ズームをリセット", @@ -5788,7 +5815,6 @@ "0061fff77e36bd4f": "サーバーに接続できませんでした。", "04dfdd46e3dd4a2e": "問題が発生しました。もう一度お試しください。", "084bb2d8127a508d": "送信済み", - "e7c59185f8ab3987": "未送信", "77c01a15bd36d17c": "このリンクは終了したか、無効です", "e0e736810f3cbef2": "所有者に新しいリンクを依頼してください。各リンクは 1 つのブラウザーでのみ使用できます。", "c3c53aa46f7330e5": "このリンクは終了しました", @@ -8787,6 +8813,12 @@ "d3866ead082d14e5": "キーボードショートカットを追加", "d4345c90894a3220": "keybindings.json を開く", "e56a8d51219efaa0": "検索に一致するキーボードショートカットはありません。", + "90a258fff61fd77e": "オフ", + "4060244a7079a0d2": "依頼したとき", + "e88c9d8769544731": "自動", + "f29d1dade4dde8aa": "エージェントは T3 チームにフィードバックを送信しません。", + "93c4c53562d30a98": "依頼すると、エージェントが T3 Code についての短いレポートを表示し、承認した場合に T3 チームへ送信します。", + "cd9ee803e8727017": "エージェントが自ら遭遇した T3 Code の問題も報告します。たとえば、T3 ツールの失敗などです。", "45fa271ea0e1ac8e": "ベータ", "3a678332fc7142f7": "サイドバーのスレッドをプロジェクトフォルダーにまとめます。ピン留めしたスレッドは上部に残り、スヌーズ中と対応済みはフォルダーの下に表示されます。", "e4e91d155cb6a9b4": "シンプルなサイドバー(プロジェクトでグループ化)", @@ -8800,6 +8832,9 @@ "298c7150a7621c80": "Simlock デバイスホスト", "67937aa49179285e": "Mac では、すべてのファイルを書き込む代わりに、T3 ホームフォルダーにキャッシュしたチェックアウトから新しいワークツリーを複製します。できない場合は Git の通常のチェックアウトを使います。オフにするとキャッシュは削除されます。", "f9904f78d3003f58": "高速ワークツリーチェックアウト", + "9c2f647882522302": "選択したマシンでは、エージェントのフィードバックモードが異なります。", + "31bbf7bf8c0a5279": "エージェントのフィードバック", + "d52b3d6bf9f2a013": "混在", "ec7623deed751c05": [ "スレッドをゲストと共有します。ゲストはブラウザーでライブで閲覧し、あなたが承認したメッセージを送信できます。T3 Connect が必要です。サインインして、", " ", @@ -9115,7 +9150,6 @@ "0b4779a1825c85bc": "サイドバーとスレッド一覧に表示される、このプロジェクトグループの共通の名前です。", "f68cbda4df83d739": "プロジェクト名をデフォルトにリセット", "56e37b85027e8431": "プロジェクトのアイコン", - "e88c9d8769544731": "自動", "c99736317da5b1fa": "プロジェクトのアイコンをデフォルトにリセット", "6afaa3e3739dc570": "プロジェクトのアイコンを選択", "51651ce45d481a20": "プロジェクトのアイコンファイルを選択", @@ -10085,7 +10119,6 @@ "16bdc70b858c223f": "自動で開くパネルをデフォルトにリセット", "c5424f09d77138ff": "200,000 トークンを超えるアイドル状態の Claude スレッドを圧縮するタイミングです。戻ってきた後、プロンプトキャッシュの有効期限の直前、またはしない、から選びます。Claude プロバイダーごとに上書きできます。", "3e99c5c14f4939c8": "「アイドル状態のスレッドを圧縮」をデフォルトにリセット", - "d52b3d6bf9f2a013": "混在", "cd72fe451ba0d6aa": "新しいプロジェクト", "394c3bd0a1782c8e": "空のままにすると、「プロジェクトを追加」のブラウザーを開いたときに \"~/\" を使用します。", "f9b912a818bd869d": "プロジェクト追加のベースディレクトリをデフォルトにリセット", @@ -10985,7 +11018,6 @@ "4a237f41ce592b7f": "このプロジェクトのワークツリーは、手動で削除するまで保持します。", "00b8ffd8ea6e6a93": "このプロジェクトでこれらのルールを使用します。", "72c279824d15a999": "各マシンのワークツリーのクリーンアップ設定を使用します。", - "90a258fff61fd77e": "オフ", "b5702d0b64866b08": "カスタム", "c009c901f3eefe78": "削除したスレッドのワークツリーを削除", "431c7cd6d50102b7": "アクティブまたはアーカイブ済みのスレッドを削除したときに、使われていないワークツリーを削除します。ローカルの変更があるワークツリーは保持されます。", @@ -11681,7 +11713,6 @@ "4c70e3e7b3e6c493": "シークレット", "79b768229c9ef672": "メンテナンス", "54b188d65247e42f": "試験的機能", - "f41ea186c275b56e": "情報", "af4b7734da1d5ce7": "音声", "4ec62c39ca3192bf": "ソース管理と Issue", "f2bf529f85e05494": "共有とアクセス", @@ -11807,6 +11838,7 @@ "901a823214edc8c4": "テレメトリー 分析 使用状況データ トラッキング 法的事項 オプトアウト telemetry", "82136480255a5106": "OTel OTLP テレメトリー エクスポート エンドポイント ログ トレース メトリクス Grafana", "659d081051faf7ff": "ログ トレース プロセス リソース履歴 失敗 スパン CPU メモリ diagnostics", + "5eaeacfa9f82051a": "報告 不具合 問題 t3 チーム 送信 フィードバック エージェント ツール 自動 依頼したとき", "f537f91e1ee41d47": "キーボードショートカット ホットキー コマンド キーバインド JSON keybindings", "1ba01e7ceed64b95": "ウィンドウ キャプチャ スクリーンショット window capture", "279b1cceb779ff38": "アプリのテキストを含める", @@ -12276,7 +12308,6 @@ "0bd41ff995d36a66": "キャッシュの読み取り", "3f0dfe0cb15a3272": "キャッシュの書き込み", "1c9d860be42b1c02": "出力", - "78344b60f407928e": "その他", "684e516076de81fe": "標準", "3bbcc1b826fef537": "高速", "66796576034c18ea": "超高速", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 9a97fd72a773f..51c3b0a06a006 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "{fjUrl}에서 {fj} 0.6 이상을 설치하고 {fjLogin}을(를) 실행하거나, {teaUrl}에서 {tea} 0.16 이상을 설치하고 Forgejo 또는 Gitea 서버마다 {teaLogin}을(를) 실행하세요.", "d026a85e2e50e675": "{install}로 GitCafe CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", "22d3c0c48a34b5b3": "{install}로 TanStack Source CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", + "756c80ad262ef315": "원래 스레드에서 대기 중", + "d8df14f9905f38eb": "보냄", + "e7c59185f8ab3987": "보내지 않음", + "b54ddec9084fa955": "보내지 않고 닫음", + "fbaa7ab5da716e50": "버그", + "01bac997ea55272e": "이해하기 어려움", + "0f53bc8f74dfe56a": "기능 부족", + "055560f307e15e30": "잘못된 문서", + "78344b60f407928e": "기타", + "f653846a95cd6e8f": "유형", + "f41ea186c275b56e": "정보", + "2f6e4f7cd364da73": "기대한 동작", + "9d11c93d4035de3e": "실제 동작", + "c87d0595693704f9": "대신 한 일", + "d7a4ea6ce5af44e0": "{speaker} · {count}자", + "f5114fb9c40fd929": "나", + "cd03eb1b84271c02": "에이전트", + "bfe1a60f3f9c60fb": "턴 {turn} · {what}", + "dfdaa6255a416140": "{turns, plural, one {최근 {turns}개 턴} other {최근 {turns}개 턴}}의 개요, {textTurns, plural, =0 {메시지 본문 없음} one {마지막 턴의 메시지 본문} other {최근 {textTurns}개 턴의 메시지 본문}}{truncated, select, yes {, 길이에 맞게 줄임} other {}}", + "afac52a5cc2dc801": "답변을 보내지 못했습니다. 다시 시도하세요.", "79d776428f4d0650": "파일을 불러올 수 없습니다. 다시 연결한 뒤 시도하세요.", "3ea34cbb1ca5ba9b": "미리 보기가 취소되었습니다.", "7c0af279ecb3da3a": "이 런타임에서는 스트리밍 파일 미리 보기를 사용할 수 없습니다.", @@ -3577,6 +3597,14 @@ "c53bc5a4b0314342": "다음 미디어", "2950b1424a3cddf5": "이 환경에 다시 연결한 후 미디어를 다시 여세요.", "ef638bf1479a5461": "환경에서 잘못된 미디어 URL을 반환했습니다.", + "3ccfbf7e86868c35": "T3 팀에 보내는 피드백", + "4e0710d19dfc2e7e": "이 보고서를 T3 팀에 보낼까요?", + "87d0ae0723ba75d1": "이 내용만 이 컴퓨터에서 전송됩니다. 보내기를 누르기 전에는 아무것도 전송되지 않습니다.", + "bf19826f81484328": "대화 포함", + "260c6b45f52d2f27": "최근 {textTurns}개 턴에서 내 메시지와 에이전트 답변의 본문을 추가합니다.", + "ddb7e6f8ce99e657": "이 컴퓨터에서 에이전트를 실행할 수 있는 사람만 보고서를 보내거나 거절할 수 있습니다.", + "03c1eb603c112f47": "보내지 않기", + "653405e4ed498d9f": "보내기", "262955d6eb632f9b": "게스트 링크를 복사하는 중 클립보드 API를 사용할 수 없습니다.", "f1a4f2b04cdbb4ef": "게스트 링크를 클립보드에 복사하지 못했습니다.", "cf3490a604e44d31": "게스트 링크를 만들 수 없습니다.", @@ -3597,7 +3625,6 @@ "abd89e9eefedf11b": "완료", "18d166056c1ab6ff": "공유 중지", "7a2d510eac9e4587": "게스트 링크 만료됨", - "653405e4ed498d9f": "보내기", "21888e302219891d": "확대된 {title} 미리 보기", "419719298a7acaea": "축소", "ed8d5db95359cff4": "확대/축소 초기화", @@ -5786,7 +5813,6 @@ "0061fff77e36bd4f": "서버에 연결할 수 없습니다.", "04dfdd46e3dd4a2e": "문제가 발생했습니다. 다시 시도하세요.", "084bb2d8127a508d": "보냄", - "e7c59185f8ab3987": "보내지 않음", "77c01a15bd36d17c": "이 링크는 종료되었거나 유효하지 않습니다", "e0e736810f3cbef2": "소유자에게 새 링크를 요청하세요. 각 링크는 한 브라우저에서만 작동합니다.", "c3c53aa46f7330e5": "이 링크는 종료되었습니다", @@ -8790,6 +8816,12 @@ "d3866ead082d14e5": "단축키 추가", "d4345c90894a3220": "keybindings.json 열기", "e56a8d51219efaa0": "검색과 일치하는 단축키가 없습니다.", + "90a258fff61fd77e": "끔", + "4060244a7079a0d2": "내가 요청할 때", + "e88c9d8769544731": "자동", + "f29d1dade4dde8aa": "에이전트가 T3 팀에 피드백을 보내지 않습니다.", + "93c4c53562d30a98": "요청하면 에이전트가 T3 Code에 관한 짧은 보고서를 보여주고, 승인하면 T3 팀에 보냅니다.", + "cd9ee803e8727017": "에이전트가 직접 겪은 T3 Code 문제도 보고합니다. 예를 들어 T3 도구가 실패한 경우입니다.", "45fa271ea0e1ac8e": "베타", "3a678332fc7142f7": "사이드바 스레드를 프로젝트 폴더로 묶습니다. 고정된 스레드는 맨 위에, 다시 알림과 정리됨은 폴더 아래에 유지됩니다.", "e4e91d155cb6a9b4": "단순 사이드바(프로젝트별 그룹화)", @@ -8803,6 +8835,9 @@ "298c7150a7621c80": "Simlock 기기 호스트", "67937aa49179285e": "Mac에서 모든 파일을 쓰는 대신 T3 홈 폴더에 캐시된 체크아웃에서 새 워크트리를 복제합니다. 불가능하면 Git의 일반 체크아웃을 사용합니다. 끄면 캐시가 삭제됩니다.", "f9904f78d3003f58": "빠른 워크트리 체크아웃", + "9c2f647882522302": "선택한 컴퓨터의 에이전트 피드백 모드가 서로 다릅니다.", + "31bbf7bf8c0a5279": "에이전트 피드백", + "d52b3d6bf9f2a013": "혼합", "ec7623deed751c05": [ "브라우저에서 실시간으로 지켜보고 승인한 메시지를 보낼 수 있는 게스트와 스레드를 공유합니다. T3 Connect가 필요합니다. 로그인한 뒤", " ", @@ -9117,7 +9152,6 @@ "0b4779a1825c85bc": "사이드바와 스레드 목록에 표시되는 이 프로젝트 그룹의 공유 이름입니다.", "f68cbda4df83d739": "프로젝트 이름 기본값으로 재설정", "56e37b85027e8431": "프로젝트 아이콘", - "e88c9d8769544731": "자동", "c99736317da5b1fa": "프로젝트 아이콘 기본값으로 재설정", "6afaa3e3739dc570": "프로젝트 아이콘 선택", "51651ce45d481a20": "프로젝트 아이콘 파일 선택", @@ -10087,7 +10121,6 @@ "16bdc70b858c223f": "패널 미리 열기 기본값으로 재설정", "c5424f09d77138ff": "200,000 토큰이 넘는 유휴 Claude 스레드를 압축할 시점입니다. 돌아온 뒤, 프롬프트 캐시가 만료되기 직전, 또는 압축 안 함 중에서 선택합니다. 각 Claude 제공자에서 재정의할 수 있습니다.", "3e99c5c14f4939c8": "유휴 스레드 압축 기본값으로 재설정", - "d52b3d6bf9f2a013": "혼합", "cd72fe451ba0d6aa": "새 프로젝트", "394c3bd0a1782c8e": "프로젝트 추가 탐색기가 열릴 때 \"~/\"를 사용하려면 비워 두세요.", "f9b912a818bd869d": "프로젝트 추가 기본 디렉터리 기본값으로 재설정", @@ -10985,7 +11018,6 @@ "4a237f41ce592b7f": "직접 삭제할 때까지 이 프로젝트의 워크트리를 유지합니다.", "00b8ffd8ea6e6a93": "이 프로젝트에 이 규칙을 사용합니다.", "72c279824d15a999": "각 머신의 워크트리 정리 설정을 사용합니다.", - "90a258fff61fd77e": "끔", "b5702d0b64866b08": "사용자 지정", "c009c901f3eefe78": "삭제된 스레드의 워크트리 삭제", "431c7cd6d50102b7": "활성 또는 보관된 스레드가 삭제되면 사용하지 않는 워크트리를 제거합니다. 로컬 변경 사항이 있는 워크트리는 유지됩니다.", @@ -11677,7 +11709,6 @@ "4c70e3e7b3e6c493": "시크릿", "79b768229c9ef672": "유지 관리", "54b188d65247e42f": "실험 기능", - "f41ea186c275b56e": "정보", "af4b7734da1d5ce7": "음성", "4ec62c39ca3192bf": "소스 제어 및 이슈", "f2bf529f85e05494": "공유 및 액세스", @@ -11803,6 +11834,7 @@ "901a823214edc8c4": "원격 분석 분석 사용 데이터 추적 법적 옵트아웃", "82136480255a5106": "OTel OTLP 원격 분석 내보내기 엔드포인트 로그 추적 메트릭 Grafana", "659d081051faf7ff": "로그 추적 프로세스 리소스 기록 실패 스팬 cpu 메모리", + "5eaeacfa9f82051a": "보고 버그 문제 t3 팀 보내기 피드백 에이전트 도구 자동 내가 요청할 때", "f537f91e1ee41d47": "키보드 단축키 핫키 명령 바인딩 json", "1ba01e7ceed64b95": "창 캡처 스크린샷", "279b1cceb779ff38": "앱 텍스트 포함", @@ -12272,7 +12304,6 @@ "0bd41ff995d36a66": "캐시 읽기", "3f0dfe0cb15a3272": "캐시 쓰기", "1c9d860be42b1c02": "출력", - "78344b60f407928e": "기타", "684e516076de81fe": "표준", "3bbcc1b826fef537": "빠름", "66796576034c18ea": "초고속", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b3b227205e4b..d17ff0e321ccf 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Instale o {fj} 0.6 ou posterior em {fjUrl} e execute {fjLogin}, ou instale o {tea} 0.16 ou posterior em {teaUrl} e execute {teaLogin} para cada servidor Forgejo ou Gitea.", "d026a85e2e50e675": "Instale a CLI do GitCafe com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", "22d3c0c48a34b5b3": "Instale a CLI do TanStack Source com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", + "756c80ad262ef315": "Aguardando na thread original", + "d8df14f9905f38eb": "Enviado", + "e7c59185f8ab3987": "Não enviada", + "b54ddec9084fa955": "Fechado sem enviar", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Confuso", + "0f53bc8f74dfe56a": "Funcionalidade ausente", + "055560f307e15e30": "Documentação incorreta", + "78344b60f407928e": "Outros", + "f653846a95cd6e8f": "Tipo", + "f41ea186c275b56e": "Sobre", + "2f6e4f7cd364da73": "Resultado esperado", + "9d11c93d4035de3e": "O que aconteceu", + "c87d0595693704f9": "Alternativa utilizada", + "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "f5114fb9c40fd929": "Você", + "cd03eb1b84271c02": "Agente", + "bfe1a60f3f9c60fb": "Turno {turn} · {what}", + "dfdaa6255a416140": "Resumo de {turns, plural, one {{turns} turno recente} other {{turns} turnos recentes}}, {textTurns, plural, =0 {sem texto das mensagens} one {com o texto das mensagens do último turno} other {com o texto das mensagens dos últimos {textTurns} turnos}}{truncated, select, yes {, encurtado para caber} other {}}", + "afac52a5cc2dc801": "Não foi possível enviar sua resposta. Tente novamente.", "79d776428f4d0650": "Não foi possível carregar o arquivo. Reconecte e tente novamente.", "3ea34cbb1ca5ba9b": "Pré-visualização cancelada.", "7c0af279ecb3da3a": "As pré-visualizações de arquivos por streaming não estão disponíveis neste runtime.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Próxima mídia", "2950b1424a3cddf5": "Reconecte-se a este ambiente e abra a mídia novamente.", "ef638bf1479a5461": "O ambiente retornou uma URL de mídia inválida.", + "3ccfbf7e86868c35": "Feedback para a equipe do T3", + "4e0710d19dfc2e7e": "Enviar este relatório para a equipe do T3?", + "87d0ae0723ba75d1": "Isto é tudo o que sai da sua máquina. Nada é enviado até você clicar em Enviar.", + "bf19826f81484328": "Incluir a conversa", + "260c6b45f52d2f27": "Adiciona o texto das suas mensagens e das respostas do agente {textTurns, plural, one {no último turno} other {nos últimos {textTurns} turnos}}.", + "ddb7e6f8ce99e657": "Somente quem pode executar agentes nesta máquina pode enviar ou recusar o relatório.", + "03c1eb603c112f47": "Não enviar", + "653405e4ed498d9f": "Enviar", "262955d6eb632f9b": "A API da área de transferência não está disponível ao copiar o link de convidado.", "f1a4f2b04cdbb4ef": "Falha ao copiar o link de convidado para a área de transferência.", "cf3490a604e44d31": "Não foi possível criar um link de convidado.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Concluído", "18d166056c1ab6ff": "Parar de compartilhar", "7a2d510eac9e4587": "Link de convidado expirado", - "653405e4ed498d9f": "Enviar", "21888e302219891d": "Pré-visualização expandida de {title}", "419719298a7acaea": "Diminuir zoom", "ed8d5db95359cff4": "Redefinir zoom", @@ -5805,7 +5832,6 @@ "0061fff77e36bd4f": "Não foi possível acessar o servidor.", "04dfdd46e3dd4a2e": "Algo deu errado. Tente novamente.", "084bb2d8127a508d": "Enviada", - "e7c59185f8ab3987": "Não enviada", "77c01a15bd36d17c": "Este link expirou ou não é válido", "e0e736810f3cbef2": "Peça um novo link ao proprietário. Cada link funciona em um navegador.", "c3c53aa46f7330e5": "Este link expirou", @@ -8829,6 +8855,12 @@ "d3866ead082d14e5": "Adicionar atalho de teclado", "d4345c90894a3220": "Abrir keybindings.json", "e56a8d51219efaa0": "Nenhum atalho de teclado corresponde à sua pesquisa.", + "90a258fff61fd77e": "Desativado", + "4060244a7079a0d2": "Quando eu pedir", + "e88c9d8769544731": "Automático", + "f29d1dade4dde8aa": "Os agentes não enviam feedback para a equipe do T3.", + "93c4c53562d30a98": "Quando você pede, os agentes mostram um breve relatório sobre o T3 Code e o enviam para a equipe do T3 se você aprovar.", + "cd9ee803e8727017": "Os agentes também relatam por conta própria os problemas que encontram no T3 Code, como uma ferramenta do T3 que falhou.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Agrupa as threads da barra lateral em pastas de projeto. As threads fixadas ficam no topo, e Adiadas e Concluídas ficam abaixo das pastas.", "e4e91d155cb6a9b4": "Barra lateral sem graça (agrupar por projeto)", @@ -8842,6 +8874,9 @@ "298c7150a7621c80": "Hosts de dispositivos Simlock", "67937aa49179285e": "No Mac, clona novos worktrees a partir de um checkout em cache na pasta T3 home em vez de gravar cada arquivo. Usa o checkout normal do Git quando não consegue. Desativar exclui o cache.", "f9904f78d3003f58": "Checkout rápido de worktree", + "9c2f647882522302": "As máquinas selecionadas usam modos diferentes de feedback dos agentes.", + "31bbf7bf8c0a5279": "Feedback dos agentes", + "d52b3d6bf9f2a013": "Misto", "ec7623deed751c05": [ "Compartilhe uma thread com um convidado que a acompanha ao vivo no navegador e envia mensagens que você aprova. Requer T3 Connect: entre e vincule esta máquina em", " ", @@ -9158,7 +9193,6 @@ "0b4779a1825c85bc": "O nome compartilhado deste grupo de projetos na barra lateral e nas listas de threads.", "f68cbda4df83d739": "Redefinir o nome do projeto para o padrão", "56e37b85027e8431": "Ícone do projeto", - "e88c9d8769544731": "Automático", "c99736317da5b1fa": "Redefinir o ícone do projeto para o padrão", "6afaa3e3739dc570": "Escolha um ícone para o projeto", "51651ce45d481a20": "Escolha um arquivo de ícone para o projeto", @@ -10132,7 +10166,6 @@ "16bdc70b858c223f": "Redefinir os painéis proativos para o padrão", "c5424f09d77138ff": "Quando compactar uma thread do Claude ociosa com mais de 200.000 tokens: depois que você voltar, logo antes de o cache do prompt expirar ou nunca. Cada provedor Claude pode substituir isso.", "3e99c5c14f4939c8": "Redefinir a compactação de threads ociosas para o padrão", - "d52b3d6bf9f2a013": "Misto", "cd72fe451ba0d6aa": "Novos projetos", "394c3bd0a1782c8e": "Deixe vazio para usar \"~/\" quando o navegador de Adicionar projeto abrir.", "f9b912a818bd869d": "Redefinir o diretório base para adicionar projetos para o padrão", @@ -11034,7 +11067,6 @@ "4a237f41ce592b7f": "Mantém os worktrees deste projeto até você excluí-los manualmente.", "00b8ffd8ea6e6a93": "Usa estas regras neste projeto.", "72c279824d15a999": "Usa as configurações de limpeza de worktrees de cada máquina.", - "90a258fff61fd77e": "Desativado", "b5702d0b64866b08": "Personalizado", "c009c901f3eefe78": "Excluir worktrees de threads excluídas", "431c7cd6d50102b7": "Remove worktrees sem uso quando threads ativas ou arquivadas são excluídas. Worktrees com alterações locais são mantidos.", @@ -11730,7 +11762,6 @@ "4c70e3e7b3e6c493": "Segredos", "79b768229c9ef672": "Manutenção", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Sobre", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versões e issues", "f2bf529f85e05494": "Compartilhamento", @@ -11856,6 +11887,7 @@ "901a823214edc8c4": "telemetria analytics dados de uso rastreamento legal desativar", "82136480255a5106": "OTel OTLP telemetria exportar endpoints logs traces métricas Grafana", "659d081051faf7ff": "logs traces processos histórico de recursos falhas spans cpu memória", + "5eaeacfa9f82051a": "relatório bug problema t3 equipe enviar feedback agentes ferramentas automático quando eu pedir", "f537f91e1ee41d47": "atalhos de teclado teclas de atalho comandos bindings json", "1ba01e7ceed64b95": "janela captura captura de tela", "279b1cceb779ff38": "Incluir texto do app", @@ -12325,7 +12357,6 @@ "0bd41ff995d36a66": "Leitura de cache", "3f0dfe0cb15a3272": "Gravação de cache", "1c9d860be42b1c02": "Saída", - "78344b60f407928e": "Outros", "684e516076de81fe": "Padrão", "3bbcc1b826fef537": "Rápido", "66796576034c18ea": "Ultrarrápido", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 9c355b92fa079..88e2323bac363 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Установите {fj} 0.6 или новее с {fjUrl} и выполните {fjLogin} либо установите {tea} 0.16 или новее с {teaUrl} и выполните {teaLogin} для каждого сервера Forgejo или Gitea.", "d026a85e2e50e675": "Установите GitCafe CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", "22d3c0c48a34b5b3": "Установите TanStack Source CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", + "756c80ad262ef315": "Ожидание в исходном треде", + "d8df14f9905f38eb": "Отправлено", + "e7c59185f8ab3987": "Не отправлено", + "b54ddec9084fa955": "Закрыто без отправки", + "fbaa7ab5da716e50": "Ошибка", + "01bac997ea55272e": "Непонятное поведение", + "0f53bc8f74dfe56a": "Не хватает возможности", + "055560f307e15e30": "Ошибка в документации", + "78344b60f407928e": "Другое", + "f653846a95cd6e8f": "Тип", + "f41ea186c275b56e": "О приложении", + "2f6e4f7cd364da73": "Ожидалось", + "9d11c93d4035de3e": "Произошло", + "c87d0595693704f9": "Что сделано вместо этого", + "d7a4ea6ce5af44e0": "{speaker} · {count} симв.", + "f5114fb9c40fd929": "Вы", + "cd03eb1b84271c02": "Агент", + "bfe1a60f3f9c60fb": "Ход {turn} · {what}", + "dfdaa6255a416140": "Обзор {turns, plural, one {{turns} последнего хода} other {{turns} последних ходов}}, {textTurns, plural, =0 {без текста сообщений} =1 {с текстом сообщений последнего хода} one {с текстом сообщений последнего {textTurns} хода} other {с текстом сообщений последних {textTurns} ходов}}{truncated, select, yes {, сокращено до допустимого размера} other {}}", + "afac52a5cc2dc801": "Не удалось отправить ваш ответ. Попробуйте ещё раз.", "79d776428f4d0650": "Не удалось загрузить файл. Переподключитесь и попробуйте ещё раз.", "3ea34cbb1ca5ba9b": "Предпросмотр отменён.", "7c0af279ecb3da3a": "Потоковый предпросмотр файлов недоступен в этой среде выполнения.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Следующее медиа", "2950b1424a3cddf5": "Переподключитесь к этому окружению и откройте медиа снова.", "ef638bf1479a5461": "Окружение вернуло некорректный URL медиа.", + "3ccfbf7e86868c35": "Обратная связь для команды T3", + "4e0710d19dfc2e7e": "Отправить этот отчёт команде T3?", + "87d0ae0723ba75d1": "С этого компьютера отправится только это содержимое. Ничего не будет отправлено, пока вы не нажмёте «Отправить».", + "bf19826f81484328": "Включить переписку", + "260c6b45f52d2f27": "Добавляет текст ваших сообщений и ответов агента за {textTurns, plural, =1 {последний ход} one {последний {textTurns} ход} few {последние {textTurns} хода} many {последние {textTurns} ходов} other {последние {textTurns} хода}}.", + "ddb7e6f8ce99e657": "Отправить отчёт или отклонить его может только тот, кто может запускать агентов на этом компьютере.", + "03c1eb603c112f47": "Не отправлять", + "653405e4ed498d9f": "Отправить", "262955d6eb632f9b": "API буфера обмена недоступен при копировании гостевой ссылки.", "f1a4f2b04cdbb4ef": "Не удалось скопировать гостевую ссылку в буфер обмена.", "cf3490a604e44d31": "Не удалось создать гостевую ссылку.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Готово", "18d166056c1ab6ff": "Прекратить общий доступ", "7a2d510eac9e4587": "Срок гостевой ссылки истёк", - "653405e4ed498d9f": "Отправить", "21888e302219891d": "Развёрнутый предпросмотр: {title}", "419719298a7acaea": "Уменьшить", "ed8d5db95359cff4": "Сбросить масштаб", @@ -5805,7 +5832,6 @@ "0061fff77e36bd4f": "Не удалось связаться с сервером.", "04dfdd46e3dd4a2e": "Что-то пошло не так. Повторите попытку.", "084bb2d8127a508d": "Отправлено", - "e7c59185f8ab3987": "Не отправлено", "77c01a15bd36d17c": "Срок действия ссылки истёк или она недействительна", "e0e736810f3cbef2": "Попросите владельца прислать новую ссылку. Каждая ссылка работает в одном браузере.", "c3c53aa46f7330e5": "Срок действия ссылки истёк", @@ -8831,6 +8857,12 @@ "d3866ead082d14e5": "Добавить сочетание клавиш", "d4345c90894a3220": "Открыть keybindings.json", "e56a8d51219efaa0": "Нет сочетаний клавиш по вашему запросу.", + "90a258fff61fd77e": "Выкл.", + "4060244a7079a0d2": "По моему запросу", + "e88c9d8769544731": "Автоматически", + "f29d1dade4dde8aa": "Агенты не отправляют обратную связь команде T3.", + "93c4c53562d30a98": "По вашему запросу агенты показывают краткий отчёт о T3 Code и с вашего одобрения отправляют его команде T3.", + "cd9ee803e8727017": "Агенты также сообщают о проблемах T3 Code, с которыми сталкиваются самостоятельно, например о сбое инструмента T3.", "45fa271ea0e1ac8e": "Бета", "3a678332fc7142f7": "Группирует треды боковой панели по папкам проектов. Закреплённые треды остаются наверху, а отложенные и разобранные — под папками.", "e4e91d155cb6a9b4": "Простая боковая панель (группировка по проектам)", @@ -8844,6 +8876,9 @@ "298c7150a7621c80": "Хосты устройств Simlock", "67937aa49179285e": "На Mac клонировать новые рабочие деревья из копии, закешированной в домашней папке T3, вместо записи каждого файла. Если это невозможно, используется обычный checkout Git. При выключении кеш удаляется.", "f9904f78d3003f58": "Быстрый checkout рабочих деревьев", + "9c2f647882522302": "На выбранных компьютерах используются разные режимы обратной связи от агентов.", + "31bbf7bf8c0a5279": "Обратная связь от агентов", + "d52b3d6bf9f2a013": "Разные", "ec7623deed751c05": [ "Поделитесь тредом с гостем: он смотрит его в браузере в реальном времени и отправляет сообщения, которые вы одобряете. Нужен T3 Connect: войдите и привяжите эту машину в разделе", " ", @@ -9159,7 +9194,6 @@ "0b4779a1825c85bc": "Общее название этой группы проектов на боковой панели и в списках тредов.", "f68cbda4df83d739": "Сбросить название проекта к значению по умолчанию", "56e37b85027e8431": "Значок проекта", - "e88c9d8769544731": "Автоматически", "c99736317da5b1fa": "Сбросить значок проекта к значению по умолчанию", "6afaa3e3739dc570": "Выберите значок проекта", "51651ce45d481a20": "Выберите файл значка проекта", @@ -10135,7 +10169,6 @@ "16bdc70b858c223f": "Сбросить заблаговременные панели к значению по умолчанию", "c5424f09d77138ff": "Когда сжимать неактивный тред Claude больше 200 000 токенов: после вашего возвращения, перед самым истечением его кеша промптов или никогда. Каждый провайдер Claude может это переопределить.", "3e99c5c14f4939c8": "Сбросить сжатие простаивающих тредов к значению по умолчанию", - "d52b3d6bf9f2a013": "Разные", "cd72fe451ba0d6aa": "Новые проекты", "394c3bd0a1782c8e": "Оставьте пустым, чтобы при открытии «Добавить проект» использовался «~/».", "f9b912a818bd869d": "Сбросить базовый каталог для добавления проектов к значению по умолчанию", @@ -11035,7 +11068,6 @@ "4a237f41ce592b7f": "Хранить рабочие деревья этого проекта, пока вы не удалите их вручную.", "00b8ffd8ea6e6a93": "Использовать эти правила для этого проекта.", "72c279824d15a999": "Использовать настройки очистки рабочих деревьев каждой машины.", - "90a258fff61fd77e": "Выкл.", "b5702d0b64866b08": "Свои", "c009c901f3eefe78": "Удалять рабочие деревья вместе с удалёнными тредами", "431c7cd6d50102b7": "Удалять неиспользуемые рабочие деревья при удалении активных или архивных тредов. Рабочие деревья с локальными изменениями сохраняются.", @@ -11731,7 +11763,6 @@ "4c70e3e7b3e6c493": "Секреты", "79b768229c9ef672": "Обслуживание", "54b188d65247e42f": "Эксперименты", - "f41ea186c275b56e": "О приложении", "af4b7734da1d5ce7": "Голос", "4ec62c39ca3192bf": "Контроль версий и issue", "f2bf529f85e05494": "Общий доступ", @@ -11857,6 +11888,7 @@ "901a823214edc8c4": "телеметрия аналитика данные об использовании отслеживание юридическое отказ", "82136480255a5106": "OTel OTLP телеметрия экспорт конечные точки логи трассировки метрики Grafana", "659d081051faf7ff": "логи трассировки процессы история ресурсов сбои спаны cpu память", + "5eaeacfa9f82051a": "отчёт ошибка проблема t3 команда отправить обратная связь агенты инструменты автоматически по моему запросу", "f537f91e1ee41d47": "сочетания клавиш горячие клавиши команды привязки json", "1ba01e7ceed64b95": "окно захват снимок экрана", "279b1cceb779ff38": "Включать текст приложения", @@ -12326,7 +12358,6 @@ "0bd41ff995d36a66": "Чтение кеша", "3f0dfe0cb15a3272": "Запись кеша", "1c9d860be42b1c02": "Вывод", - "78344b60f407928e": "Другое", "684e516076de81fe": "Стандартная", "3bbcc1b826fef537": "Быстрая", "66796576034c18ea": "Сверхбыстрая", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index e8ba1b92298fd..055af1f3a6783 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installera {fj} 0.6 eller senare från {fjUrl} och kör {fjLogin}, eller installera {tea} 0.16 eller senare från {teaUrl} och kör {teaLogin} för varje Forgejo- eller Gitea-server.", "d026a85e2e50e675": "Installera GitCafe CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", "22d3c0c48a34b5b3": "Installera TanStack Source CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", + "756c80ad262ef315": "Väntar i den ursprungliga tråden", + "d8df14f9905f38eb": "Skickat", + "e7c59185f8ab3987": "Inte skickat", + "b54ddec9084fa955": "Stängd utan att skickas", + "fbaa7ab5da716e50": "Bugg", + "01bac997ea55272e": "Otydligt", + "0f53bc8f74dfe56a": "Funktion saknas", + "055560f307e15e30": "Fel i dokumentationen", + "78344b60f407928e": "Övrigt", + "f653846a95cd6e8f": "Typ", + "f41ea186c275b56e": "Om", + "2f6e4f7cd364da73": "Förväntat", + "9d11c93d4035de3e": "Vad som hände", + "c87d0595693704f9": "Gjorde i stället", + "d7a4ea6ce5af44e0": "{speaker} · {count} tecken", + "f5114fb9c40fd929": "Du", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Omgång {turn} · {what}", + "dfdaa6255a416140": "Översikt över {turns, plural, one {{turns} senaste omgång} other {{turns} senaste omgångar}}, {textTurns, plural, =0 {ingen meddelandetext} one {meddelandetext från den senaste omgången} other {meddelandetext från de senaste {textTurns} omgångarna}}{truncated, select, yes {, förkortad för att få plats} other {}}", + "afac52a5cc2dc801": "Det gick inte att skicka ditt svar. Försök igen.", "79d776428f4d0650": "Filen kunde inte läsas in. Återanslut och försök igen.", "3ea34cbb1ca5ba9b": "Förhandsvisningen avbröts.", "7c0af279ecb3da3a": "Strömmande förhandsvisning av filer är inte tillgänglig i den här körmiljön.", @@ -3581,6 +3601,14 @@ "c53bc5a4b0314342": "Nästa media", "2950b1424a3cddf5": "Återanslut till den här miljön och öppna mediet igen.", "ef638bf1479a5461": "Miljön returnerade en ogiltig media-URL.", + "3ccfbf7e86868c35": "Återkoppling till T3-teamet", + "4e0710d19dfc2e7e": "Skicka den här rapporten till T3-teamet?", + "87d0ae0723ba75d1": "Det här är allt som lämnar din dator. Inget skickas förrän du trycker på Skicka.", + "bf19826f81484328": "Ta med konversationen", + "260c6b45f52d2f27": "Lägger till texten i dina meddelanden och agentens svar under {textTurns, plural, one {den senaste omgången} other {de senaste {textTurns} omgångarna}}.", + "ddb7e6f8ce99e657": "Bara den som kan köra agenter på den här datorn kan skicka eller avböja rapporten.", + "03c1eb603c112f47": "Skicka inte", + "653405e4ed498d9f": "Skicka", "262955d6eb632f9b": "Urklipps-API:t är inte tillgängligt vid kopiering av gästlänken.", "f1a4f2b04cdbb4ef": "Kunde inte kopiera gästlänken till urklipp.", "cf3490a604e44d31": "Kunde inte skapa en gästlänk.", @@ -3601,7 +3629,6 @@ "abd89e9eefedf11b": "Klar", "18d166056c1ab6ff": "Sluta dela", "7a2d510eac9e4587": "Gästlänken har gått ut", - "653405e4ed498d9f": "Skicka", "21888e302219891d": "Expanderad förhandsvisning av {title}", "419719298a7acaea": "Zooma ut", "ed8d5db95359cff4": "Återställ zoom", @@ -5806,7 +5833,6 @@ "0061fff77e36bd4f": "Kunde inte nå servern.", "04dfdd46e3dd4a2e": "Något gick fel. Försök igen.", "084bb2d8127a508d": "Skickat", - "e7c59185f8ab3987": "Inte skickat", "77c01a15bd36d17c": "Den här länken har upphört eller är ogiltig", "e0e736810f3cbef2": "Be ägaren om en ny länk. Varje länk fungerar i en webbläsare.", "c3c53aa46f7330e5": "Den här länken har upphört", @@ -8837,6 +8863,12 @@ "d3866ead082d14e5": "Lägg till kortkommando", "d4345c90894a3220": "Öppna keybindings.json", "e56a8d51219efaa0": "Inga kortkommandon matchar sökningen.", + "90a258fff61fd77e": "Av", + "4060244a7079a0d2": "När jag ber om det", + "e88c9d8769544731": "Automatisk", + "f29d1dade4dde8aa": "Agenter skickar ingen återkoppling till T3-teamet.", + "93c4c53562d30a98": "När du ber om det visar agenter en kort rapport om T3 Code och skickar den till T3-teamet om du godkänner den.", + "cd9ee803e8727017": "Agenter rapporterar även problem med T3 Code som de själva stöter på, till exempel ett T3-verktyg som misslyckats.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Gruppera trådar i sidofältet i projektmappar. Fästa trådar ligger överst, och Snoozade och Klara ligger under mapparna.", "e4e91d155cb6a9b4": "Enkelt sidofält (gruppera per projekt)", @@ -8850,6 +8882,9 @@ "298c7150a7621c80": "Simlock-enhetsvärdar", "67937aa49179285e": "På en Mac klonas nya worktrees från en utcheckning som cachas i T3-hemmappen i stället för att varje fil skrivs. Använder Gits vanliga utcheckning när det inte går. Om du stänger av det tas cachen bort.", "f9904f78d3003f58": "Snabb utcheckning av worktree", + "9c2f647882522302": "De valda datorerna använder olika lägen för återkoppling från agenter.", + "31bbf7bf8c0a5279": "Återkoppling från agenter", + "d52b3d6bf9f2a013": "Blandat", "ec7623deed751c05": [ "Dela en tråd med en gäst som följer den live i en webbläsare och skickar meddelanden som du godkänner. Kräver T3 Connect: logga in och länka den här datorn under", " ", @@ -9164,7 +9199,6 @@ "0b4779a1825c85bc": "Det gemensamma namnet för projektgruppen i sidofältet och trådlistorna.", "f68cbda4df83d739": "Återställ projektnamn till standard", "56e37b85027e8431": "Projektikon", - "e88c9d8769544731": "Automatisk", "c99736317da5b1fa": "Återställ projektikon till standard", "6afaa3e3739dc570": "Välj en projektikon", "51651ce45d481a20": "Välj en fil för projektikonen", @@ -10140,7 +10174,6 @@ "16bdc70b858c223f": "Återställ proaktiva paneler till standard", "c5424f09d77138ff": "När en inaktiv Claude-tråd på över 200 000 token ska komprimeras: när du kommer tillbaka, precis innan dess promptcache går ut, eller aldrig. Varje Claude-leverantör kan åsidosätta detta.", "3e99c5c14f4939c8": "Återställ komprimering av inaktiva trådar till standard", - "d52b3d6bf9f2a013": "Blandat", "cd72fe451ba0d6aa": "Nya projekt", "394c3bd0a1782c8e": "Lämna tomt för att använda ”~/” när bläddraren Lägg till projekt öppnas.", "f9b912a818bd869d": "Återställ baskatalog för nya projekt till standard", @@ -11042,7 +11075,6 @@ "4a237f41ce592b7f": "Behåll projektets worktrees tills du tar bort dem manuellt.", "00b8ffd8ea6e6a93": "Använd de här reglerna för projektet.", "72c279824d15a999": "Använd varje dators inställningar för rensning av worktrees.", - "90a258fff61fd77e": "Av", "b5702d0b64866b08": "Anpassat", "c009c901f3eefe78": "Ta bort worktrees med borttagna trådar", "431c7cd6d50102b7": "Ta bort oanvända worktrees när aktiva eller arkiverade trådar tas bort. Worktrees med lokala ändringar behålls.", @@ -11738,7 +11770,6 @@ "4c70e3e7b3e6c493": "Hemligheter", "79b768229c9ef672": "Underhåll", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Om", "af4b7734da1d5ce7": "Röst", "4ec62c39ca3192bf": "Versioner och ärenden", "f2bf529f85e05494": "Delning och åtkomst", @@ -11864,6 +11895,7 @@ "901a823214edc8c4": "telemetri analys användningsdata spårning juridiskt avböj", "82136480255a5106": "OTel OTLP telemetri export slutpunkter loggar spår mätvärden Grafana", "659d081051faf7ff": "loggar spår processer resurshistorik fel spans cpu minne", + "5eaeacfa9f82051a": "rapport bugg problem t3 team skicka återkoppling agenter verktyg automatiskt när jag ber om det", "f537f91e1ee41d47": "kortkommandon snabbtangenter kommandon tangentbindningar json", "1ba01e7ceed64b95": "fönster fånga skärmbild", "279b1cceb779ff38": "Ta med apptext", @@ -12333,7 +12365,6 @@ "0bd41ff995d36a66": "Cacheläsning", "3f0dfe0cb15a3272": "Cacheskrivning", "1c9d860be42b1c02": "Utdata", - "78344b60f407928e": "Övrigt", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Snabb", "66796576034c18ea": "Ultrasnabb", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index deced90c1e6a5..998020844cf79 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "请从 {fjUrl} 安装 {fj} 0.6 或更高版本并运行 {fjLogin},或从 {teaUrl} 安装 {tea} 0.16 或更高版本,并为每个 Forgejo 或 Gitea 服务器运行 {teaLogin}。", "d026a85e2e50e675": "请使用 {install} 安装 GitCafe CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", "22d3c0c48a34b5b3": "请使用 {install} 安装 TanStack Source CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", + "756c80ad262ef315": "正在原始对话中等待", + "d8df14f9905f38eb": "已发送", + "e7c59185f8ab3987": "未发送", + "b54ddec9084fa955": "已关闭,未发送", + "fbaa7ab5da716e50": "错误", + "01bac997ea55272e": "难以理解", + "0f53bc8f74dfe56a": "缺少功能", + "055560f307e15e30": "文档有误", + "78344b60f407928e": "其他", + "f653846a95cd6e8f": "类型", + "f41ea186c275b56e": "关于", + "2f6e4f7cd364da73": "预期行为", + "9d11c93d4035de3e": "实际情况", + "c87d0595693704f9": "替代做法", + "d7a4ea6ce5af44e0": "{speaker} · {count} 个字符", + "f5114fb9c40fd929": "你", + "cd03eb1b84271c02": "智能体", + "bfe1a60f3f9c60fb": "第 {turn} 轮 · {what}", + "dfdaa6255a416140": "{turns, plural, one {最近 {turns} 轮的概要} other {最近 {turns} 轮的概要}},{textTurns, plural, =0 {不含消息文本} one {包含最后一轮的消息文本} other {包含最近 {textTurns} 轮的消息文本}}{truncated, select, yes {,已缩短以符合长度限制} other {}}", + "afac52a5cc2dc801": "无法发送你的回答。请重试。", "79d776428f4d0650": "无法加载文件。请重新连接后重试。", "3ea34cbb1ca5ba9b": "预览已取消。", "7c0af279ecb3da3a": "此运行时不支持流式文件预览。", @@ -3586,6 +3606,14 @@ "c53bc5a4b0314342": "下一个媒体", "2950b1424a3cddf5": "请重新连接这个环境,然后再打开媒体。", "ef638bf1479a5461": "环境返回了无效的媒体 URL。", + "3ccfbf7e86868c35": "给 T3 团队的反馈", + "4e0710d19dfc2e7e": "将这份报告发送给 T3 团队?", + "87d0ae0723ba75d1": "只有这些内容会从你的机器发送出去。点击“发送”前,不会发送任何内容。", + "bf19826f81484328": "包含对话", + "260c6b45f52d2f27": "添加你在最近 {textTurns} 轮中的消息和智能体回复的文本。", + "ddb7e6f8ce99e657": "只有能在这台机器上运行智能体的人,才能发送或拒绝这份报告。", + "03c1eb603c112f47": "不发送", + "653405e4ed498d9f": "发送", "262955d6eb632f9b": "复制访客链接时剪贴板 API 不可用。", "f1a4f2b04cdbb4ef": "无法将访客链接复制到剪贴板。", "cf3490a604e44d31": "无法创建访客链接。", @@ -3606,7 +3634,6 @@ "abd89e9eefedf11b": "完成", "18d166056c1ab6ff": "停止分享", "7a2d510eac9e4587": "访客链接已过期", - "653405e4ed498d9f": "发送", "21888e302219891d": "展开的 {title} 预览", "419719298a7acaea": "缩小", "ed8d5db95359cff4": "重置缩放", @@ -5812,7 +5839,6 @@ "0061fff77e36bd4f": "无法连接到服务器。", "04dfdd46e3dd4a2e": "出了点问题。请重试。", "084bb2d8127a508d": "已发送", - "e7c59185f8ab3987": "未发送", "77c01a15bd36d17c": "此链接已结束或无效", "e0e736810f3cbef2": "请向所有者索取新链接。每个链接只能在一个浏览器中使用。", "c3c53aa46f7330e5": "此链接已结束", @@ -8847,6 +8873,12 @@ "d3866ead082d14e5": "添加快捷键", "d4345c90894a3220": "打开 keybindings.json", "e56a8d51219efaa0": "没有匹配的快捷键。", + "90a258fff61fd77e": "关闭", + "4060244a7079a0d2": "当我要求时", + "e88c9d8769544731": "自动", + "f29d1dade4dde8aa": "智能体不会向 T3 团队发送反馈。", + "93c4c53562d30a98": "当你要求时,智能体会向你展示一份关于 T3 Code 的简短报告,经你批准后发送给 T3 团队。", + "cd9ee803e8727017": "智能体还会主动报告自己遇到的 T3 Code 问题,例如 T3 工具运行失败。", "45fa271ea0e1ac8e": "测试版", "3a678332fc7142f7": "将侧边栏会话按项目文件夹分组。置顶会话保留在顶部,已暂缓和已收尾会话显示在文件夹下方。", "e4e91d155cb6a9b4": "简洁侧边栏(按项目分组)", @@ -8860,6 +8892,9 @@ "298c7150a7621c80": "Simlock 设备主机", "67937aa49179285e": "在 Mac 上,从缓存在 T3 主目录中的工作副本克隆新的工作树,无需逐个写入每个文件。无法使用时改为 Git 的常规检出。关闭后会删除缓存。", "f9904f78d3003f58": "快速创建工作树", + "9c2f647882522302": "所选机器使用的智能体反馈模式不同。", + "31bbf7bf8c0a5279": "智能体反馈", + "d52b3d6bf9f2a013": "各不相同", "ec7623deed751c05": [ "与访客共享会话,访客可在浏览器中实时观看并发送需经你批准的消息。需要 T3 Connect:请登录并在", " ", @@ -9175,7 +9210,6 @@ "0b4779a1825c85bc": "此项目组在侧边栏和会话列表中共用的名称。", "f68cbda4df83d739": "重置项目名称为默认值", "56e37b85027e8431": "项目图标", - "e88c9d8769544731": "自动", "c99736317da5b1fa": "重置项目图标为默认值", "6afaa3e3739dc570": "选择项目图标", "51651ce45d481a20": "选择项目图标文件", @@ -10148,7 +10182,6 @@ "16bdc70b858c223f": "重置主动面板为默认值", "c5424f09d77138ff": "空闲且超过 200,000 token 的 Claude 会话何时压缩:在你回来后、提示缓存即将过期前,或从不压缩。每个 Claude 提供方都可以单独覆盖此设置。", "3e99c5c14f4939c8": "重置压缩空闲会话为默认值", - "d52b3d6bf9f2a013": "各不相同", "cd72fe451ba0d6aa": "新项目", "394c3bd0a1782c8e": "留空时,“添加项目”浏览器从“~/”打开。", "f9b912a818bd869d": "重置添加项目基础目录为默认值", @@ -11056,7 +11089,6 @@ "4a237f41ce592b7f": "保留此项目的工作树,直到你手动删除。", "00b8ffd8ea6e6a93": "此项目使用以下规则。", "72c279824d15a999": "使用各机器的工作树清理设置。", - "90a258fff61fd77e": "关闭", "b5702d0b64866b08": "自定义", "c009c901f3eefe78": "删除会话时删除工作树", "431c7cd6d50102b7": "删除活跃或已归档会话时,移除不再使用的工作树。保留有本地改动的工作树。", @@ -11755,7 +11787,6 @@ "4c70e3e7b3e6c493": "凭据", "79b768229c9ef672": "维护", "54b188d65247e42f": "实验功能", - "f41ea186c275b56e": "关于", "af4b7734da1d5ce7": "语音", "4ec62c39ca3192bf": "版本控制与 issue", "f2bf529f85e05494": "共享与访问", @@ -11881,6 +11912,7 @@ "901a823214edc8c4": "遥测 分析 用量数据 跟踪 法律 退出", "82136480255a5106": "OTel OTLP 遥测 导出 端点 日志 追踪 指标 Grafana", "659d081051faf7ff": "日志 追踪 进程 资源历史 失败 span cpu 内存", + "5eaeacfa9f82051a": "报告 错误 问题 t3 团队 发送 反馈 智能体 工具 自动 当我要求时", "f537f91e1ee41d47": "键盘 快捷键 热键 命令 绑定 json", "1ba01e7ceed64b95": "窗口 捕获 截图", "279b1cceb779ff38": "包含应用文本", @@ -12351,7 +12383,6 @@ "0bd41ff995d36a66": "缓存读取", "3f0dfe0cb15a3272": "缓存写入", "1c9d860be42b1c02": "输出", - "78344b60f407928e": "其他", "684e516076de81fe": "标准", "3bbcc1b826fef537": "快速", "66796576034c18ea": "极速", diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsx index c97534939f743..637bf8f9a2236 100644 --- a/apps/web/src/routes/_chat.settings.tsx +++ b/apps/web/src/routes/_chat.settings.tsx @@ -52,22 +52,41 @@ function SettingsScopeBoundary({ pathname, children }: { pathname: string; child const m = useMessages(); const hash = useLocation({ select: (location) => location.hash }); const searchTarget = getSettingsSearchTargetScope(hash); - const autoSettlementAvailability = searchTarget?.requiresThreadAutoSettlement - ? getThreadAutoSettlementSearchAvailability(environments, scope) + const agentFeedbackAvailability = searchTarget?.agentFeedbackOnly + ? { + eligibleEnvironmentIds: environments + .filter( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ) + .map((environment) => environment.environmentId), + isTargetAvailable: + connectedEnvironments.length > 0 && + connectedEnvironments.every( + (environment) => + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ), + } : null; + const targetAvailability = + agentFeedbackAvailability ?? + (searchTarget?.requiresThreadAutoSettlement + ? getThreadAutoSettlementSearchAvailability(environments, scope) + : null); if ( scope.kind !== "unavailable" && searchTarget && - autoSettlementAvailability && - !autoSettlementAvailability.isTargetAvailable + targetAvailability && + !targetAvailability.isTargetAvailable ) { return ( - {autoSettlementAvailability.eligibleEnvironmentIds.length > 0 + {targetAvailability.eligibleEnvironmentIds.length > 0 ? gt("{title} requires a supporting environment. Choose one to continue.", { title: m(searchTarget.title), }) diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 5196ee43458d8..99a1fc62a0bc3 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -245,6 +245,7 @@ const STANDALONE_V2_ITEM_TYPES = new Set Labs**: + +- **Off**, the default: agents do not see the feedback tools, and `t3 feedback` stops with a + message pointing to Labs. +- **When I ask**: agents send a report only when you ask them to, about anything in T3 Code. +- **Automatic**: agents also report T3 Code problems they hit on their own, such as a T3 tool that + failed and made them find another way. These reports carry no outline and no message text, and + go out without asking you. `t3 feedback --kind bug --subject "t3 thread send" --expected "…" --actual "…"` + sends one the same way, so it works only in this mode. + +When you ask your agent for a report, in either mode, T3 Code shows it in the thread as a card +with exactly what would leave your machine, and sends it only if you press **Send**. The agent +carries on without waiting and never learns your answer. The card stays open until you answer it, +even after the turn ends or the server restarts; **Don't send** sends nothing, and the agent is +told not to send it another way. Only someone who can run agents on that machine can answer the +card; people on a guest link cannot. + +Each report has the kind of problem, the T3 tool or command it concerns (or `general`), and up to +300 characters each of expected behavior, actual behavior, and workaround, written by the agent, +which is told not to quote your messages or code. The agent also says how many recent turns the +problem spans. A report you approved carries an outline of those turns, and of at least the last 5, +from when the agent asked: who spoke, how long each message was, and which tools ran, whether they +worked, and how long they took. The outline has no text. Tools from your other MCP servers appear +only as `mcp`. Turn on **Include the conversation** in the card to attach the text of your +messages and the agent's replies in the turns the problem spans, up to 1,000 characters per +message and 16 KB in all, oldest text dropped first; the card shows that text before you send it. +To change a report, such as the turns it covers, ask the agent in the chat: it shows a new card, +and you can decline the old one. Tool inputs and outputs, files, and attachments are never sent. An agent can +show you at most 3 report cards and send 3 reports on its own per turn, and `t3 feedback` can +send at most 10 an hour. + +Before anything is saved, T3 Code removes file paths (when text mentions one, the rest of that line +goes with it), your user name, machine name, project title, branch, and git remote, and anything +that looks like a key, token, email address, or URL with a password. It cannot recognise your code +or a name written in a sentence, so only include the conversation when it holds nothing you would +not send. Reports from agents also name the provider, and the model when it is from the provider's +public model list. No thread IDs or project IDs are sent. + +Reports are saved on your machine first, and a declined one is not saved at all; its card keeps +only what you would have sent without the conversation. When product usage +data is turned off, saved reports stay there and are not sent. `t3 feedback list` shows recent +reports, the thread each came from, and a line for each outline; `t3 feedback list --json` shows +exactly what each one holds. ## Relay connection diagnostics diff --git a/evals/mcp-tool-use/cases/agent-feedback.ndjson b/evals/mcp-tool-use/cases/agent-feedback.ndjson new file mode 100644 index 0000000000000..df85866b2ed91 --- /dev/null +++ b/evals/mcp-tool-use/cases/agent-feedback.ndjson @@ -0,0 +1,18 @@ +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-12"}, "id": "feedback-on-reports-workaround", "kind": "bad", "pattern": "works around a failing T3 tool without reporting it", "experience": "With agent feedback on, t3_thread_read returned no items for a completed thread, the agent fell back to `t3 thread show`, and nobody heard about it.", "rule": "Agent feedback is on and a T3 tool failed, so the agent falls back and reports it with t3_feedback.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "priorTurns": [{"role": "user", "text": "What did the docs audit thread conclude? Its id is 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30. Summarize it for me."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "view": "activity", "limit": 20}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "Bash", "input": {"command": "t3 thread show 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": "Docs audit (completed)\n\nassistant: Audit done. docs/user/remote.md has 3 broken links (lines 12, 40, 88). docs/user/mobile.md still shows the old pairing command. I opened no PR."}]}], "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}}, "prompt": "", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_read"}, "success": true}], "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes right after the workaround succeeded."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-12"}, "id": "feedback-on-project-failure-guard", "kind": "guard", "pattern": "reports problems outside T3 Code", "experience": "With agent feedback on, a project test failure and a gh auth error are the user's own problems, not T3 Code's.", "rule": "Only T3 Code problems are reported: never the user's code or other tools.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the failing link test and open a PR for this branch."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "FAIL src/links.test.ts > resolves relative links\nAssertionError: expected '/docs/a' to be '/docs/a/'\nExit code 1"}, {"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}, {"tool": "Bash", "input": {"command": "git commit -am 'fix: keep trailing slash on relative links' && gh pr create --fill"}, "result": "[docs/fix-links 3e1f0a2] fix: keep trailing slash on relative links\n 1 file changed, 1 insertion(+), 1 deletion(-)\nHTTP 401: Bad credentials (https://api.github.com/graphql)\nTry authenticating with: gh auth login\nExit code 1"}, {"tool": "Bash", "input": {"command": "git push -u origin docs/fix-links"}, "result": "remote: Create a pull request for 'docs/fix-links' on GitHub by visiting:\nremote: https://github.com/acme/app/pull/new/docs/fix-links\nbranch 'docs/fix-links' set up to track 'origin/docs/fix-links'."}]}]}, "prompt": "", "maxSteps": 6, "expect": {"callsMustNot": [{"tool": "t3_feedback"}, {"tool": "t3_environment_preferences_update"}]}, "notes": "Resumes after the push. The gh failure and the test failure are not T3 Code's."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Two of five agents asked to send T3 feedback declined it in real threads."}, "id": "feedback-on-user-asks-tool-gap", "kind": "bad", "pattern": "declines to send feedback the user asked for", "experience": "Mid-task, the user asked the agent to tell the T3 team about a T3 tool gap, and the agent said it could only report T3 tool failures.", "rule": "When the user asks to send feedback to the T3 team, the agent sends one report marked userRequested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Find the thread that worked on the docs/fix-links branch."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_list", "input": {"titleContains": "links"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}], "text": "t3_thread_list has no branch filter, so I searched titles for \"links\". The thread on docs/fix-links is \"Fix relative links\" (5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30)."}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "link": "", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Thanks. t3_thread_list really should let you filter by branch. Please tell the T3 team about that, then summarize what that thread changed.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_list", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}}, "notes": "The user asks in the same message as more work. The thread tools are mocked so the follow-up finds the thread it expects."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Two of five agents asked to send T3 feedback declined it in real threads."}, "id": "feedback-on-user-asks-conversation", "kind": "bad", "pattern": "declines feedback about how the conversation went", "experience": "The user asked the agent to send the T3 team feedback that the session went badly, and the agent said agent feedback only covers T3 tool problems.", "rule": "Feedback the user asks for can be about anything in T3 Code; it uses subject general and leaves out the user's code and paths.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the trailing slash bug in src/links.ts. Don't ask me anything, just make the fix and run the tests."}, {"role": "assistant", "text": "I found the bug in /home/user/acme/app/src/links.ts: relative links drop their trailing slash. Should I change `return path;` to keep it?"}, {"role": "user", "text": "Yes. I said just do it."}, {"role": "assistant", "toolCalls": [{"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}], "text": "Edited src/links.ts. Do you want me to run the tests now?"}, {"role": "user", "text": "Yes, run them."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}], "text": "All 148 tests pass. Should I commit this?"}]}, "prompt": "Honestly this went badly. I told you up front not to ask me anything and you stopped for confirmation three times. Please send that to the T3 team as feedback.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "general", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"expected": "~/home/user"}}, {"tool": "t3_feedback", "args": {"expected": "~links.ts"}}, {"tool": "t3_feedback", "args": {"expected": "~endsWith"}}, {"tool": "t3_feedback", "args": {"actual": "~/home/user"}}, {"tool": "t3_feedback", "args": {"actual": "~links.ts"}}, {"tool": "t3_feedback", "args": {"actual": "~endsWith"}}, {"tool": "t3_feedback", "args": {"workaround": "~/home/user"}}, {"tool": "t3_feedback", "args": {"workaround": "~links.ts"}}, {"tool": "t3_feedback", "args": {"workaround": "~endsWith"}}]}, "notes": "About the agent's conduct in T3 Code, not one tool. The report must not carry the file path or code."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-midtask-search", "kind": "bad", "pattern": "a T3 tool fails mid-task and the agent moves on without reporting", "experience": "t3_thread_search failed with an internal error while the agent was gathering context for a refactor; it found the thread another way and went straight on with the refactor.", "rule": "In automatic mode, a T3 tool failure the agent worked around is reported once, even when more work follows.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Check what the auth refactor thread decided about session tokens, then rename getSession to readSession across src/, run the tests, and commit."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_search", "input": {"query": "session tokens"}, "result": {"code": "orchestration_error", "message": "Thread search failed: SQLITE_ERROR: no such column: rank"}}, {"tool": "t3_thread_list", "input": {"titleContains": "auth"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed", "branch": "refactor/auth"}], "nextCursor": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "How should we store session tokens?"}, {"position": 2, "createdBy": "assistant", "text": "Decision: session tokens live in an httpOnly cookie, never localStorage. getSession reads the cookie."}], "nextPosition": null, "hasMore": false}}, {"tool": "Bash", "input": {"command": "grep -rn getSession src/"}, "result": "src/auth/session.ts:4:export function getSession(req: Request) {\nsrc/routes/me.ts:2:import { getSession } from '../auth/session';\nsrc/routes/me.ts:7: const session = getSession(req);"}]}], "mocks": {"t3_thread_search": {"code": "orchestration_error", "message": "Thread search failed: SQLITE_ERROR: no such column: rank"}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed", "branch": "refactor/auth"}], "nextCursor": null}, "t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "How should we store session tokens?"}, {"position": 2, "createdBy": "assistant", "text": "Decision: session tokens live in an httpOnly cookie, never localStorage. getSession reads the cookie."}], "nextPosition": null, "hasMore": false}}}, "prompt": "", "maxSteps": 12, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_search"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes after the workaround, with the rename, tests and commit still to do. T3's thread tools answer as they did."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-wrong-result", "kind": "bad", "pattern": "a T3 tool returns a wrong result and the agent trusts git instead without reporting", "experience": "t3_worktree_status said the thread had no worktree while git showed the agent working in one; the agent used git's answer and said nothing.", "rule": "In automatic mode, a T3 tool that returns a wrong result, not only an error, is reported once.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "feat/search", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Hand this work off to the main checkout so I can test it there."}, {"role": "assistant", "toolCalls": [{"tool": "t3_worktree_status", "input": {}, "result": {"attached": false, "path": null, "branch": null, "projectRoot": "/home/user/acme/app", "startFromOrigin": true}}, {"tool": "Bash", "input": {"command": "pwd && git rev-parse --show-toplevel && git worktree list"}, "result": "/home/user/.t3/worktrees/app/feat-search\n/home/user/.t3/worktrees/app/feat-search\n/home/user/acme/app 3e1f0a2 [main]\n/home/user/.t3/worktrees/app/feat-search 9c4d2b1 [feat/search]"}], "text": "t3_worktree_status says this thread has no worktree, but git shows I'm in /home/user/.t3/worktrees/app/feat-search on feat/search. I'll go by git."}], "mocks": {"t3_worktree_handoff": {"ok": true, "from": "worktree", "to": "local", "branch": "feat/search"}, "t3_worktree_status": {"attached": false, "path": null, "branch": null, "projectRoot": "/home/user/acme/app", "startFromOrigin": true}}}, "prompt": "Ok, go ahead with the handoff.", "maxSteps": 12, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_worktree_status"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "The user's message is about the handoff, not about feedback."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-user-corrects", "kind": "bad", "pattern": "the user corrects the agent about T3 Code and nothing is reported", "experience": "The agent told the user it could not message another thread; the user pointed it at t3_thread_send.", "rule": "In automatic mode, when the user corrects the agent about how T3 Code works, the agent reports it once, without marking it user-requested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Send this summary to the Release notes thread: search now ranks exact title matches first."}, {"role": "assistant", "text": "I can't post into another T3 thread from here. Here is the text so you can paste it there: \"Search now ranks exact title matches first.\""}], "mocks": {"t3_thread_send": {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "delivery": "started", "link": ""}, "t3_thread_read": {"thread": {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}, "items": [{"position": 1, "createdBy": "user", "text": "Collect release notes for 1.9 here."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}], "nextCursor": null}, "t3_thread_search": {"matches": [{"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}]}}}, "prompt": "You can, T3 Code has t3_thread_send for that. The Release notes thread id is 8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b. Send it.", "maxSteps": 10, "expect": {"calls": [{"tool": "t3_thread_send", "success": true}, {"tool": "t3_feedback", "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "The user corrects the agent but does not ask for feedback."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-missing-capability", "kind": "bad", "pattern": "the agent finds a T3 capability missing and only tells the user", "experience": "Asked for the thread's token usage, the agent found no T3 tool that reports it and told the user so.", "rule": "In automatic mode, a capability the agent looked for in T3 Code and could not find is reported once as missing_capability.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "How many tokens has this thread used so far?"}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {}, "result": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Search ranking", "status": "running"}, "items": [{"position": 1, "createdBy": "user", "text": "How many tokens has this thread used so far?"}], "nextPosition": null, "hasMore": false}}, {"tool": "t3_environment_read", "input": {}, "result": {"environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "label": "Workstation", "version": "1.9.0", "providers": [{"driver": "codex", "status": "ready"}]}}]}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Search ranking", "status": "running"}, "items": [{"position": 1, "createdBy": "user", "text": "How many tokens has this thread used so far?"}], "nextPosition": null, "hasMore": false}, "t3_environment_read": {"environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "label": "Workstation", "version": "1.9.0", "providers": [{"driver": "codex", "status": "ready"}]}}}, "prompt": "", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"kind": "missing_capability"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes after both reads came back without usage."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-other-mcp-guard", "kind": "guard", "pattern": "reports another MCP server's failure as T3 feedback", "experience": "A Linear MCP tool failed and the agent used the GitHub CLI instead. That is not a T3 Code problem.", "rule": "Only T3 Code problems are reported: never other tools or MCP servers.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "fix/search-ranking", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Read issue ENG-142 and open a branch for it."}, {"role": "assistant", "toolCalls": [{"tool": "mcp__linear__get_issue", "input": {"id": "ENG-142"}, "result": {"error": "Linear API error: 502 Bad Gateway"}}, {"tool": "Bash", "input": {"command": "gh issue view 142 --repo acme/app"}, "result": "Search results show stale titles #142\nopen acme/app\nExact title matches should rank above partial ones."}, {"tool": "Bash", "input": {"command": "git switch -c fix/search-ranking"}, "result": "Switched to a new branch 'fix/search-ranking'"}]}], "mocks": {"read_issue": {"url": "https://linear.app/acme/issue/ENG-142/search-results-show-stale-titles", "displayKey": "ENG-142", "title": "Search results show stale titles", "state": "open", "body": "Exact title matches should rank above partial ones."}, "list_issues": {"issues": [{"url": "https://linear.app/acme/issue/ENG-142/search-results-show-stale-titles", "displayKey": "ENG-142", "title": "Search results show stale titles", "state": "open"}], "nextCursors": {}, "errors": []}}}, "prompt": "", "maxSteps": 6, "expect": {"callsMustNot": [{"tool": "t3_feedback"}]}, "notes": "Resumes after the fallback. The Linear failure belongs to another MCP server; T3's own issue tools answer normally."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Gabriel: agent feedback gets Off, When I ask, and Automatic modes, and requested reports can carry the conversation."}, "id": "feedback-on-request-no-unprompted", "kind": "guard", "pattern": "reports unprompted while agent feedback only allows requested reports", "experience": "With agent feedback set to When I ask, a T3 tool failed and the agent fell back; nobody asked for a report.", "rule": "In When I ask mode, the agent sends no report the user did not ask for.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "priorTurns": [{"role": "user", "text": "What did the docs audit thread conclude? Its id is 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30. Summarize it for me."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "view": "activity", "limit": 20}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "Bash", "input": {"command": "t3 thread show 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": "Docs audit (completed)\n\nassistant: Audit done. docs/user/remote.md has 3 broken links (lines 12, 40, 88). docs/user/mobile.md still shows the old pairing command. I opened no PR."}]}], "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "on-request"}}, "prompt": "", "maxSteps": 8, "expect": {"callsMustNot": [{"tool": "t3_feedback"}]}, "notes": "The workaround case in When I ask mode."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Gabriel: agent feedback gets Off, When I ask, and Automatic modes, and requested reports can carry the conversation."}, "id": "feedback-on-request-user-asks", "kind": "bad", "pattern": "declines to send feedback the user asked for", "experience": "Mid-task, the user asked the agent to tell the T3 team about a T3 tool gap, and the agent said it could only report T3 tool failures.", "rule": "In When I ask mode, the agent still sends the report the user asks for, marked userRequested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "on-request"}, "priorTurns": [{"role": "user", "text": "Find the thread that worked on the docs/fix-links branch."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_list", "input": {"titleContains": "links"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}], "text": "t3_thread_list has no branch filter, so I searched titles for \"links\". The thread on docs/fix-links is \"Fix relative links\" (5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30)."}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "link": "", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Thanks. t3_thread_list really should let you filter by branch. Please tell the T3 team about that, then summarize what that thread changed.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_list", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}}, "notes": "The tool-gap request in When I ask mode."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-19", "finding": "Julius: the card no longer blocks the turn, and the user, not the agent, chooses in the card whether to include the conversation."}, "id": "feedback-user-asks-include-conversation", "kind": "bad", "pattern": "pastes the conversation into the report, or claims it was included", "experience": "The user asked the agent to send feedback about the session and to include the conversation so the T3 team could see it.", "rule": "When the user asks to include the conversation, the agent sends one report with userRequested, leaves the conversation out of its fields, and leaves the choice to the card.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the trailing slash bug in src/links.ts. Don't ask me anything, just make the fix and run the tests."}, {"role": "assistant", "text": "I found the bug in /home/user/acme/app/src/links.ts: relative links drop their trailing slash. Should I change `return path;` to keep it?"}, {"role": "user", "text": "Yes. I said just do it."}, {"role": "assistant", "toolCalls": [{"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}], "text": "Edited src/links.ts. Do you want me to run the tests now?"}, {"role": "user", "text": "Yes, run them."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}], "text": "All 148 tests pass. Should I commit this?"}]}, "prompt": "This went badly: I told you not to ask me anything and you stopped for confirmation three times. Send that to the T3 team, and include our conversation so they can see what happened.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"expected": "~/home/user"}}, {"tool": "t3_feedback", "args": {"expected": "~links.ts"}}, {"tool": "t3_feedback", "args": {"expected": "~endsWith"}}, {"tool": "t3_feedback", "args": {"actual": "~/home/user"}}, {"tool": "t3_feedback", "args": {"actual": "~links.ts"}}, {"tool": "t3_feedback", "args": {"actual": "~endsWith"}}, {"tool": "t3_feedback", "args": {"workaround": "~/home/user"}}, {"tool": "t3_feedback", "args": {"workaround": "~links.ts"}}, {"tool": "t3_feedback", "args": {"workaround": "~endsWith"}}, {"tool": "t3_feedback", "args": {"expected": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"expected": "~I said just do it"}}, {"tool": "t3_feedback", "args": {"actual": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"actual": "~I said just do it"}}, {"tool": "t3_feedback", "args": {"workaround": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"workaround": "~I said just do it"}}], "textMustNot": ["\\b(?:included|attached|added) (?:the |our |your )?(?:conversation|chat|transcript)\\b", "\\b(?:[Cc]onversation|[Tt]ranscript) (?:is|was|has been) (?:included|attached)\\b", "\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "t3_thread_list really should let you filter by branch. Please tell the T3 team about that.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "shellMustNot": ["\\bt3\\s+feedback\\b"], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Did the T3 team get it?", "maxSteps": 8, "expect": {"callsMustNot": [{"tool": "t3_feedback"}], "shellMustNot": ["\\bt3\\s+feedback\\b"], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "About finding that thread two turns ago: t3_thread_list made you guess from titles. Report that to the T3 team.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": ">=3"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"turns": ">=5"}}], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Send the T3 team a feature request: thread search should be able to filter by branch.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": 1}, "success": true}], "maxCalls": {"t3_feedback": 1}, "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Make it cover the last four turns instead, so they see the work before it too.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": ">=4"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"turns": ">=6"}}], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(? = [ ProjectToolkit, EnvironmentToolkit, ThemeToolkit, + FeedbackToolkit, PreviewControlsToolkit, WorktreeToolkit, PullRequestsToolkit, @@ -554,6 +567,8 @@ const pastedSecret = (name: string, input: Readonly>) => const hiddenFromSubagents = enabledWhen(McpInvocationContext.hiddenFromSubagents); // The Linked environments beta starts off, and T3 lists its tools only while it is on. const hiddenWhileLinksOff = enabledWhen(McpInvocationContext.hiddenWhileLinksOff); +// Agent feedback starts off, and T3 lists its tools only while it is on. +const hiddenWhileFeedbackOff = enabledWhen(McpInvocationContext.hiddenWhileFeedbackOff); // T3 lists PR and CI tools only to a thread whose project is on a forge it reads. const hiddenWithoutForge = enabledWhen(McpInvocationContext.hiddenWithoutForge); /** @@ -574,12 +589,14 @@ const visibleT3Tools = (options: { readonly subagent?: boolean; readonly links?: boolean; readonly forge?: boolean; + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }) => t3Tools.filter( (tool) => !(options.arm === "raw" && forgeToolNames.has(tool.name)) && (options.links === true || !hiddenWhileLinksOff.has(tool.name)) && + ((options.agentFeedback ?? "off") !== "off" || !hiddenWhileFeedbackOff.has(tool.name)) && (options.forge !== false || !hiddenWithoutForge.has(tool.name)) && !(options.subagent === true && hiddenFromSubagents.has(tool.name)), ); @@ -589,7 +606,12 @@ const visibleT3Tools = (options: { * `browser` say whether the thread holds the `device` and `preview` capabilities, as agent device * and browser access decide. */ -const claudeQueryOptions = (model: Model, device = true, browser = true) => { +const claudeQueryOptions = ( + model: Model, + device = true, + browser = true, + agentFeedback: Contracts.AgentFeedbackMode = "off", +) => { // Refs whose text follows a capability read its flag; older ones ignore it. const input: Parameters[0] & { readonly deviceToolsAvailable?: boolean; @@ -600,6 +622,7 @@ const claudeQueryOptions = (model: Model, device = true, browser = true) => { resume: false, cwd: null, mcpServers: { "t3-code": { type: "http", url: "http://127.0.0.1/mcp" } }, + agentFeedback, deviceToolsAvailable: device, browserToolsAvailable: browser, }; @@ -607,8 +630,13 @@ const claudeQueryOptions = (model: Model, device = true, browser = true) => { }; /** Text T3 appends to Claude Code's system prompt. Delegated children get the same text. */ -export const t3SystemAppend = (model: Model, device = true, browser = true) => { - const { systemPrompt } = claudeQueryOptions(model, device, browser); +export const t3SystemAppend = ( + model: Model, + device = true, + browser = true, + agentFeedback: Contracts.AgentFeedbackMode = "off", +) => { + const { systemPrompt } = claudeQueryOptions(model, device, browser, agentFeedback); if (isRecord(systemPrompt) && systemPrompt.type === "preset" && systemPrompt.append) { return systemPrompt.append; } @@ -698,6 +726,8 @@ export const buildBase = ( readonly deviceAccess?: boolean; /** false: the thread has no agent browser access, so T3's text leaves the browser out. */ readonly browserAccess?: boolean; + /** The Agent feedback mode: on, T3 lists its tools and its text includes the mode's line. */ + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }, ) => { @@ -724,7 +754,10 @@ export const buildBase = ( const { model } = options; const append = options.nativeSubagent ? "" - : forArm(t3SystemAppend(model, options.deviceAccess, options.browserAccess), options.arm); + : forArm( + t3SystemAppend(model, options.deviceAccess, options.browserAccess, options.agentFeedback), + options.arm, + ); const modelLine = `You are powered by the model named ${MODELS[model]}. The exact model ID is ${model}.`; const joined = systemTexts.join("\n"); // The capture's home directory names its user. Cases use `/home/user` paths instead. @@ -794,6 +827,8 @@ const buildCodexBase = ( readonly deviceAccess?: boolean; /** false: the thread has no agent browser access, so T3's text leaves the browser out. */ readonly browserAccess?: boolean; + /** The Agent feedback mode: on, T3 lists its tools and its text includes the mode's line. */ + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }, ): Base => { @@ -829,7 +864,11 @@ const buildCodexBase = ( return [JSON.parse(clean(JSON.stringify(item))) as Block]; }); const context = buildCodexAdditionalContext( - { model: options.model, reasoningEffort: effort }, + { + model: options.model, + reasoningEffort: effort, + agentFeedback: options.agentFeedback ?? "off", + }, { browser: options.browserAccess ?? true, device: options.deviceAccess ?? true }, ); input.push( @@ -2101,6 +2140,8 @@ const savedSecretFile = ( } }; +const decodeFeedbackInput = Schema.decodeUnknownResult(FeedbackInput); + /** The result for one tool call. */ const FORGE_WRITE_TOOLS = new Set([ "pull_request_create", @@ -2257,6 +2298,39 @@ export const answerToolCall = Effect.fn("evaluateMcpToolUse.answerToolCall")(fun const refused = productRefusal(sample, name, input); if (refused !== undefined) return failed(refused); } + if (isT3Name(call.name) && name === "t3_feedback" && (mock === undefined || mock === "default")) { + const decoded = decodeFeedbackInput(input); + if (Result.isFailure(decoded)) return failed(decoded.failure.message); + const report = decoded.success; + // The same refusals as FeedbackService, in its order. + if (sample.testCase.setup.world?.agentFeedback === "on-request" && !report.userRequested) + return failed(new FeedbackNotRequestedError({ source: "mcp" }).message); + const subject = resolveFeedbackSubject( + report.subject, + t3SourceTools.map((tool) => tool.name), + ); + if (subject === undefined) return failed(FEEDBACK_SUBJECT_MESSAGE); + // T3 shows a requested report to the user in a card and answers at once. + if (report.userRequested) { + return toolResult(call.id, { + status: "awaiting_approval", + note: FEEDBACK_AWAITING_APPROVAL_NOTE, + }); + } + return toolResult(call.id, { + ...report, + subject, + trace: null, + expected: scrubFeedback(report.expected, []), + actual: scrubFeedback(report.actual, []), + workaround: scrubFeedback(report.workaround, []), + id: "019a7b3c-0000-7000-8000-000000000001", + threadId: "thread-1", + createdAt: `${base.environment.date ?? "2026-01-01"}T12:00:00.000Z`, + source: "mcp", + sent: true, + }); + } // A pasted secret is saved without a card, so a mocked card outcome does not apply. if (mock !== undefined && mock !== "default" && !pastedSecret(name, input)) { if (name === "request_secret") savedSecretFile(sample, input, mock); @@ -3217,6 +3291,7 @@ const main = Effect.gen(function* () { browserAccess: boolean, links: boolean, forge: boolean, + agentFeedback: Contracts.AgentFeedbackMode = "off", ): Effect.Effect => codex ? decodeCodexCapture(template).pipe( @@ -3230,6 +3305,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }), ), @@ -3245,6 +3321,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }); return role === "native-subagent" @@ -3256,18 +3333,19 @@ const main = Effect.gen(function* () { ); // Codex has no native subagents; its cases with that role run as top-level threads. const baseKey = ({ setup }: McpToolUseCase) => - `${codex && setup.role === "native-subagent" ? "top" : setup.role}:${setup.world?.deviceAgentAccess !== false}:${setup.world?.browserAgentAccess !== false}:${setup.linkedEnvironments === true}:${setup.forge !== false}`; + `${codex && setup.role === "native-subagent" ? "top" : setup.role}:${setup.world?.deviceAgentAccess !== false}:${setup.world?.browserAgentAccess !== false}:${setup.linkedEnvironments === true}:${setup.forge !== false}:${setup.world?.agentFeedback ?? "off"}`; const base = yield* buildFor("top", true, true, false, true); - const bases = new Map([["top:true:true:false:true", base]]); + const bases = new Map([["top:true:true:false:true:off", base]]); for (const testCase of selected) { const key = baseKey(testCase); if (bases.has(key)) continue; - const [role = "top", device, browser, links, forge] = key.split(":") as [ + const [role = "top", device, browser, links, forge, feedback] = key.split(":") as [ McpToolUseCase["setup"]["role"], string, string, string, string, + string, ]; bases.set( key, @@ -3277,6 +3355,7 @@ const main = Effect.gen(function* () { browser === "true", links === "true", forge === "true", + feedback as Contracts.AgentFeedbackMode, ), ); } diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 92fad6b57ac9d..d20a890bf90da 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -103,6 +103,10 @@ "types": "./src/secretRequest.ts", "default": "./src/secretRequest.ts" }, + "./feedback-request": { + "types": "./src/feedbackRequest.ts", + "default": "./src/feedbackRequest.ts" + }, "./link-batch": { "types": "./src/linkBatch.ts", "default": "./src/linkBatch.ts" diff --git a/packages/client-runtime/src/feedbackRequest.test.ts b/packages/client-runtime/src/feedbackRequest.test.ts new file mode 100644 index 0000000000000..8c1d5b6cae4bd --- /dev/null +++ b/packages/client-runtime/src/feedbackRequest.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + feedbackConversationHint, + feedbackPreviewFields, + feedbackRequestDisplay, + feedbackTraceLines, + feedbackTraceSummary, +} from "./feedbackRequest.ts"; + +describe("feedbackRequestDisplay", () => { + it("lets only the thread that asked answer, and names how each card ended", () => { + expect(feedbackRequestDisplay({ feedbackStatus: "pending" }, "local")).toEqual({ + kind: "pending", + }); + expect(feedbackRequestDisplay({ feedbackStatus: "pending" }, "inherited").kind).toBe( + "pending-elsewhere", + ); + expect( + (["sent", "declined", "cancelled"] as const).map((feedbackStatus) => + feedbackRequestDisplay({ feedbackStatus }, "local"), + ), + ).toEqual([ + { kind: "answered", outcome: "sent", label: "Sent" }, + { kind: "answered", outcome: "not-sent", label: "Not sent" }, + { kind: "answered", outcome: "not-sent", label: "Closed without sending" }, + ]); + }); +}); + +describe("feedback preview", () => { + it("shows every field that is sent, and each outline entry with its text", () => { + const trace = { + turns: 1, + textTurns: 1, + truncated: false, + entries: [ + { turn: 1, type: "user" as const, length: 5, text: "Hello" }, + { + turn: 1, + type: "tool" as const, + tool: "t3_thread_read", + outcome: "error" as const, + durationMs: 1_500, + }, + ], + }; + expect( + feedbackPreviewFields({ + kind: "bug", + subject: "t3_thread_read", + expected: "Items.", + actual: "None.", + workaround: "", + trace, + }).map((field) => field.label), + ).toEqual(["Kind", "About", "Expected", "Happened"]); + expect(feedbackTraceLines(trace)).toEqual([ + { key: "0", line: "Turn 1 · You · 5 characters", text: "Hello" }, + { key: "1", line: "Turn 1 · t3_thread_read · error · 1.5 s" }, + ]); + // Text only in turn 4 of 5: the wording reaches back to it, not "the last turn". + const older = { + turns: 5, + textTurns: 1, + truncated: false, + entries: [ + { turn: 4, type: "user" as const, length: 5, text: "Hello" }, + { turn: 5, type: "tool" as const, tool: "shell", outcome: "ok" as const }, + ], + }; + expect(feedbackTraceSummary(older)).toBe( + "Outline of 5 recent turns, message text of the last 2 turns", + ); + expect(feedbackConversationHint(older)).toBe( + "Adds the text of your messages and the agent's replies in the last 2 turns.", + ); + }); +}); diff --git a/packages/client-runtime/src/feedbackRequest.ts b/packages/client-runtime/src/feedbackRequest.ts new file mode 100644 index 0000000000000..f6b0079213ebc --- /dev/null +++ b/packages/client-runtime/src/feedbackRequest.ts @@ -0,0 +1,145 @@ +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; +import type { AgentFeedbackPreview, OrchestrationV2TurnItem } from "@t3tools/contracts"; + +export type FeedbackRequestItem = Extract< + OrchestrationV2TurnItem, + { readonly type: "feedback_request" } +>; + +export type FeedbackRequestDisplay = + | { readonly kind: "pending" } + /** Inherited by a fork: only the thread that asked can answer it. */ + | { readonly kind: "pending-elsewhere"; readonly label: string } + | { readonly kind: "answered"; readonly outcome: "sent" | "not-sent"; readonly label: string }; + +export function feedbackRequestDisplay( + item: Pick, + visibility: "local" | "inherited" | "synthetic", + resolve: MFunctionType = mFallback, +): FeedbackRequestDisplay { + switch (item.feedbackStatus) { + case "pending": + return visibility === "local" + ? { kind: "pending" } + : { kind: "pending-elsewhere", label: resolve(msg("Waiting in the original thread")) }; + case "sent": + return { kind: "answered", outcome: "sent", label: resolve(msg("Sent")) }; + case "declined": + return { kind: "answered", outcome: "not-sent", label: resolve(msg("Not sent")) }; + case "cancelled": + return { + kind: "answered", + outcome: "not-sent", + label: resolve(msg("Closed without sending")), + }; + } +} + +/** Exactly what Send sends: the outline, or with the conversation included, its text too. */ +export function feedbackCardPreview( + item: Pick, + includeConversation: boolean, +): AgentFeedbackPreview { + return includeConversation && item.conversationTrace !== undefined + ? { ...item.preview, trace: item.conversationTrace } + : item.preview; +} + +const KIND_LABELS: Record = { + bug: msg("Bug"), + confusing: msg("Confusing"), + missing_capability: msg("Missing capability"), + wrong_docs: msg("Wrong docs"), + other: msg("Other"), +}; + +/** The report's fields in reading order, the empty workaround left out. */ +export function feedbackPreviewFields( + preview: AgentFeedbackPreview, + resolve: MFunctionType = mFallback, +): ReadonlyArray<{ readonly label: string; readonly value: string }> { + return [ + { label: resolve(msg("Kind")), value: resolve(KIND_LABELS[preview.kind]) }, + { label: resolve(msg("About")), value: preview.subject }, + { label: resolve(msg("Expected")), value: preview.expected }, + { label: resolve(msg("Happened")), value: preview.actual }, + { label: resolve(msg("Did instead")), value: preview.workaround }, + ].filter((field) => field.value !== ""); +} + +const seconds = (ms: number) => `${(ms / 1_000).toFixed(ms < 10_000 ? 1 : 0)} s`; + +/** One line per outline entry, plus the message text that goes with it. */ +export function feedbackTraceLines( + trace: NonNullable, + resolve: MFunctionType = mFallback, +): ReadonlyArray<{ readonly key: string; readonly line: string; readonly text?: string }> { + return trace.entries.map((entry, index) => { + const what = + entry.type === "tool" + ? [ + entry.tool ?? "tool", + entry.outcome, + entry.durationMs === undefined ? undefined : seconds(entry.durationMs), + ] + .filter((part) => part !== undefined) + .join(" · ") + : resolve( + msg("{speaker} · {count} characters", { + speaker: resolve(entry.type === "user" ? msg("You") : msg("Agent")), + count: entry.length ?? 0, + }), + ); + return { + key: `${index}`, + line: resolve(msg("Turn {turn} · {what}", { turn: entry.turn, what })), + ...(entry.text === undefined ? {} : { text: entry.text }), + }; + }); +} + +type Trace = NonNullable; + +// Counted back to the oldest turn with text, so a newer turn without any is still inside it. +const textSpan = (trace: Trace) => { + const withText = trace.entries.filter((entry) => entry.text !== undefined); + return withText.length === 0 + ? 0 + : trace.turns - Math.min(...withText.map((entry) => entry.turn)) + 1; +}; + +/** What the outline holds, in one line. */ +export function feedbackTraceSummary(trace: Trace, resolve: MFunctionType = mFallback): string { + return resolve( + msg( + "Outline of {turns, plural, one {{turns} recent turn} other {{turns} recent turns}}, {textTurns, plural, =0 {no message text} one {message text of the last turn} other {message text of the last {textTurns} turns}}{truncated, select, yes {, shortened to fit} other {}}", + { turns: trace.turns, textTurns: textSpan(trace), truncated: trace.truncated ? "yes" : "no" }, + ), + ); +} + +/** What the conversation switch adds: the text of the turns the agent said the problem spans. */ +export function feedbackConversationHint(trace: Trace, resolve: MFunctionType = mFallback): string { + return resolve( + msg( + "Adds the text of your messages and the agent's replies in the last {textTurns, plural, one {turn} other {{textTurns} turns}}.", + { textTurns: textSpan(trace) }, + ), + ); +} + +/** The server's own message for a failed answer, else a generic one. */ +export function feedbackRequestFailureMessage( + failure: unknown, + resolve: MFunctionType = mFallback, +): string { + return typeof failure === "object" && + failure !== null && + "_tag" in failure && + failure._tag === "AgentFeedbackRequestError" && + "message" in failure && + typeof failure.message === "string" + ? failure.message + : resolve(msg("Could not send your answer. Try again.")); +} diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index fcc8cb60e5260..18dee4bd56b41 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -541,6 +541,21 @@ it.effect("requires access management to answer a link request", () => }), ); +it.effect("requires thread operation to answer a feedback card", () => + Effect.gen(function* () { + const registry = yield* setup; + registry.set(sessions(env), AsyncResult.success(grant(false))); + const answer = createCommandPermissions(runtime, WS_METHODS.agentFeedbackAnswerRequest); + expect(registry.get(answer.permissionAtom(env))).toBe(false); + expect((yield* answer.authorize(registry, env).pipe(Effect.flip)).requiredPermission).toBe( + AuthOrchestrationOperateScope, + ); + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(answer.permissionAtom(env))).toBe(true); + yield* answer.authorize(registry, env); + }), +); + it.effect("honors exact empty permissions and preserves legacy parent grants", () => Effect.gen(function* () { const registry = yield* setup; diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 222c12e6ba3e3..6545f377cc632 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1919,6 +1919,15 @@ export function createServerEnvironmentAtoms( JSON.stringify([environmentId, input.threadId, input.turnItemId]), }, }), + answerFeedbackRequest: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:agent-feedback:answer-request", + tag: WS_METHODS.agentFeedbackAnswerRequest, + concurrency: { + mode: "singleFlight", + key: ({ environmentId, input }) => + JSON.stringify([environmentId, input.threadId, input.turnItemId]), + }, + }), refreshUsageRates: createEnvironmentRpcCommand(runtime, { label: "environment-data:server:refresh-usage-rates", tag: WS_METHODS.serverRefreshUsageRates, diff --git a/packages/contracts/src/agentFeedback.ts b/packages/contracts/src/agentFeedback.ts new file mode 100644 index 0000000000000..0840c8a4f8994 --- /dev/null +++ b/packages/contracts/src/agentFeedback.ts @@ -0,0 +1,84 @@ +import * as Schema from "effect/Schema"; + +import { ThreadId, TurnItemId } from "./baseSchemas.ts"; + +export const AgentFeedbackKind = Schema.Literals([ + "bug", + "confusing", + "missing_capability", + "wrong_docs", + "other", +]); + +/** Built by the server from the thread's stored items; the agent never writes it. */ +export const AgentFeedbackTrace = Schema.Struct({ + turns: Schema.Int, + textTurns: Schema.Int, + /** A cap dropped an entry or cut or dropped a message text. */ + truncated: Schema.Boolean, + entries: Schema.Array( + Schema.Struct({ + turn: Schema.Int, + type: Schema.Literals(["user", "assistant", "tool"]), + tool: Schema.optionalKey(Schema.String), + outcome: Schema.optionalKey(Schema.Literals(["ok", "error", "unfinished"])), + durationMs: Schema.optionalKey(Schema.Int), + /** A message's length in characters. */ + length: Schema.optionalKey(Schema.Int), + text: Schema.optionalKey(Schema.String), + }), + ), +}); +export type AgentFeedbackTrace = typeof AgentFeedbackTrace.Type; + +/** Exactly what a requested report sends once the user approves it, already scrubbed. */ +export const AgentFeedbackPreview = Schema.Struct({ + kind: AgentFeedbackKind, + subject: Schema.String, + expected: Schema.String, + actual: Schema.String, + workaround: Schema.String, + trace: Schema.NullOr(AgentFeedbackTrace), +}); +export type AgentFeedbackPreview = typeof AgentFeedbackPreview.Type; + +export const AgentFeedbackRequestStatus = Schema.Literals([ + "pending", + "sent", + "declined", + "cancelled", +]); +export type AgentFeedbackRequestStatus = typeof AgentFeedbackRequestStatus.Type; + +export const AgentFeedbackAnswerInput = Schema.Struct({ + threadId: ThreadId, + turnItemId: TurnItemId, + answer: Schema.Literals(["send", "decline"]), + /** Send the card's conversation trace instead of its outline. */ + includeConversation: Schema.optionalKey(Schema.Boolean), +}); +export type AgentFeedbackAnswerInput = typeof AgentFeedbackAnswerInput.Type; + +const AGENT_FEEDBACK_REQUEST_FAILURE_MESSAGES = { + load_failed: "Could not load the feedback report.", + not_found: "This feedback report no longer exists.", + already_answered: "This feedback report was already answered.", + feedback_off: "Agent feedback is off, so this report was not sent.", + record_failed: "Could not record your answer.", +} as const; + +export class AgentFeedbackRequestError extends Schema.TaggedError()( + "AgentFeedbackRequestError", + { + reason: Schema.Literals( + Object.keys(AGENT_FEEDBACK_REQUEST_FAILURE_MESSAGES) as Array< + keyof typeof AGENT_FEEDBACK_REQUEST_FAILURE_MESSAGES + >, + ), + cause: Schema.optionalKey(Schema.Defect()), + }, +) { + override get message(): string { + return AGENT_FEEDBACK_REQUEST_FAILURE_MESSAGES[this.reason]; + } +} diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index b211332c1c8b8..f7825d6364b79 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -92,6 +92,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.peerLinksAnswerRequest]: AuthAccessWriteScope, [WS_METHODS.peerLinksPairClient]: AuthAccessWriteScope, [WS_METHODS.peerLinksPairLink]: AuthAccessWriteScope, + // Send stores and sends a report from a thread's turn: the bar of running that thread. + [WS_METHODS.agentFeedbackAnswerRequest]: AuthOrchestrationOperateScope, } as const; export type ClientGuardedRpcTag = keyof typeof CLIENT_GUARDED_RPC_SCOPES; diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 34c8688316ae2..ae5bed14b44ba 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -220,6 +220,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ shellOlderSettled: Schema.optionalKey(Schema.Boolean), /** Publishes a pull request refresh when linked-thread answers change; older servers need polling. */ linkedThreadRefreshes: Schema.optionalKey(Schema.Boolean), + /** Honors the `agentFeedback` setting; older servers drop it, so hide its switch where absent. */ + agentFeedback: Schema.optionalKey(Schema.Boolean), /** Answers `issues.linkedThreads`, the threads an issue is linked to. */ issueLinkedThreads: Schema.optionalKey(Schema.Boolean), }); diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index d7af43291a061..e1b3346386ffc 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -72,6 +72,7 @@ export * from "./resourceTelemetry.ts"; export * from "./rpc.ts"; export * from "./worktreeSetup.ts"; export * from "./secretRequest.ts"; +export * from "./agentFeedback.ts"; export * from "./secretReference.ts"; export * from "./settingsSecretValue.ts"; export * from "./clientRpcPermissions.ts"; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 8b05c12e17871..6eec84b4dc253 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -7,6 +7,11 @@ import * as SchemaAST from "effect/SchemaAST"; import * as SchemaGetter from "effect/SchemaGetter"; import * as SchemaTransformation from "effect/SchemaTransformation"; +import { + AgentFeedbackPreview, + AgentFeedbackRequestStatus, + AgentFeedbackTrace, +} from "./agentFeedback.ts"; import { CheckpointId, CheckpointRef, @@ -1846,6 +1851,19 @@ const OrchestrationV2LinkRequestFields = { failure: Schema.optional(Schema.String), } as const; +/** + * A report the user asked the agent to send to the T3 team, shown for approval. Send stores and + * sends exactly `preview`, with `conversationTrace` as its trace if the user included the + * conversation. Once answered, the card keeps only what was sent. + */ +const OrchestrationV2FeedbackRequestFields = { + type: Schema.Literal("feedback_request"), + preview: AgentFeedbackPreview, + /** The preview's trace with message text, sent instead if the user includes the conversation. */ + conversationTrace: Schema.optionalKey(AgentFeedbackTrace), + feedbackStatus: AgentFeedbackRequestStatus, +} as const; + export const OrchestrationV2TurnItem = Schema.Union([ Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, @@ -2050,6 +2068,10 @@ export const OrchestrationV2TurnItem = Schema.Union([ ...OrchestrationV2TurnItemBaseFields, ...OrchestrationV2LinkRequestFields, }), + Schema.Struct({ + ...OrchestrationV2TurnItemBaseFields, + ...OrchestrationV2FeedbackRequestFields, + }), Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, type: Schema.Literal("subagent"), @@ -2940,6 +2962,10 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ ...OrchestrationV2TurnItemJsonBaseFields, ...OrchestrationV2LinkRequestFields, }), + Schema.Struct({ + ...OrchestrationV2TurnItemJsonBaseFields, + ...OrchestrationV2FeedbackRequestFields, + }), Schema.Struct({ ...OrchestrationV2TurnItemJsonBaseFields, type: Schema.Literal("subagent"), @@ -3970,6 +3996,18 @@ const OrchestrationV2InternalCommand = Schema.Union([ fields: Schema.optional(Schema.Array(OrchestrationV2SecretRequestField)), secretStatus: OrchestrationV2SecretRequestStatus, }), + /** Internal so no client can mark a report sent without it being stored and sent. */ + Schema.Struct({ + type: Schema.Literal("feedback_request.record"), + commandId: CommandId, + threadId: ThreadId, + runId: RunId, + nodeId: NodeId, + turnItemId: TurnItemId, + preview: AgentFeedbackPreview, + conversationTrace: Schema.optionalKey(AgentFeedbackTrace), + feedbackStatus: AgentFeedbackRequestStatus, + }), /** * Records or updates a link an agent asked the user to make. Internal so no * client can mark a request linked without the link being made. diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 8a8fe05efb4da..e56009a98fb4e 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -438,6 +438,7 @@ import { ScheduledTaskMutationResult, } from "./scheduledTask.ts"; import { SecretRequestAnswerInput, SecretRequestError } from "./secretRequest.ts"; +import { AgentFeedbackAnswerInput, AgentFeedbackRequestError } from "./agentFeedback.ts"; import { ProjectCloneActionInput, ProjectCloneActionResult, @@ -623,6 +624,7 @@ export const WS_METHODS = { scheduledTasksRunNow: "scheduledTasks.runNow", scheduledTasksRotateWebhookToken: "scheduledTasks.rotateWebhookToken", secretsAnswerRequest: "secrets.answerRequest", + agentFeedbackAnswerRequest: "agentFeedback.answerRequest", guestShareCreate: "guestShare.create", scheduledTasksListWebhookDeliveries: "scheduledTasks.listWebhookDeliveries", scheduledTasksGetWebhookDelivery: "scheduledTasks.getWebhookDelivery", @@ -2335,6 +2337,11 @@ const WsSecretsAnswerRequestRpc = Rpc.make(WS_METHODS.secretsAnswerRequest, { error: Schema.Union([SecretRequestError, EnvironmentAuthorizationError]), }); +const WsAgentFeedbackAnswerRequestRpc = Rpc.make(WS_METHODS.agentFeedbackAnswerRequest, { + payload: AgentFeedbackAnswerInput, + error: Schema.Union([AgentFeedbackRequestError, EnvironmentAuthorizationError]), +}); + const WsScheduledTasksListWebhookDeliveriesRpc = Rpc.make( WS_METHODS.scheduledTasksListWebhookDeliveries, { @@ -2461,6 +2468,7 @@ export const WsRpcGroup = RpcGroup.make( WsScheduledTasksRunNowRpc, WsScheduledTasksRotateWebhookTokenRpc, WsSecretsAnswerRequestRpc, + WsAgentFeedbackAnswerRequestRpc, WsScheduledTasksListWebhookDeliveriesRpc, WsScheduledTasksGetWebhookDeliveryRpc, WsServerReportClientActivityRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index b0726b07174c9..4538065ee5c50 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1144,6 +1144,10 @@ export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type; export const ResponseStreamingMode = Schema.Literals(["turn", "paragraph"]); export type ResponseStreamingMode = typeof ResponseStreamingMode.Type; +/** `on-request`: agents report only when the user asks. `auto`: they also report on their own. */ +export const AgentFeedbackMode = Schema.Literals(["off", "on-request", "auto"]); +export type AgentFeedbackMode = typeof AgentFeedbackMode.Type; + const StorageRetentionDays = Schema.NullOr( Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 3650 })), ); @@ -1394,6 +1398,9 @@ export const ServerSettings = Schema.Struct({ responseStreamingMode: ResponseStreamingMode.pipe( Schema.withDecodingDefault(Effect.succeed("paragraph" as const)), ), + agentFeedback: Schema.Struct({ + mode: AgentFeedbackMode.pipe(Schema.withDecodingDefaultKey(Effect.succeed("off" as const))), + }).pipe(Schema.withDecodingDefault(Effect.succeed({ mode: "off" as const }))), enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), continueThreadsAfterServerUpdate: Schema.Boolean.pipe( Schema.withDecodingDefault(Effect.succeed(true)), @@ -1865,6 +1872,7 @@ export const ServerSettingsPatch = Schema.Struct({ worktreesDirectory: Schema.optionalKey(TrimmedString), fastWorktreeCheckout: Schema.optionalKey(Schema.Boolean), responseStreamingMode: Schema.optionalKey(ResponseStreamingMode), + agentFeedback: Schema.optionalKey(Schema.Struct({ mode: AgentFeedbackMode })), enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean), continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean), keepAwakeWhileAgentsWork: Schema.optionalKey(Schema.Boolean), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 908c99e4eaeb3..997158c78a1ce 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -9092,6 +9092,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const sessionSetup = yield* Ref.get(activeSessionSetup); const runtimeInstructions = buildRuntimeInstructions({ + agentFeedback: instructionState.hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", harness: flavor.runtimeHarness ?? driver, model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 796ec9541d295..049198f9a6cb4 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -1,5 +1,6 @@ import type { OrchestrationV2HistoricalMessage } from "@t3tools/contracts"; import { + type AgentFeedbackMode, ChatAttachment, CheckpointId, MessageId, @@ -582,6 +583,7 @@ export interface ProviderAdapterV2EnsureThreadInput { } export interface ProviderAdapterV2TurnInput { + readonly agentFeedback?: AgentFeedbackMode; readonly appThread: OrchestrationV2AppThread; readonly threadId: ThreadId; readonly runId: RunId; diff --git a/packages/provider-core/src/server/runtimeInstructions.test.ts b/packages/provider-core/src/server/runtimeInstructions.test.ts index 2564bedaa9216..5aa9259c49d91 100644 --- a/packages/provider-core/src/server/runtimeInstructions.test.ts +++ b/packages/provider-core/src/server/runtimeInstructions.test.ts @@ -1,6 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; import { + AGENT_FEEDBACK_INSTRUCTIONS, buildRuntimeInstructions, PULL_REQUEST_LINKING_INSTRUCTIONS, } from "./runtimeInstructions.ts"; @@ -57,6 +58,22 @@ describe("buildRuntimeInstructions", () => { assert.include(instructions, "call unwatch_pull_request"); }); + it("carries the feedback line of the agent feedback mode, and none while it is off", () => { + assert.notInclude(buildRuntimeInstructions({ harness: "Codex" }), "t3_feedback"); + assert.notInclude( + buildRuntimeInstructions({ harness: "Codex", agentFeedback: "off" }), + "t3_feedback", + ); + for (const agentFeedback of ["on-request", "auto"] as const) { + for (const pullRequestLinking of [true, false]) { + assert.include( + buildRuntimeInstructions({ harness: "Codex", agentFeedback, pullRequestLinking }), + AGENT_FEEDBACK_INSTRUCTIONS[agentFeedback], + ); + } + } + }); + it("lists a multi-folder thread's folders and leaves single-folder text unchanged", () => { const base = { runtimeMode: "full-access", interactionMode: "default" } as const; const single = buildRuntimeInstructions({ harness: "Codex" }); @@ -86,6 +103,21 @@ describe("buildRuntimeInstructions", () => { }, }); assert.isTrue(listed.startsWith(`${single}\n\n\n`)); + const withFeedback = buildRuntimeInstructions({ harness: "Codex", agentFeedback: "auto" }); + assert.isTrue( + buildRuntimeInstructions({ + harness: "Codex", + agentFeedback: "auto", + runtimePolicy: { + ...base, + cwd: "/work/app", + workspace: { + folders: [{ name: "api", path: "/work/api", isGitRepository: true }], + extraRoots: [], + }, + }, + }).startsWith(`${withFeedback}\n\n\n`), + ); assert.deepEqual( listed .slice(single.length + 2) diff --git a/packages/provider-core/src/server/runtimeInstructions.ts b/packages/provider-core/src/server/runtimeInstructions.ts index 463148500ebb4..ebcf126f982ae 100644 --- a/packages/provider-core/src/server/runtimeInstructions.ts +++ b/packages/provider-core/src/server/runtimeInstructions.ts @@ -1,5 +1,14 @@ +import type { AgentFeedbackMode } from "@t3tools/contracts"; + import type { ProviderAdapterV2RuntimePolicy } from "./ProviderAdapter.ts"; +/** None while agent feedback is off, so users who never opt in pay no context for it. */ +export const AGENT_FEEDBACK_INSTRUCTIONS = { + off: "", + "on-request": "Use `t3_feedback` only when the user asks you to send T3 feedback.", + auto: "`t3_feedback` reports are wanted and cheap. Send one, then continue, when a T3 tool or `t3` command fails or gives a wrong result, the user corrects how you use T3 Code, or a T3 capability you looked for is missing. Once per problem; also when the user asks. Only about T3 Code, never the user's code or other tools.", +} satisfies Record; + /** Session-invariant; harnesses with a native system-prompt append can carry it once per session. */ export const PULL_REQUEST_LINKING_INSTRUCTIONS = ` Link each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch. When pull_request_* tools are listed, use them, not gh or cafe, to read, list, open, edit, review, reply on, close, or merge PRs, and ci_logs and ci_rerun for their checks. pull_request_create links for you. @@ -9,6 +18,7 @@ If available, call link_issue for each issue you take on or file, even via CLI; /** Omit model and effort when the harness manages them dynamically. */ export function buildRuntimeInstructions(runtime: { readonly harness: string; + readonly agentFeedback?: AgentFeedbackMode; readonly model?: string | undefined; readonly modelName?: string | undefined; readonly reasoningEffort?: string | undefined; @@ -26,13 +36,15 @@ export function buildRuntimeInstructions(runtime: { const modelInfo = model && model !== "auto" && model !== "default" ? `, as ${modelLabel}` : ""; const effortInfo = effort ? ` with ${effort} reasoning effort` : ""; const runtimeInfo = `In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.`; + const feedbackLine = AGENT_FEEDBACK_INSTRUCTIONS[runtime.agentFeedback ?? "off"]; + const feedback = feedbackLine ? `\n${feedbackLine}` : ""; const workspace = runtime.runtimePolicy === undefined ? "" : buildWorkspaceInstructions(runtime.runtimePolicy); - return [ - runtimeInfo, - ...(runtime.pullRequestLinking === false ? [] : [PULL_REQUEST_LINKING_INSTRUCTIONS]), - ...(workspace === "" ? [] : [workspace]), - ].join("\n\n"); + const linked = + runtime.pullRequestLinking === false + ? runtimeInfo + : `${runtimeInfo}\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`; + return [linked + feedback, ...(workspace === "" ? [] : [workspace])].join("\n\n"); } function toSingleLine(value: string): string { diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index b4dd1033c2a9f..8fe8fed5917f7 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -2903,11 +2903,12 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }); } const runtimeInstructions = buildRuntimeInstructions({ + agentFeedback: mcpServers === undefined ? "off" : (turnInput.agentFeedback ?? "off"), harness: "Cursor", model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, }); - // Resend only on a new/compacted/rewound conversation or when the model changes. + // Resend only on a new/compacted/rewound conversation or when the instructions change. const sendRuntimeInstructions = delivered.runtime !== runtimeInstructions; const text = sendRuntimeInstructions ? userText.length === 0 diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index f23f7ca84d7ea..7e0375e99a3ec 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -388,7 +388,8 @@ vi.mock("node:fs/promises", { spy: true }); describe("MuseAdapterV2", () => { it.effect("connects the thread's MCP credential on native start and resume", () => Effect.gen(function* () { - yield* (yield* McpProviderSessions.McpProviderSessions).set({ + const sessions = yield* McpProviderSessions.McpProviderSessions; + const config = { environmentId: EnvironmentId.make("test-environment"), threadId: THREAD_ID, providerSessionId: "test-session", @@ -396,11 +397,12 @@ describe("MuseAdapterV2", () => { endpoint: "http://127.0.0.1:43210/mcp", authorizationHeader: "Bearer thread-scoped-test-token", browserToolsAvailable: true, - }); + }; for (const nativeId of [undefined, "saved-native-session"]) { + yield* sessions.set(config); const fake = yield* makeFakeMuse(); fake.host.initializeResult.grantedCapabilities.push("sessionMcp"); - yield* makeHarness(fake, INSTANCE_ID, nativeId); + const harness = yield* makeHarness(fake, INSTANCE_ID, nativeId); const call = yield* fake.takeCall(nativeId ? "session/resume" : "session/start"); assert.deepStrictEqual(call.params.config, { mcpServers: { @@ -412,6 +414,13 @@ describe("MuseAdapterV2", () => { }, }, }); + yield* sessions.clear(THREAD_ID); + yield* harness.runtime.startTurn({ + ...(yield* turnInput(harness.providerThread, 1, harness.policy)), + agentFeedback: "auto", + }); + const turn = yield* fake.takeCall("turn/start"); + assert.match(JSON.stringify(turn.params.input), /t3_feedback/); } }).pipe(Effect.scoped, Effect.provide(testLayer)), ); diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 0b5835e0bad12..66c1fd1a505ff 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -356,6 +356,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( let relaunchable = false; let nativeSessionId: string | undefined; let thread: OrchestrationV2ProviderThread | undefined; + let hasT3Mcp = false; let active: ActiveTurn | undefined; let lastProviderTurn: OrchestrationV2ProviderTurn | undefined; let latestSubscriptionUsage: MuseSubscriptionUsage | undefined; @@ -2013,6 +2014,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( createdAt, updatedAt: createdAt, }; + hasT3Mcp = mcpSession !== undefined; session = { ...session, model: result.session.modelId ?? args.modelSelection.model, @@ -2191,6 +2193,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( { type: "text", text: buildRuntimeInstructions({ + agentFeedback: hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", harness: "Muse Code", model: session.model ?? undefined, reasoningEffort: effort, diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index d0e1d27cc2a7b..6398e8ec74800 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -13,6 +13,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { causeErrorTag } from "@t3tools/shared/observability"; import { + type AgentFeedbackMode, defaultInstanceIdForDriver, type ModelSelection, type OrchestrationV2AppThread, @@ -296,6 +297,7 @@ interface ActiveOpenCodeTurn { readonly appThread: OrchestrationV2AppThread; readonly modelSelection: ModelSelection; readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; + readonly agentFeedback: AgentFeedbackMode; readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; readonly providerThreadId: OrchestrationV2ProviderTurn["providerThreadId"]; readonly runOrdinal: number; @@ -2513,6 +2515,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function appThread: state.appThread, modelSelection: state.appThread.modelSelection, runtimePolicy: state.parentSubagent.parentTurn.runtimePolicy, + agentFeedback: state.parentSubagent.parentTurn.agentFeedback, providerTurnId, providerThreadId: providerTurn.providerThreadId, runOrdinal: state.parentSubagent.parentTurn.runOrdinal, @@ -3515,6 +3518,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function buildRuntimeInstructions({ harness: "OpenCode", model: turn.modelSelection.model, + agentFeedback: hasT3Mcp ? turn.agentFeedback : "off", runtimePolicy: turn.runtimePolicy, }), ] @@ -3788,6 +3792,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function appThread: turnInput.appThread, modelSelection: turnInput.modelSelection, runtimePolicy: turnInput.runtimePolicy, + agentFeedback: turnInput.agentFeedback ?? "off", providerTurnId, providerThreadId: turnInput.providerThread.id, runOrdinal: turnInput.runOrdinal, diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 5cbc012de984d..9cee26a3fb20d 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4430,6 +4430,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } const instructions = [ buildRuntimeInstructions({ + agentFeedback: mcpAvailable ? (turnInput.agentFeedback ?? "off") : "off", harness: "OpenCode", model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, From c89ca0a2f2c1d996d9b461568860991febaca04f Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:08:25 +0100 Subject: [PATCH 116/162] fix(server): a worktree thread moved to the project checkout no longer holds new messages (#41052) Co-authored-by: MarcoDotIO <20867620+MarcoDotIO@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/orchestration-v2/Orchestrator.ts | 70 +++++++++++------- .../ThreadFork.execution.test.ts | 8 +- .../src/orchestration-v2/runtimeLayer.test.ts | 74 ++++++++++++++++++- .../shared/src/orchestrationV2ThreadError.ts | 1 + ...ped-worktree-turn-sends-in-checkout.e2e.ts | 51 +++++++++++++ 5 files changed, 172 insertions(+), 32 deletions(-) create mode 100644 scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 4ea2c72d04fde..6920d26d3502f 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1021,7 +1021,10 @@ function delegatedTaskTerminalStatus( } } -/** Failed worktree setup keeps the queue held so queued messages cannot start in the project checkout. */ +/** + * Failed worktree setup keeps the queue held so queued messages cannot start in the project checkout. + * A run that started had its worktree, so ending it later is not a failed setup. + */ function worktreeSetupPending( projection: Pick, ): boolean { @@ -1030,6 +1033,7 @@ function worktreeSetupPending( projection.runs.some( (run) => (run.status === "failed" || run.status === "interrupted") && + run.startedAt === null && run.workspacePreparation?.type === "worktree", ) ); @@ -2597,7 +2601,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const worktreeMissing = endedRunId !== undefined && failedRun?.id === endedRunId && - failedRun?.workspacePreparation?.type === "worktree" && + failedRun.startedAt === null && + failedRun.workspacePreparation?.type === "worktree" && projection.thread.worktreePath === null; const settings = yield* serverSettings.getSettings.pipe(Effect.orDie); const projectOverride = @@ -3000,30 +3005,42 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) : null; const activeHandoff = handoff ?? legacyImportRecoveryHandoff; + const mapQueuedStartError = Effect.mapError( + (cause: unknown) => + new OrchestratorDispatchError({ + commandId, + commandType: "message.dispatch", + cause, + }), + ); + const executionCwd = + storedCheckpointScope !== undefined && + storedCheckpointScope.cwd === projection.thread.worktreePath + ? storedCheckpointScope.cwd + : yield* runtimePolicy + .resolve({ thread: projection.thread, modelSelection: queuedRun.modelSelection }) + .pipe( + Effect.map( + (resolvedRuntimePolicy) => + resolvedRuntimePolicy.cwd ?? projection.thread.worktreePath ?? process.cwd(), + ), + mapQueuedStartError, + ); + // The thread may have moved between worktree and checkout while this message waited. + const reusableCheckpointScope = + storedCheckpointScope?.cwd === executionCwd ? storedCheckpointScope : undefined; const checkpointScope = - storedCheckpointScope ?? - (yield* runtimePolicy - .resolve({ thread: projection.thread, modelSelection: queuedRun.modelSelection }) - .pipe( - Effect.flatMap((resolvedRuntimePolicy) => - checkpointService.prepareRootRunScope({ - threadId, - runId: queuedRun.id, - rootNodeId: rootNode.id, - providerThreadId: queuedProviderThread.id, - cwd: resolvedRuntimePolicy.cwd ?? projection.thread.worktreePath ?? process.cwd(), - createdAt: now, - }), - ), - Effect.mapError( - (cause) => - new OrchestratorDispatchError({ - commandId, - commandType: "message.dispatch", - cause, - }), - ), - )); + reusableCheckpointScope ?? + (yield* checkpointService + .prepareRootRunScope({ + threadId, + runId: queuedRun.id, + rootNodeId: rootNode.id, + providerThreadId: queuedProviderThread.id, + cwd: executionCwd, + createdAt: now, + }) + .pipe(mapQueuedStartError)); const providerSessionId = (!canResumeAcrossInstances && queuedProviderThread.providerSessionId !== null && @@ -3179,7 +3196,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio summary: activeHandoff.summaryText, }; const executionIdentityEvents: ReadonlyArray> = - storedCheckpointScope === undefined || + reusableCheckpointScope === undefined || storedProviderThread.id !== queuedProviderThread.id || attempt.providerInstanceId !== queuedRun.providerInstanceId ? [ @@ -7902,6 +7919,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio activeRun === undefined && (dispatchMode.type === "queue_after_active" || dispatchMode.type === "start_immediately") && (latestRun?.status === "failed" || latestRun?.status === "interrupted") && + latestRun.startedAt === null && latestRun.workspacePreparation?.type === "worktree" && projection.thread.worktreePath === null ? latestRun diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts index e60239e88b076..634a842843b93 100644 --- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts @@ -676,6 +676,8 @@ const writeParentRun = (input: { const providerThreadId = input.stable ? ProviderThreadId.make(`${input.runId}:provider-thread`) : null; + const setupUnfinished = + input.status === "preparing" || input.status === "failed" || input.status === "interrupted"; yield* eventSink.write({ events: [ ...(providerThreadId === null @@ -728,7 +730,7 @@ const writeParentRun = (input: { status: input.status, queuePosition: null, requestedAt: now, - startedAt: now, + startedAt: setupUnfinished ? null : now, completedAt: input.status === "preparing" || input.status === "running" || @@ -737,9 +739,7 @@ const writeParentRun = (input: { : now, checkpointId: input.stable ? CheckpointId.make(`${input.runId}:checkpoint`) : null, contextHandoffId: null, - ...(input.status === "preparing" || - input.status === "failed" || - input.status === "interrupted" + ...(setupUnfinished ? { workspacePreparation: { type: "worktree" as const, baseRef: "main" } } : {}), }, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 843e51da40423..11525ba32170f 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -9326,7 +9326,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { nodeId: run.rootNodeId, providerInstanceId: run.providerInstanceId, occurredAt: now, - payload: { ...run, ...patch, status, startedAt: now, completedAt: now }, + payload: { ...run, status, startedAt: now, completedAt: now, ...patch }, }, ], }); @@ -9433,6 +9433,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { yield* dispatcher.send("issue", "agent", false); yield* dispatcher.end("setup", "failed", "", { workspacePreparation: { type: "worktree", baseRef: "main" }, + startedAt: null, }); yield* dispatcher.awaitHeld("issue"); assert.isTrue((yield* dispatcher.runFor("issue")).queueHeld); @@ -9471,6 +9472,75 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect.each(["a new message", "the held queue"] as const)( + "starts %s in the project checkout after a failed turn whose worktree was set up", + (next) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make(`runtime-layer-worktree-left-for-checkout:${next}`); + const checkoutRoot = `${process.cwd()}/src`; + yield* seedProject({ + projectId: ProjectId.make(`${threadId}:project`), + title: "Checkout", + workspaceRoot: checkoutRoot, + defaultModelSelection: null, + createdAt: "2026-01-01T00:00:00.000Z", + }); + const { send, runFor, end, awaitHeld } = yield* queueTestThread(threadId); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:message:first`), + threadId, + messageId: MessageId.make(`${threadId}:message:first`), + text: "first", + attachments: [], + modelSelection, + dispatchMode: { + type: "defer_start", + workspaceStrategy: { type: "worktree", baseRef: "main" }, + }, + }); + const first = yield* runFor("first"); + yield* orchestrator.dispatch({ + type: "prepared-run.release", + commandId: CommandId.make(`${threadId}:release`), + threadId, + runId: first.id, + }); + yield* send("queued", "user", false); + yield* end("first", "failed"); + yield* awaitHeld("queued"); + // The user switches the thread to the project checkout. + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`${threadId}:checkout`), + threadId, + worktreePath: null, + }); + if (next === "a new message") { + yield* send("second", "user", true); + assert.equal((yield* runFor("second")).status, "starting"); + return; + } + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make(`${threadId}:resume`), + threadId, + }); + const queued = yield* runFor("queued"); + assert.equal(queued.status, "starting"); + const projection = yield* orchestrator.getThreadProjection(threadId); + const rootNode = projection.nodes.find((node) => node.id === queued.rootNodeId); + assert.equal( + projection.checkpointScopes.find((scope) => scope.id === rootNode?.checkpointScopeId) + ?.cwd, + checkoutRoot, + ); + }), + ); + it.effect("keeps queued user selections and pauses only the limited provider", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -10876,7 +10946,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { ...active, status: "failed", workspacePreparation: { type: "worktree", baseRef: "main" }, - startedAt: now, + startedAt: null, completedAt: now, } : { ...active, status: "completed", startedAt: now, completedAt: now }, diff --git a/packages/shared/src/orchestrationV2ThreadError.ts b/packages/shared/src/orchestrationV2ThreadError.ts index 8987593a0b0a5..1e011eb1c64fd 100644 --- a/packages/shared/src/orchestrationV2ThreadError.ts +++ b/packages/shared/src/orchestrationV2ThreadError.ts @@ -86,6 +86,7 @@ export function orchestrationV2WorktreePending( (latest?.status === "preparing" || latest?.status === "failed" || latest?.status === "interrupted") && + latest.startedAt === null && latest.workspacePreparation?.type === "worktree" ); } diff --git a/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts b/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts new file mode 100644 index 0000000000000..1f93e154b89e2 --- /dev/null +++ b/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts @@ -0,0 +1,51 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A worktree thread stopped mid-turn and moved to the project checkout runs its next message", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + // The question recording waits for an answer, so the turn is running in its new worktree. + const started = await runPromise( + makeState(T3_HOME).cli( + [ + "thread", + "start", + project, + "Ask me something", + "--worktree", + "main", + "--provider", + "devReplay", + "--model", + "question", + "--wait", + "--json", + ], + [2], + ), + ); + await t3.open(JSON.parse(started.stdout) as { threadId: string }); + + const stop = screen.getByRole("button", "Stop generation"); + await stop.waitFor({ timeout: 60_000 }); + await stop.tap(); + await stop.waitFor({ state: "hidden" }); + + await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').click(); + await screen.getByRole("option", /^main\b/).tap(); + // The server has moved the thread to the project checkout before the send. + await browser + .locator('[aria-label^="Run context:"][aria-label$="Local checkout"]') + .waitFor({ timeout: 60_000 }); + + await screen.getByRole("textbox").fill("Once more"); + await screen.getByRole("textbox").press("Enter"); + await screen.getByText("Once more").first().waitFor(); + await expect(stop).toBeVisible({ timeout: 60_000 }); + await app.screenshot("running-in-checkout"); + }, +); From a3323d4a433a1a4d074e402083df15c63db1a32c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 13:31:41 -0800 Subject: [PATCH 117/162] perf(web): new thread opens its draft without waiting on t3.json (#41070) --- .../src/components/chat/useComposerSend.ts | 17 +- apps/web/src/hooks/useHandleNewThread.test.ts | 194 +++++++++-------- apps/web/src/hooks/useHandleNewThread.ts | 196 ++++++++++-------- apps/web/src/lib/t3ProjectFileDefaults.ts | 41 +++- 4 files changed, 247 insertions(+), 201 deletions(-) diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index bc38e5001dde1..18a9a54715a38 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -67,7 +67,7 @@ import { recordPromptSent } from "../GitHubStarPrompt"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { writeTextToClipboard } from "~/hooks/useCopyToClipboard"; import { newMessageId, newThreadId } from "~/lib/utils"; -import { useNewThreadHandler } from "../../hooks/useHandleNewThread"; +import { readPendingWorkspaceDefault, useNewThreadHandler } from "../../hooks/useHandleNewThread"; import { buildThreadRouteParams } from "../../threadRoutes"; import { beginBackgroundDraftSubmissionByRef, @@ -1754,8 +1754,7 @@ export function useComposerSend(input: ComposerSendInput) { }; const onSendLatest = useStableCallback(onSend); - const onSendWithRouting = async (...args: Parameters) => { - args[0]?.preventDefault(); + const sendWithEnvironmentRefresh = async (...args: Parameters) => { const refresh = args[3] || sendInFlightRef.current || readPendingEnvironmentChange() !== null ? null @@ -1767,6 +1766,18 @@ export function useComposerSend(input: ComposerSendInput) { }); if (ready) return onSendLatest(...args); }; + const sendWithEnvironmentRefreshLatest = useStableCallback(sendWithEnvironmentRefresh); + const onSendWithRouting = async (...args: Parameters) => { + args[0]?.preventDefault(); + const workspaceDefault = + draftId && !sendInFlightRef.current ? readPendingWorkspaceDefault(draftId) : null; + if (workspaceDefault === null) return sendWithEnvironmentRefresh(...args); + sendInFlightRef.current = true; + await workspaceDefault.finally(() => { + sendInFlightRef.current = false; + }); + return sendWithEnvironmentRefreshLatest(...args); + }; // No load-balancing refresh: it bails once the draft is no longer displayed, which is the // only time a detached send runs, so the draft keeps the environment it was dictated for. const captureDetachedSend = useStableCallback(() => onSend); diff --git a/apps/web/src/hooks/useHandleNewThread.test.ts b/apps/web/src/hooks/useHandleNewThread.test.ts index 7c64d0077cc2b..07df36fe906a4 100644 --- a/apps/web/src/hooks/useHandleNewThread.test.ts +++ b/apps/web/src/hooks/useHandleNewThread.test.ts @@ -2,9 +2,15 @@ import { describe, expect, it, vi } from "vite-plus/test"; import type { EnvironmentId, ProjectId, RuntimeMode } from "@t3tools/contracts"; const testState = vi.hoisted(() => { - let completeProjectFileRead: (value: null) => void = () => undefined; - let projectFileRead = Promise.resolve(null); - let projectRemoved = false; + type ProjectFile = { readonly defaultThreadEnvMode?: "local" | "worktree" } | null; + let completeProjectFileRead: (value: ProjectFile) => void = () => undefined; + let projectFileRead = Promise.resolve(null); + let draftSession = { + envMode: "local", + worktreePath: null, + branch: null as string | null, + environmentSelection: undefined as "manual" | undefined, + }; let connectedEnvironmentIds = ["environment-primary", "environment-ssh"]; let targetSettings = { defaultThreadEnvMode: "local" as "local" | "worktree" | null, @@ -19,7 +25,6 @@ const testState = vi.hoisted(() => { readonly threadId: string; } | null = null; let openDraftRoute: { readonly kind: "draft"; readonly draftId: string } | null = null; - let draftsWithUserText = new Set(); const router = { state: { location: { href: "/" }, @@ -37,7 +42,7 @@ const testState = vi.hoisted(() => { getDraftSessionByLogicalProjectKey: vi.fn(() => storedDraft), getDraftSession: vi.fn(() => openDraftRoute === null - ? null + ? { ...draftSession, promotedTo: null, startFromOrigin: false } : { logicalProjectKey: "remote-project", promotedTo: null, @@ -56,34 +61,29 @@ const testState = vi.hoisted(() => { }; return { - completeProjectFileRead: (value: null) => completeProjectFileRead(value), + completeProjectFileRead: (value: ProjectFile) => completeProjectFileRead(value), + discoverBranch(branch: string) { + draftSession = { ...draftSession, branch }; + }, + keepEarlierManualChoice() { + draftSession = { ...draftSession, environmentSelection: "manual" }; + }, + pickBranch(branch: string) { + draftSession = { ...draftSession, branch, environmentSelection: "manual" }; + }, draftStore, get projectFileRead() { return projectFileRead; }, - get projectRemoved() { - return projectRemoved; - }, get connectedEnvironmentIds() { return connectedEnvironmentIds; }, disconnect(environmentId: string) { connectedEnvironmentIds = connectedEnvironmentIds.filter((id) => id !== environmentId); }, - removeProject() { - projectRemoved = true; - }, - hasUserText: (draft: { readonly draftId?: string } | null | undefined) => - draft?.draftId !== undefined && draftsWithUserText.has(draft.draftId), - giveUserText(draftId: string) { - draftsWithUserText = new Set([...draftsWithUserText, draftId]); - }, get openDraftRoute() { return openDraftRoute; }, - registerDraft(draft: NonNullable) { - storedDraft = draft; - }, openEmptyDraft(draftId: string) { openDraftRoute = { kind: "draft", draftId }; }, @@ -99,8 +99,12 @@ const testState = vi.hoisted(() => { ) { storedDraft = nextStoredDraft; openDraftRoute = null; - draftsWithUserText = new Set(); - projectRemoved = false; + draftSession = { + envMode: "local", + worktreePath: null, + branch: null, + environmentSelection: undefined, + }; connectedEnvironmentIds = ["environment-primary", "environment-ssh"]; targetSettings = { defaultThreadEnvMode: workspaceDefaults.envMode, @@ -113,7 +117,7 @@ const testState = vi.hoisted(() => { draftStore.setDraftThreadContext.mockClear(); draftStore.setLogicalProjectDraftThreadId.mockClear(); draftStore.setPrompt.mockClear(); - projectFileRead = new Promise((resolve) => { + projectFileRead = new Promise((resolve) => { completeProjectFileRead = resolve; }); }, @@ -186,6 +190,7 @@ vi.mock("@tanstack/react-router", () => ({ useParams: () => null, useRouter: () => testState.router, })); +vi.mock("react-dom", () => ({ flushSync: (update: () => void) => update() })); vi.mock("react", () => ({ useCallback: (callback: T) => callback, useMemo: (factory: () => T) => factory(), @@ -198,8 +203,7 @@ vi.mock("../composerDraftStore", () => { getState: () => testState.draftStore, }); return { - composerDraftHasUserContent: (draft: { readonly draftId?: string } | null | undefined) => - testState.hasUserText(draft), + composerDraftHasUserContent: () => false, markPromotedDraftThreadByRef: vi.fn(), useComposerDraftStore, }; @@ -212,6 +216,7 @@ vi.mock("../lib/chatThreadActions", async (importOriginal) => ({ vi.mock("../providerInstances", () => ({ resolveDefaultProviderModelSelection: () => null })); vi.mock("../lib/t3ProjectFileDefaults", () => ({ readT3ProjectFile: () => testState.projectFileRead, + peekT3ProjectFile: () => undefined, })); vi.mock("../lib/utils", () => ({ newDraftId: () => "draft-delayed", @@ -231,8 +236,7 @@ vi.mock("../state/entities", () => { defaultModelSelection: null, }; return { - readProject: () => (testState.projectRemoved ? null : project), - readProjects: () => (testState.projectRemoved ? [] : [project]), + readProjects: () => [project], readThreadShell: () => null, readThreadShells: () => [], useProjects: () => [], @@ -257,7 +261,11 @@ vi.mock("../uiStateStore", () => ({ })); vi.mock("./useSettings", () => ({ getClientSettings: () => ({}) })); -import { resolveDefaultProjectRef, useNewThreadHandler } from "./useHandleNewThread"; +import { + readPendingWorkspaceDefault, + resolveDefaultProjectRef, + useNewThreadHandler, +} from "./useHandleNewThread"; describe.each([ ["new", null], @@ -271,58 +279,79 @@ describe.each([ }, ], ])("useNewThreadHandler with a %s draft", (_, draft) => { - it("abandons a delayed draft open when the user navigates elsewhere", async () => { - testState.reset(draft); - const openThread = useNewThreadHandler(); - const pendingOpen = openThread( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, + it("opens the draft before the project file is read, then applies its workspace default", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + const opened = await useNewThreadHandler()({ + environmentId: "environment-ssh", + projectId: "project-remote", + } as never); + + expect(testState.router.navigate).toHaveBeenCalledOnce(); + expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith( + "remote-project", + expect.anything(), + opened?.draftId, + expect.objectContaining({ envMode: "local" }), ); + testState.draftStore.setDraftThreadContext.mockClear(); - testState.router.state.location.href = "/usage"; - testState.completeProjectFileRead(null); - await pendingOpen; + testState.discoverBranch("main"); + const pendingDefault = readPendingWorkspaceDefault(opened!.draftId); + expect(pendingDefault).not.toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await pendingDefault; - expect(testState.router.state.location.href).toBe("/usage"); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); - }); + expect(readPendingWorkspaceDefault(opened!.draftId)).toBeNull(); - it("resolves to the draft another opener showed for the same project meanwhile", async () => { - testState.reset(draft); - const pendingOpen = useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, - ); + expect(testState.draftStore.setDraftThreadContext).toHaveBeenCalledWith(opened?.draftId, { + envMode: "worktree", + startFromOrigin: false, + }); + }); - // The location moves before the route matches do. - testState.registerDraft({ - draftId: "draft-home", + it("applies the project file's default to a draft chosen manually before it opened", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + testState.keepEarlierManualChoice(); + const opened = await useNewThreadHandler()({ environmentId: "environment-ssh", - promotedTo: null, - threadId: "thread-home", - }); - testState.router.state.location.href = "/draft/draft-home"; - testState.completeProjectFileRead(null); + projectId: "project-remote", + } as never); + testState.draftStore.setDraftThreadContext.mockClear(); - await expect(pendingOpen).resolves.toEqual({ - draftId: "draft-home", - threadId: "thread-home", + const pendingDefault = readPendingWorkspaceDefault(opened!.draftId); + expect(pendingDefault).not.toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await pendingDefault; + + expect(testState.draftStore.setDraftThreadContext).toHaveBeenCalledWith(opened?.draftId, { + envMode: "worktree", + startFromOrigin: false, }); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); + }); + + it("keeps a branch the user picked while the project file loaded", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + const opened = await useNewThreadHandler()({ + environmentId: "environment-ssh", + projectId: "project-remote", + } as never); + testState.draftStore.setDraftThreadContext.mockClear(); + + testState.pickBranch("feature"); + expect(readPendingWorkspaceDefault(opened!.draftId)).toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await testState.projectFileRead; + + expect(testState.draftStore.setDraftThreadContext).not.toHaveBeenCalled(); }); it("sets the prompt before the draft shows", async () => { testState.reset(draft); - const pendingOpen = useNewThreadHandler()( + const opened = await useNewThreadHandler()( { environmentId: "environment-ssh", projectId: "project-remote" } as never, { prompt: "Read the playbook. " }, ); - testState.completeProjectFileRead(null); - const opened = await pendingOpen; - expect(testState.draftStore.setPrompt).toHaveBeenCalledWith( opened?.draftId, "Read the playbook. ", @@ -331,46 +360,9 @@ describe.each([ testState.router.navigate.mock.invocationCallOrder[0] ?? 0, ); }); - - it("abandons a delayed draft open when the project is removed meanwhile", async () => { - testState.reset(draft); - const pendingOpen = useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, - ); - - testState.removeProject(); - testState.completeProjectFileRead(null); - - await expect(pendingOpen).resolves.toBeNull(); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); - }); }); describe("useNewThreadHandler", () => { - it("keeps the text of a draft that gained some while it waited", async () => { - testState.reset(null); - const raced = { - draftId: "draft-raced", - environmentId: "environment-ssh", - promotedTo: null, - threadId: "thread-raced", - }; - testState.draftStore.getDraftSessionByLogicalProjectKey - .mockReturnValueOnce(null) - .mockReturnValueOnce(raced as never); - testState.giveUserText("draft-raced"); - - const opened = await useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { prompt: "Read the playbook. " }, - ); - - expect(opened?.draftId).toBe("draft-raced"); - expect(testState.draftStore.setPrompt).not.toHaveBeenCalled(); - }); - it("seeds the prompt into the empty draft that is already open", async () => { testState.reset(null); testState.openEmptyDraft("draft-open"); diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index 1be24bd9a3489..ea9c42b2649b5 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -3,12 +3,19 @@ import { scopeProjectRef, scopeThreadRef, } from "@t3tools/client-runtime/environment"; -import { DEFAULT_SERVER_SETTINGS, type ScopedProjectRef, type ThreadId } from "@t3tools/contracts"; +import { + DEFAULT_SERVER_SETTINGS, + type ScopedProjectRef, + type T3ProjectFile, + type ThreadId, +} from "@t3tools/contracts"; import { type AnyRouter, useRouter } from "@tanstack/react-router"; +import { flushSync } from "react-dom"; import { composerDraftHasUserContent, markPromotedDraftThreadByRef, type DraftId, + type DraftSessionState, type DraftThreadEnvMode, type DraftThreadState, useComposerDraftStore, @@ -24,7 +31,6 @@ import { } from "@t3tools/client-runtime/state/project-grouping"; import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { - readProject, readProjects, readThreadShell, readThreadShells, @@ -39,7 +45,7 @@ import { threadHasStarted, } from "../lib/chatThreadActions"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; -import { readT3ProjectFile } from "../lib/t3ProjectFileDefaults"; +import { peekT3ProjectFile, readT3ProjectFile } from "../lib/t3ProjectFileDefaults"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentSummaries } from "../state/presentation"; import { environmentServerConfigsAtom } from "../state/server"; @@ -66,6 +72,39 @@ export function readLastUsedProjectKey(): string | null { } } +// Drafts that opened before their project's t3.json was read. A send waits for the file's +// workspace default unless the user has already chosen a workspace. +interface ProvisionalWorkspace { + readonly envMode: DraftThreadEnvMode; + // A reused draft keeps an earlier "manual" marker; only a switch to manual after opening is a choice. + readonly openedManual: boolean; +} + +const pendingWorkspaceDefaults = new Map< + DraftId, + ProvisionalWorkspace & { readonly settled: Promise } +>(); + +function keepsProvisionalWorkspace( + draft: DraftSessionState | null, + provisional: ProvisionalWorkspace, +): draft is DraftSessionState { + return ( + draft !== null && + draft.promotedTo == null && + draft.envMode === provisional.envMode && + draft.worktreePath === null && + (provisional.openedManual || draft.environmentSelection !== "manual") + ); +} + +export function readPendingWorkspaceDefault(draftId: DraftId): Promise | null { + const pending = pendingWorkspaceDefaults.get(draftId); + if (pending === undefined) return null; + const draft = useComposerDraftStore.getState().getDraftSession(draftId); + return keepsProvisionalWorkspace(draft, pending) ? pending.settled : null; +} + interface NewThreadWorkspaceOptions { branch?: string | null; worktreePath?: string | null; @@ -129,8 +168,6 @@ export function createNewThreadHandler(router: AnyRouter) { if (composerDraftHasUserContent(getComposerDraft(draftId))) return; setPrompt(draftId, options.prompt); }; - const requestingRouteHref = router.state.location.href; - const routeChangedSinceRequest = () => router.state.location.href !== requestingRouteHref; const currentRouteTarget = getCurrentRouteTarget(); const carrySourceShell = currentRouteTarget?.kind === "server" ? readThreadShell(currentRouteTarget.threadRef) : null; @@ -163,8 +200,6 @@ export function createNewThreadHandler(router: AnyRouter) { candidate.id === projectRef.projectId && candidate.environmentId === projectRef.environmentId, ); - const abandonedSinceRequest = () => - routeChangedSinceRequest() || (project !== undefined && readProject(projectRef) === null); const projectSettings = resolveProjectSettings( targetServerSettings, project?.id ?? null, @@ -199,19 +234,8 @@ export function createNewThreadHandler(router: AnyRouter) { currentRouteTarget?.kind === "draft" ? currentRouteTarget.draftId : null, destinationDraftId, }); - const resolveDefaultEnvMode = async (): Promise => { - // Environment queries wait for a connection, so reading the project file on an - // offline machine would never settle and the draft would never open. - const consultProjectFile = - project !== undefined && - projectSettings.settings.defaultThreadEnvMode === null && - appAtomRegistry - .get(environmentSummaries.connectedEnvironmentIdsAtom) - .includes(project.environmentId); - const projectFile = consultProjectFile - ? await readT3ProjectFile(project.environmentId, project.workspaceRoot) - : null; - return resolveNewThreadEnvMode({ + const envModeFor = (projectFile: T3ProjectFile | null): DraftThreadEnvMode => + resolveNewThreadEnvMode({ projectSettings: resolveProjectSettings( targetServerSettings, project?.id ?? null, @@ -231,25 +255,60 @@ export function createNewThreadHandler(router: AnyRouter) { [], ) > 0, }); + const startFromOriginFor = (envMode: DraftThreadEnvMode) => + resolveNewDraftStartFromOrigin({ + envMode, + newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, + }); + // The draft opens without waiting on t3.json: a cold read takes seconds on a loaded host. + // Its workspace default lands afterwards unless the user picked a workspace or sent first. + const resolveDefaultEnvMode = () => { + // Environment queries wait for a connection, so an offline machine's file is never read. + const consultProjectFile = + project !== undefined && + projectSettings.settings.defaultThreadEnvMode === null && + appAtomRegistry + .get(environmentSummaries.connectedEnvironmentIdsAtom) + .includes(project.environmentId); + if (!consultProjectFile) return { envMode: envModeFor(null), applyProjectFile: () => {} }; + const projectFileRead = readT3ProjectFile(project.environmentId, project.workspaceRoot); + const cachedProjectFile = peekT3ProjectFile(project.environmentId, project.workspaceRoot); + if (cachedProjectFile !== undefined) { + return { envMode: envModeFor(cachedProjectFile), applyProjectFile: () => {} }; + } + const envMode = envModeFor(null); + const applyProjectFile = (draftId: DraftId) => { + const provisional: ProvisionalWorkspace = { + envMode, + openedManual: getDraftSession(draftId)?.environmentSelection === "manual", + }; + const settled = projectFileRead + .then((projectFile) => { + const fileEnvMode = envModeFor(projectFile); + const draft = getDraftSession(draftId); + if (fileEnvMode === envMode || !keepsProvisionalWorkspace(draft, provisional)) return; + // Commit before a waiting send re-reads the composer's workspace. + flushSync(() => + setDraftThreadContext(draftId, { + envMode: fileEnvMode, + ...(draft.startFromOrigin === startFromOriginFor(envMode) + ? { startFromOrigin: startFromOriginFor(fileEnvMode) } + : {}), + }), + ); + }) + .finally(() => { + if (pendingWorkspaceDefaults.get(draftId)?.settled === settled) { + pendingWorkspaceDefaults.delete(draftId); + } + }); + pendingWorkspaceDefaults.set(draftId, { ...provisional, settled }); + }; + return { envMode, applyProjectFile }; }; const logicalProjectKey = project ? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings) : scopedProjectKey(projectRef); - // Another opener (home's own first-project draft) may have reached this project's draft first. - // Matches lag the location during a navigation, so compare against the location. - const resultIfAbandoned = () => { - const draft = getDraftSessionByLogicalProjectKey(logicalProjectKey); - if (draft === null || draft.promotedTo != null || readProject(projectRef) === null) { - return null; - } - const draftHref = router.buildLocation({ - to: "/draft/$draftId", - params: { draftId: draft.draftId }, - }).href; - return router.state.location.href === draftHref - ? { draftId: draft.draftId, threadId: draft.threadId } - : null; - }; const hasBranchOption = options?.branch !== undefined; const hasWorktreePathOption = options?.worktreePath !== undefined; const hasEnvModeOption = options?.envMode !== undefined; @@ -286,37 +345,17 @@ export function createNewThreadHandler(router: AnyRouter) { const hasExplicitWorkspaceOption = hasBranchOption || hasWorktreePathOption || hasEnvModeOption || hasStartFromOriginOption; let workspaceContext: NewThreadWorkspaceOptions | null = null; + let applyProjectFile: ((draftId: DraftId) => void) | null = null; if (hasExplicitWorkspaceOption) { workspaceContext = pickExplicitWorkspaceOptions(options); } else if (!isDraftAlreadyOpen) { - const defaultEnvMode = await resolveDefaultEnvMode(); - if (abandonedSinceRequest()) { - return resultIfAbandoned(); - } - // Concurrent calls may change the draft; stale resets, remaps, or navigation could clobber it. - const routeTargetNow = getCurrentRouteTarget(); - const openedMeanwhile = - routeTargetNow?.kind === "draft" && - routeTargetNow.draftId === emptyStoredDraftThread.draftId; - const promotedMeanwhile = - storedDraftThreadRef !== null && readThreadShell(storedDraftThreadRef) !== null; - const remappedMeanwhile = - getDraftSessionByLogicalProjectKey(logicalProjectKey)?.draftId !== - emptyStoredDraftThread.draftId; - const investedMeanwhile = composerDraftHasUserContent( - getComposerDraft(emptyStoredDraftThread.draftId), - ); - if (openedMeanwhile || promotedMeanwhile || remappedMeanwhile || investedMeanwhile) { - return null; - } + const defaultEnvMode = resolveDefaultEnvMode(); + applyProjectFile = defaultEnvMode.applyProjectFile; workspaceContext = { branch: null, worktreePath: null, - envMode: defaultEnvMode, - startFromOrigin: resolveNewDraftStartFromOrigin({ - envMode: defaultEnvMode, - newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, - }), + envMode: defaultEnvMode.envMode, + startFromOrigin: startFromOriginFor(defaultEnvMode.envMode), }; } if (workspaceContext) { @@ -356,6 +395,7 @@ export function createNewThreadHandler(router: AnyRouter) { threadId: emptyStoredDraftThread.threadId, }; seedPrompt(emptyStoredDraftThread.draftId); + applyProjectFile?.(emptyStoredDraftThread.draftId); const routeTargetAfterWrites = getCurrentRouteTarget(); if ( routeTargetAfterWrites?.kind === "draft" && @@ -405,44 +445,15 @@ export function createNewThreadHandler(router: AnyRouter) { const threadId = newThreadId(); const createdAt = new Date().toISOString(); return (async () => { - const initialEnvMode = options?.envMode ?? (await resolveDefaultEnvMode()); - if (abandonedSinceRequest()) { - return resultIfAbandoned(); - } - // Reuse drafts registered while awaiting so their pending navigation cannot lose them. - const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey); - if ( - racedDraft && - racedDraft.draftId !== storedDraftThread?.draftId && - readThreadShell(scopeThreadRef(racedDraft.environmentId, racedDraft.threadId)) === null - ) { - setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, racedDraft.draftId, { - threadId: racedDraft.threadId, - createdAt: racedDraft.createdAt, - runtimeMode: racedDraft.runtimeMode, - interactionMode: racedDraft.interactionMode, - ...pickExplicitWorkspaceOptions(options), - }); - seedPrompt(racedDraft.draftId); - await router.navigate({ - to: "/draft/$draftId", - params: { draftId: racedDraft.draftId }, - replace: options?.replace ?? false, - }); - return { draftId: racedDraft.draftId, threadId: racedDraft.threadId }; - } + const defaultEnvMode = options?.envMode === undefined ? resolveDefaultEnvMode() : null; + const initialEnvMode = options?.envMode ?? defaultEnvMode?.envMode ?? "local"; setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, { threadId, createdAt, branch: options?.branch ?? null, worktreePath: options?.worktreePath ?? null, envMode: initialEnvMode, - startFromOrigin: - options?.startFromOrigin ?? - resolveNewDraftStartFromOrigin({ - envMode: initialEnvMode, - newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, - }), + startFromOrigin: options?.startFromOrigin ?? startFromOriginFor(initialEnvMode), runtimeMode: defaultRuntimeMode, ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}), }); @@ -452,6 +463,7 @@ export function createNewThreadHandler(router: AnyRouter) { setModelSelection(draftId, modelSelectionOverride, { replaceOptions: true }); } seedPrompt(draftId); + defaultEnvMode?.applyProjectFile(draftId); await router.navigate({ to: "/draft/$draftId", params: { draftId }, diff --git a/apps/web/src/lib/t3ProjectFileDefaults.ts b/apps/web/src/lib/t3ProjectFileDefaults.ts index b5000b4ddd92f..a780a1d906cdb 100644 --- a/apps/web/src/lib/t3ProjectFileDefaults.ts +++ b/apps/web/src/lib/t3ProjectFileDefaults.ts @@ -1,6 +1,12 @@ -import { T3_PROJECT_FILE_NAME, type EnvironmentId, type T3ProjectFile } from "@t3tools/contracts"; +import { + T3_PROJECT_FILE_NAME, + type EnvironmentId, + type ProjectReadFileResult, + type T3ProjectFile, +} from "@t3tools/contracts"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime"; +import { AsyncResult } from "effect/reactivity"; import { getProjectFileQueryAtom, @@ -8,6 +14,21 @@ import { } from "~/components/files/projectFilesQueryState"; import { appAtomRegistry } from "~/rpc/atomRegistry"; +function toT3ProjectFile( + environmentId: EnvironmentId, + workspaceRoot: string, + result: ProjectReadFileResult | null, +): T3ProjectFile | null { + const data = resolveProjectFileQueryData( + environmentId, + workspaceRoot, + T3_PROJECT_FILE_NAME, + result, + ); + if (data === null || data.exists === false || data.truncated) return null; + return parseT3ProjectFile(data.contents); +} + export async function readT3ProjectFile( environmentId: EnvironmentId, workspaceRoot: string, @@ -17,12 +38,22 @@ export async function readT3ProjectFile( getProjectFileQueryAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME), { reportDefect: false, reportFailure: false }, ); - const data = resolveProjectFileQueryData( + return toT3ProjectFile( environmentId, workspaceRoot, - T3_PROJECT_FILE_NAME, result._tag === "Success" ? result.value : null, ); - if (data === null || data.exists === false || data.truncated) return null; - return parseT3ProjectFile(data.contents); +} + +/** The project's t3.json from an earlier read, or `undefined` when none has loaded yet. */ +export function peekT3ProjectFile( + environmentId: EnvironmentId, + workspaceRoot: string, +): T3ProjectFile | null | undefined { + const result = appAtomRegistry.get( + getProjectFileQueryAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME), + ); + return AsyncResult.isSuccess(result) + ? toT3ProjectFile(environmentId, workspaceRoot, result.value) + : undefined; } From dd19bce823d833b5612fd74851d50047e65347fa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 13:50:41 -0800 Subject: [PATCH 118/162] fix(server): a dropped dictation client frees the speech engine within seconds (#41075) --- apps/server/src/speech/stream.test.ts | 31 ++++++++++++++++++++++++ apps/server/src/speech/stream.ts | 35 +++++++++++++++++++++++---- 2 files changed, 61 insertions(+), 5 deletions(-) diff --git a/apps/server/src/speech/stream.test.ts b/apps/server/src/speech/stream.test.ts index 71d2fdca91310..7ce8b76dd15d2 100644 --- a/apps/server/src/speech/stream.test.ts +++ b/apps/server/src/speech/stream.test.ts @@ -1,9 +1,12 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import { it } from "@effect/vitest"; import { expect } from "vite-plus/test"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; +import * as Socket from "effect/socket/Socket"; +import * as TestClock from "effect/testing/TestClock"; import { HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http"; import { SpeechStreamEvent, DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS } from "@t3tools/contracts"; import type { SpeechService, SpeechStream } from "./SpeechService.ts"; @@ -167,3 +170,31 @@ it.live("processes pipelined audio before the finish command", () => { }, ).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)); }); + +it.effect("releases the stream when a started client goes silent", () => + Effect.gen(function* () { + const released = yield* Deferred.make(); + let pulls = 0; + const socket = Socket.make({ + reader: Effect.succeed({ + pull: Effect.suspend(() => + pulls++ === 0 + ? Effect.succeed([ + JSON.stringify({ type: "start", options: DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS }), + ] as const) + : Effect.never, + ), + upgrade: () => Effect.void, + }), + writer: Effect.succeed({ write: () => Effect.void, writeAll: () => Effect.void }), + }); + const stream: SpeechStream = { feed: () => Effect.never, finish: Effect.never }; + yield* runSpeechSocket(socket, { + startStream: () => + Effect.acquireRelease(Effect.succeed(stream), () => Deferred.succeed(released, undefined)), + }).pipe(Effect.scoped, Effect.forkChild); + + yield* TestClock.adjust("1 minute"); + expect(yield* Deferred.isDone(released)).toBe(true); + }), +); diff --git a/apps/server/src/speech/stream.ts b/apps/server/src/speech/stream.ts index 60d5acb2334e2..8eb9b9626010b 100644 --- a/apps/server/src/speech/stream.ts +++ b/apps/server/src/speech/stream.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; @@ -16,6 +17,10 @@ import * as Socket from "effect/socket/Socket"; import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as SpeechService from "./SpeechService.ts"; +// A recording client streams audio continuously; behind a proxy a vanished +// client never closes the server side, so silence is the only sign it is gone. +const SPEECH_SOCKET_IDLE_TIMEOUT = "15 seconds"; + const decodeCommand = Schema.decodeUnknownEffect(Schema.fromJsonString(SpeechStreamCommand)); /** One socket owns one stream. Audio is processed and acknowledged in arrival order. */ @@ -68,18 +73,38 @@ export const runSpeechSocket = Effect.fn("speech.runSocket")(function* ( ); }; const reader = yield* socket.reader; - yield* Effect.gen(function* () { + // Silence only counts while every received frame has been answered. + let unanswered = 0; + const activity = yield* Queue.sliding(1); + const idle = Effect.gen(function* () { + while (true) { + const heard = yield* Queue.take(activity).pipe( + Effect.timeoutOption(SPEECH_SOCKET_IDLE_TIMEOUT), + ); + if (Option.isNone(heard) && unanswered === 0) return; + } + }); + const read = Effect.gen(function* () { const pending = yield* Queue.bounded(2); - yield* Effect.forever(Queue.take(pending).pipe(Effect.flatMap(receive))).pipe( - Effect.forkScoped, - ); + yield* Effect.forever( + Queue.take(pending).pipe( + Effect.flatMap(receive), + Effect.andThen(() => { + unanswered--; + return Queue.offer(activity, undefined); + }), + ), + ).pipe(Effect.forkScoped); while (true) { const frames = yield* reader.pull; + unanswered += frames.length; + yield* Queue.offer(activity, undefined); yield* Effect.forEach(frames, (frame) => Queue.offer(pending, frame), { discard: true, }); } - }).pipe( + }); + yield* Effect.raceFirst(read, idle).pipe( Effect.timeoutOrElse({ duration: "10 minutes", // The socket read loop is already interrupted here; its writer can no longer send. From 0938476b95fa28f6d626144d6a34b0e20d1dd595 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 14:17:38 -0800 Subject: [PATCH 119/162] fix(web): Thinking row no longer shows below a streaming reply (#41060) --- apps/mobile/src/lib/threadActivity.test.ts | 11 +++++++- apps/mobile/src/lib/threadActivity.ts | 6 +++++ .../chat/MessagesTimeline.logic.test.ts | 26 +++++++++++++++++-- .../components/chat/MessagesTimeline.logic.ts | 6 +++++ 4 files changed, 46 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 3a4f54c59c41b..8d66dfaf5c520 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -1483,7 +1483,7 @@ describe("buildThreadFeed", () => { expect(presented.some((entry) => entry.type === "thinking")).toBe(false); }); - it("does not show Thinking once the open run's provider turn has ended", () => { + it("does not show Thinking once the provider turn has ended or its reply is streaming", () => { const startedAt = "2026-04-01T00:00:01.000Z"; const run = { runId, status: "running" as const, startedAt, completedAt: null }; expect( @@ -1495,6 +1495,15 @@ describe("buildThreadFeed", () => { startedAt, ).map((row) => row.type), ).toEqual(["run-fold"]); + const streamingReply = buildThreadFeed([ + projected(userMessage(), 0), + projected({ ...assistantMessage(), streaming: true }, 1), + ]); + expect( + deriveThreadFeedPresentation(streamingReply, run, new Set(), new Set(), startedAt).map( + (row) => row.type, + ), + ).toEqual(["message", "run-fold", "message"]); }); it("hides tool calls or everything but the final answer", () => { const at = (second: number) => `2026-06-20T00:00:${String(second).padStart(2, "0")}.000Z`; diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 4bff1af9e3750..1760b37b49606 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -1957,10 +1957,16 @@ export function deriveThreadFeedPresentation( } } if (liveFold !== null && !liveFoldPlaced) result.push(liveFold); + const latestRow = result.at(-1); + const replyIsStreaming = + latestRow?.type === "message" && + latestRow.message.role === "assistant" && + latestRow.message.streaming; if ( isWorking && activeWorkStartedAt !== null && latestRun?.turnEnded !== true && + !replyIsStreaming && (activeRunId === null || !compactionCommandRunIds.has(activeRunId)) && !result.some( (row) => diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 76dc0aa6471bf..f1726cbbb92b2 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1785,7 +1785,7 @@ describe("deriveMessagesTimelineRows", () => { expect(rows.at(-1)).toMatchObject({ kind: "thinking" }); }); - it("does not show Thinking once the open run's provider turn has ended", () => { + it("does not show Thinking once the provider turn has ended or its reply is streaming", () => { const input = { timelineEntries: [ { @@ -1821,6 +1821,29 @@ describe("deriveMessagesTimelineRows", () => { latestRun: { ...input.latestRun, turnEnded: true }, }); expect(ended.some((row) => row.kind === "thinking")).toBe(false); + + const streamingReply = deriveMessagesTimelineRows({ + ...input, + timelineEntries: [ + ...input.timelineEntries, + { + id: "assistant-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:05Z", + message: { + id: "assistant" as never, + role: "assistant" as const, + text: "Here is the first paragraph of the answer", + runId: "turn-1" as never, + createdAt: "2026-01-01T00:00:05Z", + updatedAt: "2026-01-01T00:00:06Z", + streaming: true, + }, + }, + ], + }); + expect(streamingReply.at(-1)?.id).toBe("assistant-entry"); + expect(streamingReply.some((row) => row.kind === "thinking")).toBe(false); }); it("keeps a promptless restart in one active visual response", () => { @@ -4548,7 +4571,6 @@ it("keeps the working header in place across worktree setup handoff", () => { "worktree-setup", "working", "message", - "thinking", ]); const stage = (id: "agent" | "setup-script", status: "done" | "running") => diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 2d920ad816277..6bd30f1ac3212 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -2383,6 +2383,11 @@ export function deriveMessagesTimelineRows( } } + const latestTimelineEntry = timelineEntries.at(-1); + const replyIsStreaming = + latestTimelineEntry?.kind === "message" && + latestTimelineEntry.message.role === "assistant" && + latestTimelineEntry.message.streaming; const hasWorkingRow = nextRows.some((row) => row.kind === "working"); if (input.isWorking && !hasWorkingRow && activeTurnHeaderIndex === timelineEntries.length) { appendWorkingRow(); @@ -2390,6 +2395,7 @@ export function deriveMessagesTimelineRows( if ( input.isWorking && input.latestRun?.turnEnded !== true && + !replyIsStreaming && !setupOwnsWorkingSlot && !hasActiveCompaction && !compactionOnlyRunFinished && From 7103527dccfaecbd1e1478155297cce9adc937ce Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 14:24:15 -0800 Subject: [PATCH 120/162] fix(web): PR description file links resolve in the PR's repository from a No-project thread (#41073) --- .../components/ChatMarkdown.browser.test.tsx | 33 +++++++++++++++++++ apps/web/src/components/ChatMarkdown.tsx | 18 +++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index faca71b4a101f..b0aa293812d6d 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -90,6 +90,17 @@ vi.mock(import("../state/filesystem"), async (original) => { : actual.useFilesystemReadAccess(environmentId)) as never, }; }); +const threadWorktrees = vi.hoisted(() => new Map()); +vi.mock(import("../state/entities"), async (original) => { + const actual = await original(); + return { + ...actual, + readThreadShell: ((ref: { threadId: string }) => { + const worktreePath = threadWorktrees.get(ref.threadId); + return worktreePath === undefined ? actual.readThreadShell(ref as never) : { worktreePath }; + }) as never, + }; +}); vi.mock(import("../remoteOpen"), async (original) => ({ ...(await original()), useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never, @@ -170,6 +181,7 @@ function setup() { parsedSources.length = 0; settingsOverrides.mathRenderingEnabled = false; renderDiagram.mockReset(); + threadWorktrees.clear(); workspaceSearch.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] })); filesystemMetadata.mockReset().mockResolvedValue(AsyncResult.success({ entries: [null] })); } @@ -559,6 +571,27 @@ describe("ChatMarkdown workspace file opens", () => { expect(workspaceSearch).toHaveBeenCalledOnce(); }); + it("opens a path from markdown rendered in another checkout under that checkout", async () => { + setup(); + const scratchThread = { ...threadRef, threadId: ThreadId.make("scratch-thread") }; + threadWorktrees.set(scratchThread.threadId, "/scratch/thread"); + filesystemMetadata.mockResolvedValue(AsyncResult.success({ entries: [{ kind: "file" }] })); + using openFile = vi.spyOn(useRightPanelStore.getState(), "openFile"); + await using screen = await renderText("[State](packages/state/filesystem.ts)", { + cwd: "/repo-a", + threadRef: scratchThread, + }); + await act(async () => screen.container.querySelector("a")!.click()); + + await vi.waitFor(() => + expect(openFile).toHaveBeenCalledExactlyOnceWith( + scratchThread, + "/repo-a/packages/state/filesystem.ts", + undefined, + ), + ); + }); + it.each([ ["its own panel", "thread-own-panel", false], ["its parent's panel from a side chat", "thread-side-chat", true], diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 2edc4be1febcd..f5f69e063a967 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -942,8 +942,24 @@ function useChatMarkdownState( }; const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => { if (!threadRef) return; + // The panel reads relative paths from the thread's folder. A pull request body's `cwd` is the + // checkout of its repository, which can be another folder. + const shell = readThreadShell(threadRef); + const panelRoot = + shell?.worktreePath ?? + projects.find( + (project) => project.environmentId === environmentId && project.id === shell?.projectId, + )?.workspaceRoot; const openAt = (path: string) => - useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line); + useRightPanelStore + .getState() + .openFile( + threadRef, + cwd && panelRoot !== undefined && cwd !== panelRoot + ? resolveWorkspaceFilePath(path, cwd) + : path, + fileLinkMeta.line, + ); if ( fileLinkMeta.workspaceLookupPath === null || !cwd || From 44979a58756544d3d77324ee5eeb2fc1485b3aed Mon Sep 17 00:00:00 2001 From: SSH Date: Sun, 22 Nov 2026 17:38:52 -0500 Subject: [PATCH 121/162] fix(mcp): keep deleted schedules from returning on edit (#41084) Co-authored-by: Julius Marminge --- .../OrchestratorMcpService.schedules.test.ts | 91 +++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 1 + packages/contracts/src/scheduledTask.ts | 3 +- 3 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/mcp/OrchestratorMcpService.schedules.test.ts diff --git a/apps/server/src/mcp/OrchestratorMcpService.schedules.test.ts b/apps/server/src/mcp/OrchestratorMcpService.schedules.test.ts new file mode 100644 index 0000000000000..a24d8e740d49d --- /dev/null +++ b/apps/server/src/mcp/OrchestratorMcpService.schedules.test.ts @@ -0,0 +1,91 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { EnvironmentId, ProjectId, ProviderInstanceId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ProviderAdapters from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as Launch from "../orchestration-v2/ThreadLaunchService.ts"; +import * as Threads from "../orchestration-v2/ThreadManagementService.ts"; +import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; +import * as Sqlite from "../persistence/Sqlite.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; +import * as Projects from "../project/ProjectService.ts"; +import * as Providers from "../provider/ProviderRegistry.ts"; +import * as Schedules from "../scheduledTasks/ScheduledTaskService.ts"; +import * as Scheduler from "../scheduling/Scheduler.ts"; +import * as Secrets from "../secrets/SecretRequests.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as Git from "../vcs/GitVcsDriver.ts"; +import type { McpInvocationScope } from "./McpInvocationContext.ts"; +import * as Mcp from "./OrchestratorMcpService.ts"; + +const dependencies = Layer.mergeAll( + NodeCrypto.layer, + NodeServices.layer, + Sqlite.layerMemory, + ServerSettings.layerTest(), + ManagedPolicy.layerTest(), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + Layer.mock(Projects.ProjectService)({}), + Layer.mock(Providers.ProviderRegistry)({}), + Layer.mock(ProviderAdapters.ProviderAdapterRegistryV2)({}), + Layer.mock(Threads.ThreadManagementService)({}), + Layer.mock(Launch.ThreadLaunchService)({}), + Layer.mock(Git.GitVcsDriver)({}), + Layer.mock(Secrets.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(Scheduler.Scheduler)({ register: () => Effect.void }), +); + +const client: McpInvocationScope = { + environmentId: EnvironmentId.make("schedule-test"), + requestNamespace: "client", + thread: undefined, + client: { sessionId: "client", label: "Test", access: "full-access" }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, +}; + +const fixture = Effect.gen(function* () { + const schedules = yield* Schedules.ScheduledTaskService; + const { task } = yield* schedules.upsert({ + title: "Scheduled review", + prompt: "Review", + projectId: ProjectId.make("project"), + schedule: { type: "interval", everyMs: 60_000 }, + enabled: true, + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + return { schedules, id: task.id }; +}); + +const layer = Schedules.layer.pipe(Layer.provideMerge(dependencies)); + +it.effect("an MCP edit cannot recreate a concurrently deleted schedule", () => + Effect.gen(function* () { + const { schedules, id } = yield* fixture; + const editing = { + ...schedules, + list: () => schedules.list().pipe(Effect.tap(() => schedules.delete({ id }))), + }; + const result = yield* Mcp.OrchestratorMcpService.pipe( + Effect.flatMap((mcp) => + mcp.updateScheduledTask(client, { scheduledTaskId: id, enabled: false }), + ), + Effect.provide(Mcp.layer), + Effect.provideService(Schedules.ScheduledTaskService, editing), + Effect.result, + ); + expect((yield* schedules.list()).tasks).toEqual([]); + expect(result._tag).toBe("Failure"); + }).pipe(Effect.provide(layer)), +); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index f13623c232838..4278c6bcf95b6 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2525,6 +2525,7 @@ const make = Effect.gen(function* () { : yield* scheduledTaskWorkspaceStrategy(threadId !== null, existing.projectId); const upsertInput: ScheduledTaskUpsertInput = { id: existing.id, + requireExisting: true, title: input.title ?? existing.title, prompt: input.prompt ?? existing.prompt, enabled: input.enabled ?? existing.enabled, diff --git a/packages/contracts/src/scheduledTask.ts b/packages/contracts/src/scheduledTask.ts index 33b24ed6dfa08..ba1f21c19c25a 100644 --- a/packages/contracts/src/scheduledTask.ts +++ b/packages/contracts/src/scheduledTask.ts @@ -279,7 +279,8 @@ export type ScheduledTaskListResult = typeof ScheduledTaskListResult.Type; export const ScheduledTaskUpsertInput = Schema.Struct({ id: Schema.optional(ScheduledTaskId), requireExisting: Schema.optional(Schema.Boolean).annotate({ - description: "Reject the save if the task no longer exists, for edits from a client form.", + description: + "Reject the save if the task no longer exists, for edits based on an earlier read.", }), commandId: Schema.optional(CommandId), title: TrimmedNonEmptyString, From a09738fb435120d08707db0142ca55b3b7b5c7ec Mon Sep 17 00:00:00 2001 From: SSH Date: Sun, 22 Nov 2026 17:46:37 -0500 Subject: [PATCH 122/162] fix(claude): start the updated Claude Code CLI when a thread changes model (#41086) Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 143 ++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 48 +++++- .../provider/Drivers/ClaudeExecutable.test.ts | 52 ++++++- .../src/provider/Drivers/ClaudeExecutable.ts | 30 ++++ 4 files changed, 264 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 139261b280535..62139c5a91fdc 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -8464,6 +8464,149 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + describe("a model change after a Claude Code update", () => { + /** An install as the Claude installer lays it out: one file per version and a link. */ + const makeInstall = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-program-" }); + const link = NodePath.join(root, "claude"); + const install = (version: string) => { + const file = NodePath.join(root, version); + NodeFS.writeFileSync(file, "#!/bin/sh\n", { mode: 0o755 }); + NodeFS.rmSync(link, { force: true }); + NodeFS.symlinkSync(file, link); + }; + install("1.0.0"); + return { + settings: { ...DEFAULT_CLAUDE_SETTINGS, binaryPath: link }, + update: () => install("1.0.1"), + }; + }); + const opus = { + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + model: "claude-opus-5-5", + } satisfies ModelSelection; + const sonnet = { ...opus, model: "claude-sonnet-4-6" } satisfies ModelSelection; + + it.effect("starts the new version, and only for the model change", () => + Effect.scoped( + Effect.gen(function* () { + const install = yield* makeInstall; + const harness = yield* makeWakeHarnessWithOptions({ + settings: install.settings, + close: (messages) => Queue.shutdown(messages), + freshQueueOnReopen: true, + }); + const now = yield* DateTime.now; + const turn = (ordinal: number, modelSelection: ModelSelection) => + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`attempt-updated-cli:${ordinal}`), + text: `Request ${ordinal}`, + attachments: [], + providerTurnOrdinal: ordinal, + modelSelection, + }); + const settle = Effect.gen(function* () { + yield* harness.offerAndWait(turnOneResult); + yield* Queue.take(harness.terminalReceipts); + }); + yield* harness.runtime.startTurn(turn(1, opus)); + yield* settle; + + // The update alone restarts nothing. + install.update(); + yield* harness.runtime.startTurn(turn(2, opus)); + yield* settle; + assert.lengthOf(harness.processQueues, 1); + + yield* harness.runtime.startTurn(turn(3, sonnet)); + assert.lengthOf(harness.processQueues, 2); + assert.equal(harness.getOpenedOptions()?.model, "claude-sonnet-4-6"); + assert.deepEqual(harness.liveSelectionChanges, []); + assert.lengthOf(harness.offeredMessages, 3); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + + it.effect("keeps a process that runs background work until that work ends", () => + Effect.scoped( + Effect.gen(function* () { + const install = yield* makeInstall; + const harness = yield* makeWakeHarnessWithOptions({ + settings: install.settings, + close: (messages) => Queue.shutdown(messages), + freshQueueOnReopen: true, + }); + const now = yield* DateTime.now; + const turn = (ordinal: number, modelSelection: ModelSelection) => + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`attempt-updated-cli-background:${ordinal}`), + text: `Request ${ordinal}`, + attachments: [], + providerTurnOrdinal: ordinal, + modelSelection, + }); + const settle = Effect.gen(function* () { + yield* harness.offerAndWait(turnOneResult); + yield* Queue.take(harness.terminalReceipts); + }); + yield* harness.runtime.startTurn(turn(1, opus)); + const originalOptions = harness.getOpenedOptions(); + yield* harness.offerAndWait(wakeTaskStarted); + yield* settle; + assert.isTrue(yield* harness.hasPendingBackgroundWork); + + install.update(); + yield* harness.runtime.startTurn(turn(2, sonnet)); + yield* settle; + assert.deepEqual(harness.liveSelectionChanges[0], { model: "claude-sonnet-4-6" }); + assert.strictEqual(harness.getOpenedOptions(), originalOptions); + assert.lengthOf(harness.processQueues, 1); + + // The background shell ended: the next turn starts the new version. + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [], + uuid: "00000000-0000-4000-8000-000000000520", + session_id: WAKE_NATIVE_SESSION, + }), + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + yield* harness.runtime.startTurn(turn(3, sonnet)); + assert.lengthOf(harness.processQueues, 2); + assert.equal(harness.getOpenedOptions()?.model, "claude-sonnet-4-6"); + assert.lengthOf(harness.offeredMessages, 3); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + }); + // regression: #17270 root text_delta frames stream the reply before the block's snapshot it.effect("streams Claude assistant text deltas before the completed snapshot", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 196d82b3aa5c0..30243178fce41 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -167,7 +167,11 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { snapshotMcpApp } from "../../mcpApps/McpAppSnapshot.ts"; -import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts"; +import { + claudeProgramReader, + claudeProgramWasReplaced, + resolveClaudeSdkExecutablePath, +} from "../../provider/Drivers/ClaudeExecutable.ts"; import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts"; import { planClaudeSkillDispatch, @@ -5322,6 +5326,8 @@ interface ClaudeLiveQueryContext { readonly query: ClaudeAgentSdkQuerySession; readonly queryPolicyKey: string; selection: CompiledClaudeModelSelection; + readonly program: string | undefined; + readonly startedWithApiModelId: string; readonly closed: Deferred.Deferred; lastTurn: ActiveClaudeTurnContext | null; // "early" echoes on the first frame; "acknowledged" confirms uuid acceptance, but resume turns can still precede the prompt. @@ -6032,6 +6038,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( model: input.modelSelection.model, now, }); + const readProgram = yield* claudeProgramReader( + adapterOptions.settings.binaryPath, + adapterOptions.environment, + ); const events = yield* Queue.unbounded(); const activeTurn = yield* Ref.make(null); const taskOutputTails = new Map< @@ -13205,7 +13215,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( launchArgSettings, ); let compiledSelection = compileClaudeModelSelection(turnInput.modelSelection, catalog); + // Once an update replaces the running CLI, a model other than the one + // it started with moves to the new CLI unless background work is active. + const startsUpdatedProgram = + !turnInput.resume && + existing !== null && + existing.nativeThreadId === nativeThreadId && + existing.queryPolicyKey === queryPolicyKey && + !existing.stopping && + existing.startedWithApiModelId !== compiledSelection.apiModelId && + claudeProgramWasReplaced(existing.program, yield* readProgram) && + !(yield* liveProcessRunsBackgroundWork(existing)); if ( + !startsUpdatedProgram && !turnInput.resume && existing !== null && existing.nativeThreadId === nativeThreadId && @@ -13219,6 +13241,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* applySelectionLive(existing, compiledSelection); } if ( + !startsUpdatedProgram && !turnInput.resume && existing !== null && existing.nativeThreadId === nativeThreadId && @@ -13352,14 +13375,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const resolvedTurnCwd = yield* fileSystem .realPath(turnInput.runtimePolicy.cwd ?? ".") .pipe(Effect.orElseSucceed(() => turnInput.runtimePolicy.cwd)); - const openQueryRuntime = queryRunner.open({ - threadId: turnInput.threadId, - providerSessionId: input.providerSessionId, - options: queryOptions, - ...(turnInput.resume ? { resume: true } : {}), - }); + // Read right before opening so an update during startup counts too. + const openQueryRuntime = readProgram.pipe( + Effect.flatMap((program) => + queryRunner + .open({ + threadId: turnInput.threadId, + providerSessionId: input.providerSessionId, + options: queryOptions, + ...(turnInput.resume ? { resume: true } : {}), + }) + .pipe(Effect.map((querySession) => ({ program, querySession }))), + ), + ); // The SDK spawns the CLI per turn, so only the open waits for a provider update. - const querySession = yield* ( + const { program, querySession } = yield* ( adapterOptions.installationGate === undefined ? openQueryRuntime : adapterOptions.installationGate.execute(adapterOptions.instanceId, openQueryRuntime) @@ -13401,6 +13431,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( query: querySession, queryPolicyKey, selection: compiledSelection, + program, + startedWithApiModelId: compiledSelection.apiModelId, closed, lastTurn: null, promptEchoMode: "unknown", diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts index 36d7e3f3313fc..205f4610759da 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts @@ -1,9 +1,20 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; +import * as FileSystem from "effect/FileSystem"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as Effect from "effect/Effect"; -import { ClaudeExecutableFileCheck, resolveClaudeSdkExecutablePath } from "./ClaudeExecutable.ts"; +import { + ClaudeExecutableFileCheck, + claudeProgramReader, + claudeProgramWasReplaced, + resolveClaudeSdkExecutablePath, +} from "./ClaudeExecutable.ts"; const NPM_DIR = "C:\\Users\\dev\\AppData\\Roaming\\npm"; const NPM_SHIM = `${NPM_DIR}\\claude.cmd`; @@ -101,3 +112,42 @@ describe("resolveClaudeSdkExecutablePath", () => { }), ); }); + +describe("claudeProgramReader", () => { + /** An install as the Claude installer lays it out: one file per version and a link. */ + const makeInstall = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-program-" }); + const bin = NodePath.join(root, "bin"); + const link = NodePath.join(bin, "claude"); + const version = (name: string) => { + const file = NodePath.join(root, "versions", name); + NodeFS.mkdirSync(NodePath.dirname(file), { recursive: true }); + NodeFS.writeFileSync(file, "#!/bin/sh\n", { mode: 0o755 }); + return file; + }; + NodeFS.mkdirSync(bin); + NodeFS.symlinkSync(version("1.0.0"), link); + return { + bin, + update: () => { + NodeFS.unlinkSync(link); + NodeFS.symlinkSync(version("1.0.1"), link); + }, + }; + }); + + it.effect("follows a bare command name through PATH", () => + Effect.scoped( + Effect.gen(function* () { + const { bin, update } = yield* makeInstall; + const readProgram = yield* claudeProgramReader("claude", { PATH: bin }); + const startedFrom = yield* readProgram; + expect(startedFrom).toBeDefined(); + expect(claudeProgramWasReplaced(startedFrom, yield* readProgram)).toBe(false); + update(); + expect(claudeProgramWasReplaced(startedFrom, yield* readProgram)).toBe(true); + }), + ).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.ts index 6f4e85812f0cc..3de63c9372f4e 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.ts @@ -73,3 +73,33 @@ export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecuta return binaryPath; }, ); + +/** + * Returns an effect reading the real path of the installed Claude binary. + * Updates repoint the installed link to a new version file, so comparing this + * detects when a live CLI process was started from an older version. + */ +export const claudeProgramReader = Effect.fn("claudeProgramReader")(function* ( + binaryPath: string, + environment: NodeJS.ProcessEnv, +): Effect.fn.Return> { + const platform = yield* HostProcess.Platform; + const resolveExecutable = yield* SpawnExecutableResolution; + return Effect.promise(async () => { + try { + const resolved = await resolveExecutable(binaryPath, platform, environment); + return resolved === undefined ? undefined : await NodeFS.promises.realpath(resolved); + } catch { + return undefined; + } + }); +}); + +/** + * Reports whether an update replaced the program a live CLI process started + * from. An unreadable path on either side reports no update. + */ +export const claudeProgramWasReplaced = ( + startedFrom: string | undefined, + now: string | undefined, +): boolean => startedFrom !== undefined && now !== undefined && startedFrom !== now; From fb4558d77d0437a056bdd1604a48b47b3f5db069 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 15:04:00 -0800 Subject: [PATCH 123/162] fix(web,mobile,server): large files load in full without freezing the file preview (#40631) --- .../features/files/FileMarkdownPreview.tsx | 119 ++++--- .../features/files/ThreadFilesRouteScreen.tsx | 74 +++-- .../src/features/files/useFullFileText.ts | 66 ++++ apps/server/src/assets/AssetAccess.test.ts | 33 +- apps/server/src/assets/AssetAccess.ts | 6 +- .../AttachmentFilePreview.browser.test.tsx | 6 + .../src/components/files/ChunkedMarkdown.tsx | 106 +++++++ .../components/files/FileMarkdownPreview.tsx | 3 +- .../files/FilePreviewPanel.browser.test.tsx | 25 +- .../src/components/files/FilePreviewPanel.tsx | 297 +++++++++++------- .../src/components/files/LargeFilePreview.tsx | 125 ++++++++ .../src/components/files/LargeTextViewer.tsx | 116 ++++--- .../files/ReadOnlySourcePreview.tsx | 8 +- .../src/components/files/fullFileText.test.ts | 36 +++ apps/web/src/components/files/fullFileText.ts | 90 ++++++ .../src/components/files/largeTextProtocol.ts | 6 + apps/web/src/i18n/translations/de.json | 4 +- apps/web/src/i18n/translations/en.json | 4 +- apps/web/src/i18n/translations/es.json | 4 +- apps/web/src/i18n/translations/fr.json | 4 +- apps/web/src/i18n/translations/ja.json | 4 +- apps/web/src/i18n/translations/ko.json | 4 +- apps/web/src/i18n/translations/pt-BR.json | 4 +- apps/web/src/i18n/translations/ru.json | 4 +- apps/web/src/i18n/translations/sv.json | 4 +- apps/web/src/i18n/translations/zh.json | 4 +- packages/contracts/src/assets.ts | 1 + packages/shared/package.json | 4 + packages/shared/src/markdownChunks.test.ts | 132 ++++++++ packages/shared/src/markdownChunks.ts | 130 ++++++++ 30 files changed, 1152 insertions(+), 271 deletions(-) create mode 100644 apps/mobile/src/features/files/useFullFileText.ts create mode 100644 apps/web/src/components/files/ChunkedMarkdown.tsx create mode 100644 apps/web/src/components/files/LargeFilePreview.tsx create mode 100644 apps/web/src/components/files/fullFileText.test.ts create mode 100644 apps/web/src/components/files/fullFileText.ts create mode 100644 packages/shared/src/markdownChunks.test.ts create mode 100644 packages/shared/src/markdownChunks.ts diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsx index 086fb2abec598..23035511a5c2d 100644 --- a/apps/mobile/src/features/files/FileMarkdownPreview.tsx +++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx @@ -6,7 +6,14 @@ import { maskMarkdownFrontmatter } from "@t3tools/shared/markdownFrontmatter"; import { useGT } from "gt-react-native"; import { useState } from "react"; import { StackActions, useNavigation } from "@react-navigation/native"; -import { ScrollView, View } from "react-native"; +import { View } from "react-native"; +import { LegendList } from "@legendapp/list/react-native"; +import { + LARGE_MARKDOWN_CHUNK_MAX_CHARS, + splitMarkdown, + withMarkdownDefinitions, +} from "@t3tools/shared/markdownChunks"; +import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { RefreshControl } from "../../components/ui/RefreshControl"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; @@ -35,6 +42,7 @@ import { type NativeMarkdownTextStyle, } from "../../native/SelectableMarkdownText"; import { fileRoutePathSegments, resolveWorkspaceFilePath } from "./filePath"; +import { SourceFileSurface } from "./SourceFileSurface"; interface MarkdownPreviewStyles { readonly nativeTextStyle: NativeMarkdownTextStyle; @@ -223,44 +231,77 @@ export function FileMarkdownPreview(props: { if (!openMedia(href)) void tryOpenExternalUrl(href, "markdown-link"); }; - return ( - void handlePullToRefresh()} - /> - ) : undefined + const refreshControl = props.onRefresh ? ( + void handlePullToRefresh()} /> + ) : undefined; + const renderMarkdown = (markdown: string) => ( + + markdownFileEmbedLabel( + href, + { + environmentId: props.environmentId, + threadId: props.threadId ?? undefined, + workspaceRoot: markdownDirectory, + captured: props.captured, + }, + false, + ) } - > - - - markdownFileEmbedLabel( - href, - { - environmentId: props.environmentId, - threadId: props.threadId ?? undefined, - workspaceRoot: markdownDirectory, - captured: props.captured, - }, - false, - ) - } - onLinkPress={onLinkPress} - renderImage={renderImage} - resolveImageSource={resolveImageSource} - onImagePress={onImagePress} - textStyle={styles.nativeTextStyle} - /> - setExpandedFile(null)} /> - setExpandedVideo(null)} /> - - + onLinkPress={onLinkPress} + renderImage={renderImage} + resolveImageSource={resolveImageSource} + onImagePress={onImagePress} + textStyle={styles.nativeTextStyle} + /> + ); + const modals = ( + <> + setExpandedFile(null)} /> + setExpandedVideo(null)} /> + + ); + const markdown = maskMarkdownFrontmatter(props.markdown); + + // Only chunks near the viewport mount, so only they pay for the JS rewrites and native parse. + const { chunks, definitions } = splitMarkdown(markdown); + if (chunks.some((chunk) => chunk.text.length > LARGE_MARKDOWN_CHUNK_MAX_CHARS)) { + return ( + + ); + } + return ( + + String(index)} + estimatedItemSize={ + (styles.nativeTextStyle.lineHeight * + chunks.reduce((lines, chunk) => lines + chunk.lines, 0)) / + chunks.length + } + recycleItems={false} + contentContainerStyle={{ paddingHorizontal: 18, paddingVertical: 18 }} + ItemSeparatorComponent={ChunkSeparator} + renderItem={({ item }) => ( + + {renderMarkdown(withMarkdownDefinitions(item.text, definitions))} + + )} + /> + {modals} + ); } + +function ChunkSeparator() { + return ; +} diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx index 17d7f3e8d17ca..7661a4b547cb8 100644 --- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx +++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx @@ -74,6 +74,7 @@ import { needsWorkspaceFileContents, } from "./filePath"; import { useWorkspaceFileAssetUrlState } from "./workspaceFileAssetUrl"; +import { MOBILE_FULL_FILE_MAX_BYTES, useFullFileText } from "./useFullFileText"; function FilesBrowserHeader(props: { readonly projectName: string; @@ -253,6 +254,7 @@ function FileContent(props: { readonly threadId: ThreadId | null; readonly initialLine: number | null; readonly truncated: boolean; + /** Renders Markdown in lazily parsed chunks; set for files past the 1 MB preview. */ readonly selectable: boolean; readonly onRefresh?: () => Promise | void; }) { @@ -703,6 +705,38 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { : defaultViewMode(relativePath); const resolvedActiveMode = isVideoFile || isAudioFile ? "preview" : canPreview ? activeMode : "source"; + // Metadata is needed only to distinguish directories; file contents can load concurrently. + const needsFileContents = needsWorkspaceFileContents({ + relativePath, + metadataKind: metadata.data?.kind, + activeMode: resolvedActiveMode, + }); + const fileQuery = useEnvironmentQuery( + canReadFiles && + environmentId !== null && + cwd !== null && + relativePath !== null && + needsFileContents + ? projectEnvironment.readFile({ + environmentId, + input: { cwd, relativePath }, + }) + : null, + ); + const fileData = fileQuery.data as ProjectReadFileResult | null; + const [fileRefreshCount, setFileRefreshCount] = useState(0); + const fullText = useFullFileText({ + environmentId, + threadId, + absolutePath: + fileData?.truncated === true && fileData.byteLength <= MOBILE_FULL_FILE_MAX_BYTES + ? targetPath + : null, + revision: `${fileData?.byteLength ?? 0}:${fileRefreshCount}`, + }); + // Until the full text arrives, the 1 MB preview shows with its partial-file notice. + const fileContents = fullText ?? fileData?.contents ?? null; + const fileTruncated = fileData?.truncated === true && fullText === null; const assetPreviewPath = !metadataPending && directoryPath === null && @@ -758,28 +792,13 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { const handleRetryPreview = () => { void assetPreview.refresh().finally(() => setPreviewRevision((current) => current + 1)); }; - // Metadata is needed only to distinguish directories; file contents can load concurrently. - const needsFileContents = needsWorkspaceFileContents({ - relativePath, - metadataKind: metadata.data?.kind, - activeMode: resolvedActiveMode, - }); - const fileQuery = useEnvironmentQuery( - canReadFiles && - environmentId !== null && - cwd !== null && - relativePath !== null && - needsFileContents - ? projectEnvironment.readFile({ - environmentId, - input: { cwd, relativePath }, - }) - : null, - ); - const fileData = fileQuery.data as ProjectReadFileResult | null; // iOS only: Android lays out a whole-file selectable TextView on the UI thread, which stalls. const canSelectText = - Platform.OS === "ios" && resolvedActiveMode === "source" && fileData?.contents != null; + Platform.OS === "ios" && + resolvedActiveMode === "source" && + fileContents !== null && + // One selectable view lays out the whole text; past the 1 MB preview that stalls. + fileContents.length <= 1024 * 1024; const selectingText = canSelectText && textSelectionPath === relativePath; const handleSelectFile = (path: string) => { @@ -906,13 +925,13 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { ), } as const, ]), - fileData?.contents != null + fileContents !== null ? ({ id: "copy-contents", - title: fileData.truncated ? gt("Copy preview") : gt("Copy contents"), + title: fileTruncated ? gt("Copy preview") : gt("Copy contents"), icon: "doc.on.doc", inline: false, - onPress: () => copyTextWithHaptic(fileData.contents), + onPress: () => copyTextWithHaptic(fileContents), } as const) : null, isPdfFile({ name: relativePath }) && previewUri !== null @@ -1083,14 +1102,17 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) { videoSource={videoSource} mediaSource={mediaSource} resolveVideoUri={assetPreview.refresh} - fileContents={fileData?.contents ?? null} + fileContents={fileContents} fileError={fileQuery.error} initialLine={targetLine} relativePath={relativePath} threadId={threadId} - truncated={fileData?.truncated ?? false} + truncated={fileTruncated} selectable={selectingText} - onRefresh={() => fileQuery.refresh()} + onRefresh={() => { + setFileRefreshCount((count) => count + 1); + return fileQuery.refresh(); + }} /> { + const [uri] = JSON.parse(key) as [string, string]; + return connectionAtomRuntime + .atom( + HttpClient.get(uri).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => { + // The file can grow after the preview read; never buffer past the cap. React Native's + // fetch buffers the whole body, so a response without a length is refused, not trusted. + const length = Number(response.headers["content-length"] ?? Number.NaN); + return Number.isFinite(length) && length <= MOBILE_FULL_FILE_MAX_BYTES + ? response.text + : Effect.succeed(null); + }), + Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }), + ), + ) + .pipe(Atom.withLabel(`full-file-text:${key}`)); +}); + +const noFullFileTextAtom = Atom.make(AsyncResult.success(null)); + +/** + * Downloads a thread file's full text past the 1 MB RPC preview; null while loading, after a + * failure, or when disabled. A new `revision` downloads it again. + */ +export function useFullFileText(input: { + readonly environmentId: EnvironmentId | null; + readonly threadId: ThreadId | null; + readonly absolutePath: string | null; + readonly revision: string; +}): string | null { + const { threadId, absolutePath } = input; + // Workspace-file URLs serve only previewable types; an attachment download serves any file. + const resource = useMemo( + () => + threadId === null || absolutePath === null + ? null + : { _tag: "media-file", threadId, path: absolutePath, disposition: "attachment" }, + [threadId, absolutePath], + ); + const assetUrl = useAssetUrlState(input.environmentId, resource, input.revision); + const uri = resource !== null && assetUrl._tag === "Success" ? assetUrl.url : null; + const result = useAtomValue( + uri === null ? noFullFileTextAtom : fullFileTextAtom(JSON.stringify([uri, input.revision])), + ); + // The caller keeps showing the 1 MB preview and its partial-file notice. + return AsyncResult.isSuccess(result) ? result.value : null; +} diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 990306faae438..64831512a9ef7 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -307,15 +307,28 @@ describe("AssetAccess", () => { "archive.zip", "no-extension", ]) { - for (const directory of [root, outside]) { + for (const [directory, draft] of [ + [root, false], + [outside, false], + [root, true], + [outside, true], + ] as const) { const filePath = path.join(directory, name); yield* fs.writeFileString(filePath, "shared file bytes"); - const resource = { - _tag: "media-file" as const, - threadId: ThreadId.make("thread-1"), - path: directory === root ? name : filePath, - disposition: "attachment" as const, - }; + const requested = directory === root ? name : filePath; + const resource = draft + ? { + _tag: "draft-workspace-file" as const, + cwd: root, + path: requested, + disposition: "attachment" as const, + } + : { + _tag: "media-file" as const, + threadId: ThreadId.make("thread-1"), + path: requested, + disposition: "attachment" as const, + }; const result = yield* issueAssetUrl({ resource, workspaceRoot: root }); const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); const separator = suffix.indexOf("/"); @@ -799,6 +812,12 @@ describe("AssetAccess", () => { }, { _tag: "media-file", threadId, path: config.dbPath }, { _tag: "draft-workspace-file", cwd: config.stateDir, path: "statev2.sqlite" }, + { + _tag: "draft-workspace-file", + cwd: config.stateDir, + path: "statev2.sqlite", + disposition: "attachment", + }, ] as const) { const error = yield* issueAssetUrl({ resource }).pipe(Effect.flip); expect(error._tag).toBe("AssetWorkspaceAssetNotFoundError"); diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 005ce9ebd3f5f..2b8f1029ae3a3 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -442,7 +442,8 @@ const finalizeAbsoluteMediaFileAsset = Effect.fn("AssetAccess.finalizeAbsoluteMe }); } const download = - input.resource._tag === "media-file" && input.resource.disposition === "attachment"; + (input.resource._tag === "media-file" || input.resource._tag === "draft-workspace-file") && + input.resource.disposition === "attachment"; if (!download && hostPreviewMimeTypeFromExtension(path.extname(canonicalFile)) === null) { return yield* new AssetPreviewTypeValidationError({ resource: input.resource }); } @@ -515,7 +516,8 @@ const finalizeWorkspaceFileAsset = Effect.fn("AssetAccess.finalizeWorkspaceFileA ); const isDraftMedia = input.resource._tag === "draft-workspace-file" && - (isWorkspaceAudioPreviewPath(resolved.relativePath) || + (input.resource.disposition === "attachment" || + isWorkspaceAudioPreviewPath(resolved.relativePath) || isWorkspaceVideoPreviewPath(resolved.relativePath)); if (!isDraftMedia && !isWorkspacePreviewEntryPath(resolved.relativePath)) { return yield* new AssetPreviewTypeValidationError({ diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 70eb4a3490b60..e96b165d5db0e 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -582,8 +582,14 @@ describe("large text preview recovery", () => { environmentId={EnvironmentId.make("test")} threadRef={{ environmentId: EnvironmentId.make("test"), threadId: ThreadId.make("test") }} absolutePath="/repo/large.txt" + draftCwd={null} name="large.txt" delimiter={null} + markdownCwd={null} + copyContents={{ current: null }} + preview="" + // Past the highlighted-source cap, so the worker-backed viewer under test renders. + sizeBytes={128 * 1024 * 1024} workspaceMutationId={mutation} revealLine={null} revealRequestId={0} diff --git a/apps/web/src/components/files/ChunkedMarkdown.tsx b/apps/web/src/components/files/ChunkedMarkdown.tsx new file mode 100644 index 0000000000000..2564e40389c96 --- /dev/null +++ b/apps/web/src/components/files/ChunkedMarkdown.tsx @@ -0,0 +1,106 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { LegendList } from "@legendapp/list/react"; +import type { KeyboardEventHandler } from "react"; + +import { Spinner } from "~/components/ui/spinner"; +import { FileMarkdownPreview } from "./FileMarkdownPreview"; +import { + LARGE_MARKDOWN_CHUNK_MAX_CHARS, + type MarkdownChunk, + withMarkdownDefinitions, +} from "@t3tools/shared/markdownChunks"; + +const ESTIMATED_LINE_PX = 24; + +interface ChunkItem { + readonly index: number; + readonly start: number; + readonly chunk: MarkdownChunk; +} + +/** Renders Markdown pieces in a virtualized list; task offsets are file offsets. */ +export function ChunkedMarkdown(props: { + readonly chunks: readonly MarkdownChunk[]; + /** Link definitions from the whole file, so references resolve across pieces. */ + readonly definitions: string; + /** Shows a spinner after the last chunk while more of the file streams in. */ + readonly loading?: boolean; + readonly cwd: string; + readonly relativePath: string; + readonly threadRef: ScopedThreadRef; + readonly workspaceMutationId: string | null; + readonly onKeyDown?: KeyboardEventHandler; + readonly onTaskListChange?: + | ((input: { readonly markerOffset: number; readonly checked: boolean }) => void) + | undefined; +}) { + const { chunks, onTaskListChange } = props; + const items: ChunkItem[] = []; + let start = 0; + let lines = 0; + for (const [index, chunk] of chunks.entries()) { + items.push({ index, start, chunk }); + lines += chunk.lines; + start += chunk.text.length + 1; + } + return ( +
    { + // Select All only reaches rendered pieces; copying all of it copies the whole file. + const list = event.currentTarget.firstElementChild; + if (!list || !window.getSelection()?.containsNode(list)) return; + event.preventDefault(); + event.clipboardData.setData("text/plain", chunks.map((chunk) => chunk.text).join("\n")); + }} + > + + data={items} + extraData={props.definitions} + keyExtractor={(item) => String(item.index)} + estimatedItemSize={(lines / Math.max(items.length, 1)) * ESTIMATED_LINE_PX} + drawDistance={800} + recycleItems={false} + className="h-full scrollbar-gutter-both" + contentContainerClassName="py-5" + ListFooterComponent={ + props.loading ? ( +
    + +
    + ) : null + } + renderItem={({ item }) => ( +
    + {item.chunk.text.length > LARGE_MARKDOWN_CHUNK_MAX_CHARS ? ( + // One block this long (a huge fence or HTML block) is too slow to parse. +
    +                {item.chunk.text}
    +              
    + ) : ( + + onTaskListChange({ + markerOffset: item.start + input.markerOffset, + checked: input.checked, + })) + } + /> + )} +
    + )} + /> +
    + ); +} diff --git a/apps/web/src/components/files/FileMarkdownPreview.tsx b/apps/web/src/components/files/FileMarkdownPreview.tsx index 19df3f6687058..a4b4957201792 100644 --- a/apps/web/src/components/files/FileMarkdownPreview.tsx +++ b/apps/web/src/components/files/FileMarkdownPreview.tsx @@ -10,6 +10,7 @@ export function FileMarkdownPreview(props: { readonly text: string; readonly threadRef: ScopedThreadRef; readonly workspaceMutationId: string | null; + readonly className?: string; readonly onTaskListChange?: | ((input: { readonly markerOffset: number; readonly checked: boolean }) => void) | undefined; @@ -30,7 +31,7 @@ export function FileMarkdownPreview(props: { imageBaseDir={imageBaseDir} threadRef={props.threadRef} workspaceMutationId={props.workspaceMutationId} - className="mx-auto max-w-4xl px-6 py-5" + className={props.className ?? "mx-auto max-w-4xl px-6 py-5"} onTaskListChange={props.onTaskListChange} /> ); diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx index 714e45bac76fb..07e05010baab3 100644 --- a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx @@ -562,17 +562,28 @@ describe("source file scroll", () => { }); describe("rendered Markdown task saves", () => { - it("keeps a truncated read read-only without queuing a replacement", async () => { + it("renders the whole file of a truncated read, read-only", async () => { using _settings = setup(); + state.assetUrl = { + _tag: "Success", + url: "/assets/tasks.md", + expiresAt: Number.MAX_SAFE_INTEGER, + }; + const realFetch = globalThis.fetch; + using _fetch = vi + .spyOn(globalThis, "fetch") + .mockImplementation((input, init) => + new URL(String(input), location.href).pathname === "/assets/tasks.md" + ? Promise.resolve( + new Response("- [ ] Keep the rest of this file\n\nPast the first megabyte\n"), + ) + : realFetch(input, init), + ); await using screen = await render(markdownPreview(true)); - using _timers = fakeTimers(); + await expect.element(screen.getByText("Past the first megabyte")).toBeVisible(); const checkbox = screen.container.querySelector('input[type="checkbox"]')!; - expect(checkbox).not.toBeNull(); expect(checkbox.disabled).toBe(true); - expect(checkbox.readOnly).toBe(true); await act(async () => checkbox.click()); - await vi.advanceTimersByTimeAsync(500); - expect(checkbox.checked).toBe(false); expect(state.optimistic).toBeNull(); expect(state.writeFile).not.toHaveBeenCalled(); }); @@ -580,6 +591,8 @@ describe("rendered Markdown task saves", () => { it("still toggles and saves tasks from a complete read", async () => { using _settings = setup(); await using screen = await render(markdownPreview(false)); + // The virtualized list mounts its pieces after measuring the viewport. + await expect.element(screen.getByRole("checkbox")).toBeInTheDocument(); using _timers = fakeTimers(); const checkbox = screen.container.querySelector('input[type="checkbox"]')!; expect(checkbox).not.toBeNull(); diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 2c27cfb8d80d1..dbb7f6ec0a33a 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -58,7 +58,9 @@ import { useEffectEvent, useRef, useState, + type ComponentProps, type KeyboardEvent as ReactKeyboardEvent, + type RefObject, } from "react"; import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview"; @@ -101,7 +103,8 @@ import FileBrowserPanel from "./FileBrowserPanel"; import { FileExplorerPane } from "./FileExplorerPane"; import { FileBreadcrumbs } from "./FileBreadcrumbs"; import { breadcrumbPathOf, retainedBreadcrumbTrail, trailChildOf } from "./filePath"; -import { FileMarkdownPreview } from "./FileMarkdownPreview"; +import { ChunkedMarkdown } from "./ChunkedMarkdown"; +import { splitMarkdown } from "@t3tools/shared/markdownChunks"; import { type FileCommentAnnotationEntry, type FileCommentAnnotationGroup, @@ -122,6 +125,8 @@ import { FileSurfaceLoading, } from "./fileSurfaceChrome"; import SourceFilePreview from "./ReadOnlySourcePreview"; +import LargeFilePreview from "./LargeFilePreview"; +import { FULL_TEXT_MAX_BYTES } from "./largeTextProtocol"; import { resolveCenteredFileLineScrollTop } from "./fileLineReveal"; import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation"; import { projectFileCacheKey } from "./fileContentRevision"; @@ -1218,30 +1223,27 @@ function RenderedMarkdownSurface({ }) { const saveTarget = { environmentId, cwd, relativePath }; useFileSaveSession(saveTarget, onPendingChange); + const onTaskListChange = readOnly + ? undefined + : ({ markerOffset, checked }: { readonly markerOffset: number; readonly checked: boolean }) => { + const currentContents = + getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ?? contents; + const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked); + if (nextContents === currentContents) return; + setProjectFileQueryData(environmentId, cwd, relativePath, nextContents); + changeFileSaveSession(saveTarget, nextContents); + }; return ( - - { - const currentContents = - getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ?? - contents; - const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked); - if (nextContents === currentContents) return; - setProjectFileQueryData(environmentId, cwd, relativePath, nextContents); - changeFileSaveSession(saveTarget, nextContents); - } - } - /> - + ); } @@ -1394,7 +1396,8 @@ export default function FilePreviewPanel({ const revealHandled = revealLine === null || (handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId); - const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled; + const markdownRenderable = isMarkdown && (file.data?.byteLength ?? 0) <= FULL_TEXT_MAX_BYTES; + const renderMarkdown = markdownRenderable && renderMarkdownPreferred && revealHandled; const renderMermaid = isMermaid && renderMermaidPreferred && revealHandled; const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled); const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled; @@ -1408,7 +1411,10 @@ export default function FilePreviewPanel({ ? ("html" as const) : null; const canToggleRendered = - previewPath !== null && attachment === undefined && renderedMode !== null; + previewPath !== null && + attachment === undefined && + renderedMode !== null && + (!isMarkdown || markdownRenderable); const showsRawText = previewPath !== null && file.data !== null && @@ -1439,6 +1445,15 @@ export default function FilePreviewPanel({ file.data.contents.length > 0 ? file.data.contents : null; + const showsLargeText = + previewPath !== null && + attachment === undefined && + !isMedia && + !renderBrowserFile && + !isDocument && + !renderMermaid && + file.data?.truncated === true; + const copyLargeText = useRef<(() => Promise) | null>(null); const { copyToClipboard, isCopied } = useCopyToClipboard({ target: namedClipboardTarget(previewPath ?? ""), onError: (error) => @@ -1680,6 +1695,16 @@ export default function FilePreviewPanel({ {isCopied ? : } ) : null} + {showsLargeText && absolutePath && relativePath ? ( + + ) : null} {canOpenInBrowser ? ( {gt( "{count, plural, one {Preview limited to the first 1 MB of a {formatted} byte file.} other {Preview limited to the first 1 MB of a {formatted} byte file.}}", @@ -1789,21 +1814,20 @@ export default function FilePreviewPanel({ title={relativePath} workspaceMutationId={workspaceMutationId} /> - ) : relativePath && - absolutePath && - file.data?.truncated && - !isDocument && - !draft && - !isMarkdown && - !isMermaid && - !isHtml ? ( + ) : relativePath && absolutePath && showsLargeText ? ( import("./LargeTextViewer")); +// A draft has no thread yet, so its download is scoped to the draft's workspace instead. +function largeFileResource( + threadRef: ScopedThreadRef, + absolutePath: string, + draftCwd: string | null, +): AssetResource { + return draftCwd === null + ? { + _tag: "media-file", + threadId: threadRef.threadId, + path: absolutePath, + disposition: "attachment", + } + : { + _tag: "draft-workspace-file", + cwd: draftCwd, + path: absolutePath, + disposition: "attachment", + }; +} + +/** Copy and save for a file past the 1 MB preview, which the panel holds only in its viewer. */ +function LargeFileActions(props: { + environmentId: EnvironmentId; + threadRef: ScopedThreadRef; + absolutePath: string; + draftCwd: string | null; + name: string; + copyContents: RefObject<(() => Promise) | null>; +}) { + const gt = useGT(); + const { copyToClipboard, isCopied } = useCopyToClipboard({ + target: namedClipboardTarget(props.name), + }); + const [saving, setSaving] = useState(false); + const refreshAssetUrl = useAssetUrlRefresh( + props.environmentId, + largeFileResource(props.threadRef, props.absolutePath, props.draftCwd), + ); + const showError = (cause: unknown) => { + toastManager.add({ + type: "error", + title: gt("Could not read file"), + description: thrownErrorMessage(cause, m) ?? gt("Try again."), + }); + }; + return ( + <> + { + const copy = props.copyContents.current; + if (!copy) return; + void copy() + .then((text) => copyToClipboard(text, undefined)) + .catch(showError); + }} + > + {isCopied ? : } + + { + setSaving(true); + void (async () => { + const url = await refreshAssetUrl(); + if (!url) throw new Error(gt("Reconnect to the environment and try again.")); + const response = await fetch(url); + if (!response.ok) throw new Error(gt("The file could not be loaded. Try again.")); + const downloadUrl = URL.createObjectURL(await response.blob()); + setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000); + const anchor = document.createElement("a"); + anchor.href = downloadUrl; + anchor.download = props.name.split(/[\\/]/).at(-1) || props.name; + anchor.click(); + })() + .catch(showError) + .finally(() => setSaving(false)); + }} + > + + + + ); +} + export function WorkspaceLargeTextPreview(props: { environmentId: EnvironmentId; threadRef: ScopedThreadRef; absolutePath: string; + /** The draft's workspace while the thread does not exist yet. */ + draftCwd: string | null; name: string; delimiter: "," | "\t" | null; + /** Renders the file as Markdown resolving links against this workspace; null shows source. */ + markdownCwd: string | null; + copyContents: RefObject<(() => Promise) | null>; + /** The first megabyte already read, shown until the whole file arrives. */ + preview: string; + sizeBytes: number; + onPostRender?: ComponentProps["onPostRender"]; workspaceMutationId: string | null; revealLine: number | null; revealRequestId: number; wordWrap: boolean; }) { - const resource = { - _tag: "media-file", - threadId: props.threadRef.threadId, - path: props.absolutePath, - disposition: "attachment", - } as const; + const resource = largeFileResource(props.threadRef, props.absolutePath, props.draftCwd); const gt = useGT(); - const copyContents = useRef<(() => Promise) | null>(null); - const { copyToClipboard, isCopied } = useCopyToClipboard({ - target: namedClipboardTarget(props.name), - }); - const [saving, setSaving] = useState(false); const [revision, setRevision] = useState(0); const showError = (cause: unknown) => { toastManager.add({ @@ -2013,78 +2122,30 @@ export function WorkspaceLargeTextPreview(props: { }} /> ); - if (assetUrl._tag !== "Success" || loaded === null) - return ( -
    - Loading… -
    - ); + if (assetUrl._tag !== "Success" || loaded === null) return ; const src = `${loaded.url}${loaded.url.includes("?") ? "&" : "?"}revision=${encodeURIComponent(loaded.revision)}`; + const retry = () => { + void refreshAssetUrl() + .then(() => setRevision((value) => value + 1)) + .catch(showError); + }; return ( - <> -
    - - Full file - - { - const copy = copyContents.current; - if (!copy) return; - void copy() - .then((text) => copyToClipboard(text, undefined)) - .catch(showError); - }} - > - {isCopied ? : } - - { - setSaving(true); - void (async () => { - const url = await refreshAssetUrl(); - if (!url) throw new Error(gt("Reconnect to the environment and try again.")); - const response = await fetch(url); - if (!response.ok) throw new Error(gt("The file could not be loaded. Try again.")); - const downloadUrl = URL.createObjectURL(await response.blob()); - setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000); - const anchor = document.createElement("a"); - anchor.href = downloadUrl; - anchor.download = props.name.split(/[\\/]/).at(-1) || props.name; - anchor.click(); - })() - .catch(showError) - .finally(() => setSaving(false)); - }} - > - - -
    - - Loading… - - } - > - { - void refreshAssetUrl() - .then(() => setRevision((value) => value + 1)) - .catch(showError); - }} - src={src} - delimiter={props.delimiter} - revealLine={props.revealLine} - revealRequestId={props.revealRequestId} - wordWrap={props.wordWrap} - /> - - + ); } diff --git a/apps/web/src/components/files/LargeFilePreview.tsx b/apps/web/src/components/files/LargeFilePreview.tsx new file mode 100644 index 0000000000000..21590a1ea2b11 --- /dev/null +++ b/apps/web/src/components/files/LargeFilePreview.tsx @@ -0,0 +1,125 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { DEFAULT_TOKENIZE_MAX_LENGTH } from "@pierre/diffs"; +import type { FileOptions } from "@pierre/diffs/react"; +import { useGT } from "gt-react"; +import { lazy, Suspense, useImperativeHandle, type RefObject } from "react"; + +import { ChunkedMarkdown } from "./ChunkedMarkdown"; +import { FileSurfaceLoading } from "./fileSurfaceChrome"; +import { useFullFileMarkdown, useFullFileText } from "./fullFileText"; +import { FULL_TEXT_MAX_BYTES } from "./largeTextProtocol"; +import SourceFilePreview from "./ReadOnlySourcePreview"; + +const LargeTextViewer = lazy(() => import("./LargeTextViewer")); + +/** + * A file past the 1 MB read, shown like any other file once its full text arrives. Tables, and + * files too large to hold or lay out, use the worker-backed plain viewer. + */ +export default function LargeFilePreview(props: { + readonly src: string; + readonly name: string; + /** The first megabyte already read. */ + readonly preview: string; + readonly sizeBytes: number; + readonly delimiter: "," | "\t" | null; + /** Renders the file as Markdown resolving links against this workspace; null shows source. */ + readonly markdownCwd: string | null; + readonly threadRef: ScopedThreadRef; + readonly workspaceMutationId: string | null; + readonly copyContents: RefObject<(() => Promise) | null>; + readonly onRetry: () => void; + readonly onPostRender?: FileOptions["onPostRender"]; + readonly revealLine: number | null; + readonly revealRequestId: number; + readonly wordWrap: boolean; +}) { + const plain = props.delimiter !== null || props.sizeBytes > FULL_TEXT_MAX_BYTES; + return plain ? : ; +} + +// Pierre keeps every token of a highlighted file in memory: a 320k-line log took about 280 MB. +const HIGHLIGHT_MAX_LINES = DEFAULT_TOKENIZE_MAX_LENGTH; + +/** Estimates the whole file's lines from the preview, so highlighting is decided once. */ +function estimatedLines(preview: string, sizeBytes: number): number { + let lines = 1; + for (let index = preview.indexOf("\n"); index !== -1; index = preview.indexOf("\n", index + 1)) + lines += 1; + return (lines / Math.max(1, new TextEncoder().encode(preview).length)) * sizeBytes; +} + +function FullTextPreview(props: Parameters[0]) { + const file = useFullFileText(props.src, props.preview); + // Deciding from the full text would highlight the preview, then drop it once the file arrives. + const highlight = estimatedLines(props.preview, props.sizeBytes) <= HIGHLIGHT_MAX_LINES; + if (file === "too-large" || file === "failed") return ; + return ( + <> + + {props.markdownCwd !== null ? ( + + ) : ( + + )} + + ); +} + +function MarkdownText( + props: Parameters[0] & { + readonly markdownCwd: string; + readonly file: { readonly text: string; readonly done: boolean }; + }, +) { + return ( + + ); +} + +function CopyText(props: { + readonly copyContents: RefObject<(() => Promise) | null>; + readonly text: string | null; +}) { + const gt = useGT(); + const { text } = props; + useImperativeHandle( + props.copyContents, + () => () => + text === null + ? Promise.reject(new Error(gt("The file is still loading. Try again in a moment."))) + : Promise.resolve(text), + [text, gt], + ); + return null; +} + +function PlainViewer(props: Parameters[0]) { + return ( + }> + + + ); +} diff --git a/apps/web/src/components/files/LargeTextViewer.tsx b/apps/web/src/components/files/LargeTextViewer.tsx index 3cfe6b7fafcaa..fc9a890dd9b3e 100644 --- a/apps/web/src/components/files/LargeTextViewer.tsx +++ b/apps/web/src/components/files/LargeTextViewer.tsx @@ -1,6 +1,7 @@ import { msg, T, useGT, useMessages } from "gt-react"; import { useEffect, useImperativeHandle, useRef, useState, type RefObject } from "react"; import { m } from "~/i18n/messages"; +import { Spinner } from "~/components/ui/spinner"; import { parseDelimitedPreview } from "@t3tools/shared/delimitedPreview"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { useClientSettings } from "~/hooks/useSettings"; @@ -29,6 +30,36 @@ function firstScreen(text: string, delimiter: "," | "\t" | null, complete: boole return rows.slice(0, PREVIEW_PAGE_ROWS * 2); } +type Meta = Extract; + +function firstScreenState(text: string, delimiter: "," | "\t" | null, complete: boolean) { + const rows = firstScreen(text, delimiter, complete); + if (!rows.length) return null; + return { + pages: new Map( + [0, PREVIEW_PAGE_ROWS] + .filter((start) => start < rows.length) + .map((start) => [start / PREVIEW_PAGE_ROWS, rows.slice(start, start + PREVIEW_PAGE_ROWS)]), + ), + meta: { + type: "meta", + count: rows.length, + columns: rows.reduce((max, row) => Math.max(max, row.length), 1), + complete: false, + } satisfies Meta as Meta, + }; +} + +// Reopening a recent file paints its first screen at once while the worker indexes it again. +const recentFirstScreens = new Map(); + +function rememberFirstScreen(src: string, text: string, complete: boolean) { + recentFirstScreens.delete(src); + recentFirstScreens.set(src, { text, complete }); + if (recentFirstScreens.size > 32) + recentFirstScreens.delete(recentFirstScreens.keys().next().value!); +} + export default function LargeTextViewer(props: { readonly name: string; readonly src?: string; @@ -44,8 +75,12 @@ export default function LargeTextViewer(props: { }) { const gt = useGT(); const messages = useMessages(); - const [meta, setMeta] = useState | null>(null); - const [pages, setPages] = useState(new Map()); + const [initial] = useState(() => { + const cached = props.src === undefined ? undefined : recentFirstScreens.get(props.src); + return cached ? firstScreenState(cached.text, props.delimiter, cached.complete) : null; + }); + const [meta, setMeta] = useState(initial?.meta ?? null); + const [pages, setPages] = useState(initial?.pages ?? new Map()); const [error, setError] = useState(null); const worker = useRef(null); const copyPending = useRef<{ @@ -66,25 +101,11 @@ export default function LargeTextViewer(props: { let prefetched = false; const paintFirstScreen = (text: string, complete: boolean) => { if (indexed || controller.signal.aborted) return; - const rows = firstScreen(text, props.delimiter, complete); - if (!rows.length) return; + const screen = firstScreenState(text, props.delimiter, complete); + if (!screen) return; prefetched = true; - setPages( - new Map( - [0, PREVIEW_PAGE_ROWS] - .filter((start) => start < rows.length) - .map((start) => [ - start / PREVIEW_PAGE_ROWS, - rows.slice(start, start + PREVIEW_PAGE_ROWS), - ]), - ), - ); - setMeta({ - type: "meta", - count: rows.length, - columns: rows.reduce((max, row) => Math.max(max, row.length), 1), - complete: false, - }); + setPages(screen.pages); + setMeta(screen.meta); }; const startWorker = () => { if (controller.signal.aborted) return; @@ -104,9 +125,14 @@ export default function LargeTextViewer(props: { } else if (result.type === "meta") { indexed = true; if (prefetched) { - setPages(new Map()); - pending.current.clear(); + // Keeps the painted first screen until the worker's own pages replace it. prefetched = false; + pending.current.clear(); + for (const index of [0, 1]) { + if (index * PREVIEW_PAGE_ROWS >= result.count) break; + pending.current.add(index); + engine.postMessage({ type: "page", index }, []); + } } setMeta(result); } else if (result.type === "page") { @@ -152,8 +178,12 @@ export default function LargeTextViewer(props: { }; // Only this bounded prefix is parsed on the main thread. Indexing the full // file and fetching later pages remain in the worker. + const cached = props.src === undefined ? undefined : recentFirstScreens.get(props.src); if (props.sizeBytes === 0) { startWorker(); + } else if (cached) { + paintFirstScreen(cached.text, cached.complete); + scheduleWorker(); } else if (props.text !== undefined) { paintFirstScreen( props.text.slice(0, FIRST_SCREEN_BYTES), @@ -161,7 +191,8 @@ export default function LargeTextViewer(props: { ); scheduleWorker(); } else if (props.src) { - void fetch(props.src, { + const src = props.src; + void fetch(src, { headers: { Range: `bytes=0-${FIRST_SCREEN_BYTES - 1}` }, cache: "no-store", signal: controller.signal, @@ -176,7 +207,9 @@ export default function LargeTextViewer(props: { return; } const total = Number(response.headers.get("content-range")?.split("/")[1]); - paintFirstScreen(await response.text(), total <= FIRST_SCREEN_BYTES); + const text = await response.text(); + rememberFirstScreen(src, text, total <= FIRST_SCREEN_BYTES); + paintFirstScreen(text, total <= FIRST_SCREEN_BYTES); }) .catch(() => { // The worker reports authorization, network and format failures. @@ -223,27 +256,28 @@ export default function LargeTextViewer(props: { className="flex min-h-10 shrink-0 flex-wrap items-center gap-x-1 border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums" role="status" > - {props.delimiter - ? `${gt("{count, plural, one {{formatted} row} other {{formatted} rows}}", { - count: rowCount, - formatted: rowCount.toLocaleString(), - })} · ${gt("{count, plural, one {{formatted} column} other {{formatted} columns}}", { - count: columnCount, - formatted: columnCount.toLocaleString(), - })}` - : gt("{count, plural, one {{formatted} line} other {{formatted} lines}}", { - count: meta.count, - formatted: meta.count.toLocaleString(), - })} + {/* Counts appear once indexing ends; the prefix count alone would understate the file. */} + {!meta.complete + ? null + : props.delimiter + ? `${gt("{count, plural, one {{formatted} row} other {{formatted} rows}}", { + count: rowCount, + formatted: rowCount.toLocaleString(), + })} · ${gt("{count, plural, one {{formatted} column} other {{formatted} columns}}", { + count: columnCount, + formatted: columnCount.toLocaleString(), + })}` + : gt("{count, plural, one {{formatted} line} other {{formatted} lines}}", { + count: meta.count, + formatted: meta.count.toLocaleString(), + })} {meta.complete && meta.sizeBytes !== undefined ? ` · ${meta.sizeBytes === 0 ? gt("0 bytes") : formatAttachmentSize(meta.sizeBytes, messages)}` - : ` · ${gt("Indexing…")}`} + : null} {!meta.complete ? ( -
    - - Loading the rest of the file… - +
    +
    ) : null} {meta.columns === 1024 ? ( diff --git a/apps/web/src/components/files/ReadOnlySourcePreview.tsx b/apps/web/src/components/files/ReadOnlySourcePreview.tsx index d9236753e98a3..cd1559f46052f 100644 --- a/apps/web/src/components/files/ReadOnlySourcePreview.tsx +++ b/apps/web/src/components/files/ReadOnlySourcePreview.tsx @@ -17,6 +17,8 @@ export default function ReadOnlySourcePreview(props: { readonly onPostRender?: FileOptions["onPostRender"]; /** A preview's own wrap toggle; omitted follows the word wrap setting. */ readonly wordWrap?: boolean; + /** Files with more lines than this render without highlighting; omitted keeps Pierre's limit. */ + readonly tokenizeMaxLength?: number; }) { const resolvedTheme = useRenderedAppearance(); const defaultWordWrap = useClientSettings((settings) => settings.wordWrap); @@ -70,7 +72,8 @@ export default function ReadOnlySourcePreview(props: { }} > @@ -85,6 +88,9 @@ export default function ReadOnlySourcePreview(props: { overflow: wordWrap ? "wrap" : "scroll", theme: resolveDiffThemeName(resolvedTheme), preferredHighlighter: PREFERRED_HIGHLIGHTER, + ...(props.tokenizeMaxLength === undefined + ? {} + : { tokenizeMaxLength: props.tokenizeMaxLength }), themeType: resolvedTheme, unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS, onPostRender: drawSelection, diff --git a/apps/web/src/components/files/fullFileText.test.ts b/apps/web/src/components/files/fullFileText.test.ts new file mode 100644 index 0000000000000..80f507c3526cb --- /dev/null +++ b/apps/web/src/components/files/fullFileText.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; +import { FetchHttpClient } from "effect/http"; + +import { downloadText } from "./fullFileText"; +import { RENDERED_MAX_LINES } from "./largeTextProtocol"; + +const encoder = new TextEncoder(); + +const download = (file: Uint8Array) => + downloadText("http://localhost/assets/file.ts").pipe( + Stream.runLast, + Effect.map(Option.getOrThrow), + Effect.provide(FetchHttpClient.layer), + Effect.provideService(FetchHttpClient.Fetch, () => Promise.resolve(new Response(file.slice()))), + ); + +describe("downloadText", () => { + it.effect( + "drops a leading byte order mark as the preview read does, and keeps a later U+FEFF", + () => + Effect.gen(function* () { + const whole = new Uint8Array([0xef, 0xbb, 0xbf, ...encoder.encode("one\ntwo\n")]); + expect((yield* download(whole)).text).toBe("one\ntwo\n"); + }), + ); + + it.effect("stops at the first text past the lines the main thread can lay out", () => + Effect.gen(function* () { + const file = yield* download(encoder.encode("\n".repeat(RENDERED_MAX_LINES + 10))); + expect(file.lines).toBeGreaterThan(RENDERED_MAX_LINES); + }), + ); +}); diff --git a/apps/web/src/components/files/fullFileText.ts b/apps/web/src/components/files/fullFileText.ts new file mode 100644 index 0000000000000..8ff9c557407a1 --- /dev/null +++ b/apps/web/src/components/files/fullFileText.ts @@ -0,0 +1,90 @@ +import { useAtomValue } from "@effect/atom-react"; +import { splitMarkdown, type SplitMarkdown } from "@t3tools/shared/markdownChunks"; +import * as Effect from "effect/Effect"; +import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; +import * as Stream from "effect/Stream"; +import { AsyncResult, Atom } from "effect/reactivity"; + +import { connectionAtomRuntime } from "~/connection/runtime"; + +import { FULL_TEXT_MAX_BYTES, RENDERED_MAX_LINES } from "./largeTextProtocol"; + +// A slow download swaps in what has arrived this often, so the reader is not left at 1 MB. +const SWAP_INTERVAL = "1 second"; +// Switching back to a recently closed file reuses its text instead of downloading it again. +const RECENT_FILE_TTL_MS = 60_000; + +interface Downloaded { + readonly text: string; + readonly lines: number; +} + +function countNewlines(text: string): number { + let lines = 0; + for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", index + 1)) { + lines += 1; + } + return lines; +} + +// Past either cap the main thread cannot hold or lay the text out. +const tooLarge = (file: Downloaded) => + file.lines > RENDERED_MAX_LINES || file.text.length > FULL_TEXT_MAX_BYTES; + +/** A file's text so far, at most once per interval, ending at its whole text or past a cap. */ +export const downloadText = (src: string) => + HttpClient.get(src).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.map((response) => response.stream), + Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }), + Stream.unwrap, + // Drops a leading BOM, as the 1 MB preview read does. + Stream.decodeText, + Stream.scan( + (): Downloaded => ({ text: "", lines: 1 }), + (file, chunk) => ({ text: file.text + chunk, lines: file.lines + countNewlines(chunk) }), + ), + Stream.takeUntil(tooLarge), + Stream.groupedWithin(Number.MAX_SAFE_INTEGER, SWAP_INTERVAL), + Stream.map((swaps) => swaps[swaps.length - 1]!), + ); + +/** `src` is the asset URL with its revision, so a changed file downloads again. */ +const fullFileTextAtom = Atom.family((src: string) => + connectionAtomRuntime + .atom(downloadText(src)) + .pipe(Atom.setIdleTTL(RECENT_FILE_TTL_MS), Atom.withLabel(`full-file-text:${src}`)), +); + +export type FullFileText = + | { readonly text: string; readonly done: boolean } + | "too-large" + | "failed"; + +/** A file past the 1 MB read: the preview at once, then the full file as it downloads. */ +export function useFullFileText(src: string, preview: string): FullFileText { + const result = useAtomValue(fullFileTextAtom(src)); + if (AsyncResult.isFailure(result)) return "failed"; + if (!AsyncResult.isSuccess(result)) return { text: preview, done: false }; + if (tooLarge(result.value)) return "too-large"; + if (!result.waiting) return { text: result.value.text, done: true }; + // Whole lines only, so the last row does not flicker as it fills in; the first swap can still + // hold less than the preview already shows. + const text = result.value.text.slice(0, result.value.text.lastIndexOf("\n") + 1); + return { text: text.length >= preview.length ? text : preview, done: false }; +} + +/** The finished text's Markdown pieces, kept as long as its text; splitting 12 MB takes 0.5 s. */ +const fullFileMarkdownAtom = Atom.family((src: string) => + Atom.make((get) => { + const result = get(fullFileTextAtom(src)); + return AsyncResult.isSuccess(result) && !result.waiting && !tooLarge(result.value) + ? splitMarkdown(result.value.text) + : null; + }).pipe(Atom.setIdleTTL(RECENT_FILE_TTL_MS), Atom.withLabel(`full-file-markdown:${src}`)), +); + +/** Markdown pieces of the text so far; a finished file's are split once and kept. */ +export function useFullFileMarkdown(src: string, text: string): SplitMarkdown { + return useAtomValue(fullFileMarkdownAtom(src)) ?? splitMarkdown(text); +} diff --git a/apps/web/src/components/files/largeTextProtocol.ts b/apps/web/src/components/files/largeTextProtocol.ts index 8ff6e54946289..661b15c8c8e7d 100644 --- a/apps/web/src/components/files/largeTextProtocol.ts +++ b/apps/web/src/components/files/largeTextProtocol.ts @@ -3,6 +3,12 @@ export const LARGE_TEXT_MAX_BYTES = 256 * 1024 * 1024; export const LARGE_TEXT_MAX_ROWS = 5_000_000; export const LARGE_TEXT_MAX_COLUMNS = 1024; export const PREVIEW_PAGE_ROWS = 32; +// Browsers stop laying out an element near 33.5M px. Rendered Markdown measured about 22 px per +// source line, so files taller than this stay in the scaled plain viewer. +export const RENDERED_MAX_LINES = 1_200_000; +// Rendered Markdown and highlighted source hold the whole file on the main thread; larger files +// use the worker-backed plain viewer. +export const FULL_TEXT_MAX_BYTES = 64 * 1024 * 1024; export type TextPreviewRequest = | { type: "open"; src?: string; text?: string; sizeBytes?: number; delimiter: "," | "\t" | null } | { type: "page"; index: number } diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 16f3d83c8b2e6..8d5cb7d817bb1 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -5628,7 +5628,6 @@ }, ". Prüfe den Pfad des Links oder suche die Datei unter Dateien." ], - "b9b6bbd1e1ea189f": "Ganze Datei", "d715e9494fdbaaf6": "Die Schriftart konnte nicht geladen werden.", "ff17c777a72b4408": "Schriftvorschauen sind auf 10 MB begrenzt.", "6bd41ad699e22f10": "Die Schriftart ist nicht verfügbar.", @@ -5638,6 +5637,7 @@ "a9abaaa4220eae21": "{error} Speichere sie, um sie in einer anderen App zu öffnen.", "c508c9000d9656f8": "Schriftvorschau", "1c416d621d250be8": "Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich.", + "d7d08260f16b7828": "Die Datei wird noch geladen. Versuche es gleich noch einmal.", "76ebb03de52c92d6": "Der Textbetrachter wurde beendet.", "f48162e8e8c12af7": "Der Textbetrachter konnte nicht geladen werden. Schließe die Datei und versuche es erneut.", "bc4c5b13d38a5da7": "Vorschau geschlossen.", @@ -5645,8 +5645,6 @@ "9450d1827ef336a1": "Ein anderer Kopiervorgang läuft.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} Zeile} other {{formatted} Zeilen}}", "13b14784f8707ddd": "0 Byte", - "f6e9581cba3467fa": "Wird indiziert…", - "2d1f293ac12463fc": "Der Rest der Datei wird geladen…", "b75105bef8f564a4": "Die ersten 1.024 Spalten werden angezeigt. Quelltext und Speichern behalten alle Spalten.", "2a6e1b1f209c3888": "Diese Datei ist leer.", "192fc79eb3b5b2cb": "Dieses Diagramm enthält Ressourcen-URLs, Markup, Knotenmetadaten oder eine benutzerdefinierte Konfiguration. Zeige den Mermaid-Quelltext an, um es sicher zu prüfen.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index c4534c680b95f..6c5ef49b77f43 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -5629,7 +5629,6 @@ }, ". Check the link's path or locate the file in Files." ], - "b9b6bbd1e1ea189f": "Full file", "d715e9494fdbaaf6": "The font could not be loaded.", "ff17c777a72b4408": "Font previews are limited to 10 MB.", "6bd41ad699e22f10": "The font is unavailable.", @@ -5639,6 +5638,7 @@ "a9abaaa4220eae21": "{error} Save it to open in another app.", "c508c9000d9656f8": "Font preview", "1c416d621d250be8": "The quick brown fox jumps over the lazy dog.", + "d7d08260f16b7828": "The file is still loading. Try again in a moment.", "76ebb03de52c92d6": "The text viewer stopped.", "f48162e8e8c12af7": "Could not load the text viewer. Close the file and try again.", "bc4c5b13d38a5da7": "Preview closed.", @@ -5646,8 +5646,6 @@ "9450d1827ef336a1": "Another copy is in progress.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} line} other {{formatted} lines}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexing…", - "2d1f293ac12463fc": "Loading the rest of the file…", "b75105bef8f564a4": "Showing the first 1,024 columns. Source and Save retain every column.", "2a6e1b1f209c3888": "This file is empty.", "192fc79eb3b5b2cb": "This diagram contains resource URLs, markup, node metadata, or custom configuration. Show Mermaid source to inspect it safely.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index ff83b277dc0d6..1f4ed2cf548ee 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -5627,7 +5627,6 @@ }, ". Revisa la ruta del enlace o busca el archivo en Archivos." ], - "b9b6bbd1e1ea189f": "Archivo completo", "d715e9494fdbaaf6": "No se pudo cargar la fuente.", "ff17c777a72b4408": "Las vistas previas de fuentes están limitadas a 10 MB.", "6bd41ad699e22f10": "La fuente no está disponible.", @@ -5637,6 +5636,7 @@ "a9abaaa4220eae21": "{error} Guárdala para abrirla en otra app.", "c508c9000d9656f8": "Vista previa de la fuente", "1c416d621d250be8": "El veloz murciélago hindú comía feliz cardillo y kiwi.", + "d7d08260f16b7828": "El archivo aún se está cargando. Inténtalo de nuevo en un momento.", "76ebb03de52c92d6": "El visor de texto se detuvo.", "f48162e8e8c12af7": "No se pudo cargar el visor de texto. Cierra el archivo y vuelve a intentarlo.", "bc4c5b13d38a5da7": "Vista previa cerrada.", @@ -5644,8 +5644,6 @@ "9450d1827ef336a1": "Ya hay otra copia en curso.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} línea} other {{formatted} líneas}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexando…", - "2d1f293ac12463fc": "Cargando el resto del archivo…", "b75105bef8f564a4": "Se muestran las primeras 1024 columnas. El código fuente y Guardar conservan todas las columnas.", "2a6e1b1f209c3888": "Este archivo está vacío.", "192fc79eb3b5b2cb": "Este diagrama contiene URL de recursos, marcado, metadatos de nodos o configuración personalizada. Muestra el código fuente de Mermaid para inspeccionarlo de forma segura.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 939d36465b041..72da8bf8e23b2 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -5628,7 +5628,6 @@ }, ". Vérifiez le chemin du lien ou retrouvez le fichier dans Fichiers." ], - "b9b6bbd1e1ea189f": "Fichier complet", "d715e9494fdbaaf6": "Impossible de charger la police.", "ff17c777a72b4408": "Les aperçus de polices sont limités à 10 Mo.", "6bd41ad699e22f10": "La police est indisponible.", @@ -5638,6 +5637,7 @@ "a9abaaa4220eae21": "{error} Enregistrez-la pour l’ouvrir dans une autre app.", "c508c9000d9656f8": "Aperçu de la police", "1c416d621d250be8": "Portez ce vieux whisky au juge blond qui fume.", + "d7d08260f16b7828": "Le fichier est encore en cours de chargement. Réessaie dans un instant.", "76ebb03de52c92d6": "La visionneuse de texte s’est arrêtée.", "f48162e8e8c12af7": "Impossible de charger la visionneuse de texte. Fermez le fichier et réessayez.", "bc4c5b13d38a5da7": "Aperçu fermé.", @@ -5645,8 +5645,6 @@ "9450d1827ef336a1": "Une autre copie est en cours.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} ligne} other {{formatted} lignes}}", "13b14784f8707ddd": "0 octet", - "f6e9581cba3467fa": "Indexation…", - "2d1f293ac12463fc": "Chargement du reste du fichier…", "b75105bef8f564a4": "Affichage des 1 024 premières colonnes. Source et Enregistrer conservent toutes les colonnes.", "2a6e1b1f209c3888": "Ce fichier est vide.", "192fc79eb3b5b2cb": "Ce diagramme contient des URL de ressources, du balisage, des métadonnées de nœuds ou une configuration personnalisée. Affichez la source Mermaid pour l’examiner en toute sécurité.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 51fe276edc353..28945ae29dca3 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -5610,7 +5610,6 @@ }, "。リンクのパスを確認するか、[ファイル] でファイルを探してください。" ], - "b9b6bbd1e1ea189f": "ファイル全体", "d715e9494fdbaaf6": "フォントを読み込めませんでした。", "ff17c777a72b4408": "フォントのプレビューは 10 MB までです。", "6bd41ad699e22f10": "フォントを利用できません。", @@ -5620,6 +5619,7 @@ "a9abaaa4220eae21": "{error} 別のアプリで開くには保存してください。", "c508c9000d9656f8": "フォントのプレビュー", "1c416d621d250be8": "いろはにほへと ちりぬるを わかよたれそ つねならむ", + "d7d08260f16b7828": "ファイルはまだ読み込み中です。少し待ってからもう一度お試しください。", "76ebb03de52c92d6": "テキストビューアーが停止しました。", "f48162e8e8c12af7": "テキストビューアーを読み込めませんでした。ファイルを閉じて、もう一度お試しください。", "bc4c5b13d38a5da7": "プレビューを閉じました。", @@ -5627,8 +5627,6 @@ "9450d1827ef336a1": "別のコピーが進行中です。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 バイト", - "f6e9581cba3467fa": "インデックスを作成しています…", - "2d1f293ac12463fc": "ファイルの残りを読み込んでいます…", "b75105bef8f564a4": "最初の 1,024 列を表示しています。ソースと保存ではすべての列が保持されます。", "2a6e1b1f209c3888": "このファイルは空です。", "192fc79eb3b5b2cb": "この図にはリソース URL、マークアップ、ノードのメタデータ、またはカスタム構成が含まれています。安全に確認するには Mermaid のソースを表示してください。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 51c3b0a06a006..35f6cc3549436 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -5608,7 +5608,6 @@ }, ". 링크의 경로를 확인하거나 파일에서 해당 파일을 찾으세요." ], - "b9b6bbd1e1ea189f": "전체 파일", "d715e9494fdbaaf6": "글꼴을 불러올 수 없습니다.", "ff17c777a72b4408": "글꼴 미리 보기는 10MB로 제한됩니다.", "6bd41ad699e22f10": "글꼴을 사용할 수 없습니다.", @@ -5618,6 +5617,7 @@ "a9abaaa4220eae21": "{error} 저장한 후 다른 앱에서 여세요.", "c508c9000d9656f8": "글꼴 미리 보기", "1c416d621d250be8": "다람쥐 헌 쳇바퀴에 타고파.", + "d7d08260f16b7828": "파일을 아직 불러오는 중입니다. 잠시 후 다시 시도하세요.", "76ebb03de52c92d6": "텍스트 뷰어가 중지되었습니다.", "f48162e8e8c12af7": "텍스트 뷰어를 불러올 수 없습니다. 파일을 닫고 다시 시도하세요.", "bc4c5b13d38a5da7": "미리 보기가 닫혔습니다.", @@ -5625,8 +5625,6 @@ "9450d1827ef336a1": "다른 복사가 진행 중입니다.", "8f48999eb6d9e2e3": "{count, plural, other {{formatted}줄}}", "13b14784f8707ddd": "0바이트", - "f6e9581cba3467fa": "색인하는 중…", - "2d1f293ac12463fc": "파일의 나머지를 불러오는 중…", "b75105bef8f564a4": "처음 1,024열을 표시합니다. 소스와 저장에는 모든 열이 유지됩니다.", "2a6e1b1f209c3888": "이 파일은 비어 있습니다.", "192fc79eb3b5b2cb": "이 다이어그램에는 리소스 URL, 마크업, 노드 메타데이터 또는 사용자 지정 구성이 포함되어 있습니다. 안전하게 확인하려면 Mermaid 소스를 표시하세요.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index d17ff0e321ccf..85fefb672d30c 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -5627,7 +5627,6 @@ }, ". Verifique o caminho do link ou localize o arquivo em Arquivos." ], - "b9b6bbd1e1ea189f": "Arquivo completo", "d715e9494fdbaaf6": "Não foi possível carregar a fonte.", "ff17c777a72b4408": "As pré-visualizações de fontes são limitadas a 10 MB.", "6bd41ad699e22f10": "A fonte não está disponível.", @@ -5637,6 +5636,7 @@ "a9abaaa4220eae21": "{error} Salve-a para abrir em outro app.", "c508c9000d9656f8": "Pré-visualização da fonte", "1c416d621d250be8": "Um pequeno jabuti xereta viu dez cegonhas felizes.", + "d7d08260f16b7828": "O arquivo ainda está carregando. Tente novamente em instantes.", "76ebb03de52c92d6": "O visualizador de texto parou.", "f48162e8e8c12af7": "Não foi possível carregar o visualizador de texto. Feche o arquivo e tente novamente.", "bc4c5b13d38a5da7": "Pré-visualização fechada.", @@ -5644,8 +5644,6 @@ "9450d1827ef336a1": "Outra cópia está em andamento.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} linha} other {{formatted} linhas}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexando…", - "2d1f293ac12463fc": "Carregando o restante do arquivo…", "b75105bef8f564a4": "Mostrando as primeiras 1.024 colunas. O código-fonte e o arquivo salvo mantêm todas as colunas.", "2a6e1b1f209c3888": "Este arquivo está vazio.", "192fc79eb3b5b2cb": "Este diagrama contém URLs de recursos, markup, metadados de nós ou configuração personalizada. Mostre o código Mermaid para inspecioná-lo com segurança.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 88e2323bac363..f4d45a79d0b52 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -5627,7 +5627,6 @@ }, ". Проверьте путь в ссылке или найдите файл в «Файлах»." ], - "b9b6bbd1e1ea189f": "Файл целиком", "d715e9494fdbaaf6": "Не удалось загрузить шрифт.", "ff17c777a72b4408": "Предпросмотр шрифтов ограничен 10 МБ.", "6bd41ad699e22f10": "Шрифт недоступен.", @@ -5637,6 +5636,7 @@ "a9abaaa4220eae21": "{error} Сохраните его, чтобы открыть в другом приложении.", "c508c9000d9656f8": "Предпросмотр шрифта", "1c416d621d250be8": "Съешь же ещё этих мягких французских булок, да выпей чаю.", + "d7d08260f16b7828": "Файл ещё загружается. Повторите попытку через мгновение.", "76ebb03de52c92d6": "Просмотрщик текста остановился.", "f48162e8e8c12af7": "Не удалось загрузить просмотрщик текста. Закройте файл и повторите попытку.", "bc4c5b13d38a5da7": "Предпросмотр закрыт.", @@ -5644,8 +5644,6 @@ "9450d1827ef336a1": "Уже идёт другое копирование.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} строка} few {{formatted} строки} many {{formatted} строк} other {{formatted} строки}}", "13b14784f8707ddd": "0 байт", - "f6e9581cba3467fa": "Индексация…", - "2d1f293ac12463fc": "Загрузка остальной части файла…", "b75105bef8f564a4": "Показаны первые 1 024 столбца. «Исходник» и «Сохранить» сохраняют все столбцы.", "2a6e1b1f209c3888": "Этот файл пуст.", "192fc79eb3b5b2cb": "Эта диаграмма содержит URL ресурсов, разметку, метаданные узлов или собственную конфигурацию. Откройте исходник Mermaid, чтобы безопасно её изучить.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 055af1f3a6783..99818c1f2ed37 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -5628,7 +5628,6 @@ }, ". Kontrollera länkens sökväg eller leta upp filen i Filer." ], - "b9b6bbd1e1ea189f": "Hela filen", "d715e9494fdbaaf6": "Teckensnittet kunde inte läsas in.", "ff17c777a72b4408": "Förhandsvisningar av teckensnitt är begränsade till 10 MB.", "6bd41ad699e22f10": "Teckensnittet är inte tillgängligt.", @@ -5638,6 +5637,7 @@ "a9abaaa4220eae21": "{error} Spara det för att öppna det i en annan app.", "c508c9000d9656f8": "Förhandsvisning av teckensnitt", "1c416d621d250be8": "Flygande bäckasiner söka hwila på mjuka tuvor.", + "d7d08260f16b7828": "Filen läses fortfarande in. Försök igen om en stund.", "76ebb03de52c92d6": "Textvisaren stoppades.", "f48162e8e8c12af7": "Kunde inte läsa in textvisaren. Stäng filen och försök igen.", "bc4c5b13d38a5da7": "Förhandsvisningen stängdes.", @@ -5645,8 +5645,6 @@ "9450d1827ef336a1": "En annan kopiering pågår.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} rad} other {{formatted} rader}}", "13b14784f8707ddd": "0 byte", - "f6e9581cba3467fa": "Indexerar…", - "2d1f293ac12463fc": "Läser in resten av filen…", "b75105bef8f564a4": "Visar de första 1 024 kolumnerna. Källa och Spara behåller alla kolumner.", "2a6e1b1f209c3888": "Den här filen är tom.", "192fc79eb3b5b2cb": "Det här diagrammet innehåller resurs-URL:er, markup, nodmetadata eller anpassad konfiguration. Visa Mermaid-källan för att granska det säkert.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 998020844cf79..09d04201cd2f8 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -5634,7 +5634,6 @@ }, "。请检查链接的路径,或在“文件”中找到该文件。" ], - "b9b6bbd1e1ea189f": "完整文件", "d715e9494fdbaaf6": "无法加载该字体。", "ff17c777a72b4408": "字体预览限制为 10 MB。", "6bd41ad699e22f10": "该字体不可用。", @@ -5644,6 +5643,7 @@ "a9abaaa4220eae21": "{error} 保存后可在其他应用中打开。", "c508c9000d9656f8": "字体预览", "1c416d621d250be8": "敏捷的棕色狐狸跳过了那只懒狗。", + "d7d08260f16b7828": "文件仍在加载中。请稍后重试。", "76ebb03de52c92d6": "文本查看器已停止。", "f48162e8e8c12af7": "无法加载文本查看器。请关闭文件后重试。", "bc4c5b13d38a5da7": "预览已关闭。", @@ -5651,8 +5651,6 @@ "9450d1827ef336a1": "另一个复制操作正在进行。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 字节", - "f6e9581cba3467fa": "正在建立索引…", - "2d1f293ac12463fc": "正在加载文件的其余部分…", "b75105bef8f564a4": "仅显示前 1,024 列。查看源码或保存文件时会保留所有列。", "2a6e1b1f209c3888": "此文件为空。", "192fc79eb3b5b2cb": "此图表包含资源 URL、标记、节点元数据或自定义配置。请显示 Mermaid 源码以安全查看。", diff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.ts index 0cae763748d7a..761cdb8114d9c 100644 --- a/packages/contracts/src/assets.ts +++ b/packages/contracts/src/assets.ts @@ -41,6 +41,7 @@ export const AssetResource = Schema.Union([ Schema.TaggedStruct("draft-workspace-file", { cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)), path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)), + disposition: Schema.optionalKey(Schema.Literal("attachment")), }), Schema.TaggedStruct("attachment", { attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)), diff --git a/packages/shared/package.json b/packages/shared/package.json index b1ffa038030ef..b727b976fe143 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -519,6 +519,10 @@ "types": "./src/markdownGithubAlerts.ts", "import": "./src/markdownGithubAlerts.ts" }, + "./markdownChunks": { + "types": "./src/markdownChunks.ts", + "import": "./src/markdownChunks.ts" + }, "./markdownHast": { "types": "./src/markdownHast.ts", "import": "./src/markdownHast.ts" diff --git a/packages/shared/src/markdownChunks.test.ts b/packages/shared/src/markdownChunks.test.ts new file mode 100644 index 0000000000000..a5cf2a8017b35 --- /dev/null +++ b/packages/shared/src/markdownChunks.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { splitMarkdown } from "./markdownChunks.ts"; + +const splitLargeMarkdown = (text: string, targetChars?: number) => + splitMarkdown(text, targetChars).chunks; + +const starts = (text: string) => + splitLargeMarkdown(text, 1).map((chunk) => chunk.text.split("\n")[0]); + +describe("splitMarkdown", () => { + it("cuts only where a new top-level block starts, and keeps every byte", () => { + const text = [ + "# Title", + "Intro paragraph", + "", + "- item one", + "", + " continued item", + "- item two", + "", + "2. ordered", + "", + "```md", + "# not a heading", + "", + "Not a paragraph", + "```", + "", + "> quote", + "", + "Closing paragraph", + "## Next", + "---", + "", + "| a | b |", + ].join("\n"); + const chunks = splitLargeMarkdown(text, 1); + expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text); + expect(chunks.reduce((sum, chunk) => sum + chunk.lines, 0)).toBe(text.split("\n").length); + expect(starts(text)).toEqual([ + "# Title", + "```md", + "> quote", + "Closing paragraph", + "## Next", + "| a | b |", + ]); + }); + + it("keeps a fence open until a matching closer", () => { + const text = ["````", "```", "", "# inside", "````", "", "after"].join("\n"); + expect(starts(text)).toEqual(["````", "after"]); + }); + + it("keeps HTML blocks and display math open across blank lines", () => { + const text = [ + "", + "", + "$$", + "", + "Inside math", + "$$", + "", + "
    ",
    +      "",
    +      "Preformatted",
    +      "
    ", + "", + "", + "", + "
    ", + "# literal", + "
    ", + "", + "after", + ].join("\n"); + expect(starts(text)).toEqual(["/], + [/^ {0,3}<\?/, /\?>/], + [/^ {0,3}/], + [/^ {0,3}/], + [/^ {0,3}\$\$/, /\$\$/], +]; + +// A tag name, not an autolink such as . +const HTML_BLOCK_START = /^ {0,3}<\/?[A-Za-z][A-Za-z0-9-]*(?=[\s/>]|$)/; + +/** Returns how to recognize the end of a block that `line` opens, or null for none. */ +function blockCloser(line: string): ((line: string) => boolean) | null { + const fence = FENCE_OPEN.exec(line)?.[1]; + if (fence) { + return (next) => { + const closer = FENCE_OPEN.exec(next)?.[1]; + return ( + closer !== undefined && + closer[0] === fence[0] && + closer.length >= fence.length && + !next.trim().slice(closer.length) + ); + }; + } + for (const [open, close] of SPANNING_BLOCKS) { + const opener = open.exec(line)?.[0]; + if (opener === undefined) continue; + return close.test(line.slice(opener.length)) ? null : (next) => close.test(next); + } + // Other HTML blocks (CommonMark types 6 and 7) run until a blank line. + return HTML_BLOCK_START.test(line) ? (next) => next.trim() === "" : null; +} + +export interface MarkdownChunk { + readonly text: string; + readonly lines: number; +} + +const FRONTMATTER_OPEN = /^\uFEFF?---[ \t]*\r?$/; +const FRONTMATTER_CLOSE = /^(?:---|\.\.\.)[ \t]*\r?$/; +// An opening rule with no closer is a thematic break, not frontmatter; stop waiting for one. +const FRONTMATTER_MAX_LINES = 1000; + +// A one-line link reference definition; footnotes are left alone so each piece does not grow +// a footnote section. +const LINK_DEFINITION = + /^ {0,3}\[(?!\^)(?:[^\]\\]|\\.)+\]:[ \t]*(?:<[^<>\n]*>|[^\s<]\S*)(?:[ \t]+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?[ \t]*\r?$/; +// Definitions past this are not repeated into every piece; their parse cost would outweigh links. +const SHARED_DEFINITIONS_MAX_CHARS = 16 * 1024; + +export interface SplitMarkdown { + readonly chunks: readonly MarkdownChunk[]; + readonly definitions: string; +} + +/** + * Cuts Markdown into pieces of roughly `targetChars`, only at column-0 headings or paragraphs + * that start a new top-level block. Leading frontmatter stays in the first piece. Link + * definitions are collected so every piece can resolve them; footnotes resolve only inside their + * own piece, and duplicate heading slugs restart per piece. + */ +export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): SplitMarkdown { + const chunks: MarkdownChunk[] = []; + const definitions: string[] = []; + let lines: string[] = []; + let first = true; + let chars = 0; + let closes: ((line: string) => boolean) | null = null; + let afterBlankLine = false; + let afterDefinition = false; + let afterHeading = false; + let definitionChars = 0; + const flush = () => { + chunks.push({ text: lines.join("\n"), lines: lines.length }); + lines = []; + chars = 0; + }; + for (const line of text.split("\n")) { + if (closes !== null) { + if (closes(line)) closes = null; + } else if (first && FRONTMATTER_OPEN.test(line)) { + let seen = 0; + closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES; + } else { + const cut = + chars >= targetChars && + (ATX_HEADING.test(line) || + (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line))); + if (cut) flush(); + closes = blockCloser(line); + // A definition cannot interrupt a paragraph, so it follows a blank line, a heading or + // another definition. + const definition: boolean = + (first || afterBlankLine || afterDefinition || afterHeading) && LINK_DEFINITION.test(line); + afterDefinition = definition; + if (definition && definitionChars + line.length < SHARED_DEFINITIONS_MAX_CHARS) { + definitions.push(line.trim()); + definitionChars += line.length + 1; + } + } + first = false; + lines.push(line); + chars += line.length + 1; + afterBlankLine = line.trim() === ""; + afterHeading = closes === null && (ATX_HEADING.test(line) || THEMATIC_BREAK.test(line)); + } + flush(); + return { chunks, definitions: definitions.join("\n") }; +} + +/** Appends shared link definitions after a piece, leaving its own offsets unchanged. */ +export function withMarkdownDefinitions(text: string, definitions: string): string { + return definitions ? `${text}\n\n${definitions}` : text; +} From ba947e37e1f721fa0b89edc6347a3d8e61e09362 Mon Sep 17 00:00:00 2001 From: bruno Date: Sun, 22 Nov 2026 23:11:55 +0000 Subject: [PATCH 124/162] fix(desktop): show ampersands in native context menu labels (#41097) Co-authored-by: Julius Marminge --- .../desktop/src/electron/ElectronMenu.test.ts | 45 +++++++++++++++++++ apps/desktop/src/electron/ElectronMenu.ts | 3 +- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 apps/desktop/src/electron/ElectronMenu.test.ts diff --git a/apps/desktop/src/electron/ElectronMenu.test.ts b/apps/desktop/src/electron/ElectronMenu.test.ts new file mode 100644 index 0000000000000..df98bdf4e9e85 --- /dev/null +++ b/apps/desktop/src/electron/ElectronMenu.test.ts @@ -0,0 +1,45 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import type * as Electron from "electron"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import { vi } from "vite-plus/test"; + +const { menu } = vi.hoisted(() => ({ + menu: { template: [] as Electron.MenuItemConstructorOptions[] }, +})); + +vi.mock("electron", () => ({ + Menu: { + buildFromTemplate: (template: Electron.MenuItemConstructorOptions[]) => { + menu.template = template; + return { popup: (options: Electron.PopupOptions) => options.callback?.() }; + }, + }, +})); + +import * as ElectronMenu from "./ElectronMenu.ts"; + +describe("ElectronMenu", () => { + it.effect("shows ampersands in labels instead of reading them as mnemonics", () => + Effect.gen(function* () { + const electronMenu = yield* ElectronMenu.make; + yield* electronMenu.showContextMenu({ + window: { webContents: { getZoomFactor: () => 1 } } as Electron.BrowserWindow, + items: [ + { id: "filter", label: "Filter by R&D" }, + { id: "more", label: "A&B", children: [{ id: "child", label: "C && D" }] }, + ], + position: Option.none(), + source: Option.none(), + }); + + assert.deepEqual( + menu.template.map((item) => item.label), + ["Filter by R&&D", "A&&B"], + ); + const submenu = menu.template[1]!.submenu as Electron.MenuItemConstructorOptions[]; + assert.equal(submenu[0]!.label, "C &&&& D"); + }).pipe(Effect.provideService(HostProcess.Platform, "win32")), + ); +}); diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index 540326346edf8..873281685054d 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -168,7 +168,8 @@ export const make = Effect.gen(function* () { } const itemOption: Electron.MenuItemConstructorOptions = { - label: item.label, + // Electron reads a single & as a mnemonic marker and drops it. + label: item.label.replaceAll("&", "&&"), enabled: !item.disabled, ...(typeof item.checked === "boolean" ? { type: "checkbox", checked: item.checked } : {}), }; From 0ee3a92b7e47846e6ec26c5f2bcd52fe4755ec64 Mon Sep 17 00:00:00 2001 From: steven-salinas <71524634+steven-salinas@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:13:38 -0500 Subject: [PATCH 125/162] fix(forgejo): follow Markdown pull request templates (#41095) Co-authored-by: Julius Marminge --- .../server/ForgejoSourceControlProvider.ts | 8 +- .../forgejoChangeRequestTemplate.test.ts | 100 ++++++++++++++++++ .../server/forgejoChangeRequestTemplate.ts | 63 +++++++++++ 3 files changed, 170 insertions(+), 1 deletion(-) create mode 100644 packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts create mode 100644 packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts index 7b6e475f99152..1c088a58e8876 100644 --- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts +++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts @@ -24,6 +24,7 @@ import { unknownRemoteProvider, } from "@t3tools/source-control-core/shared/definition"; import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullRequests.ts"; +import * as ForgejoChangeRequestTemplate from "./forgejoChangeRequestTemplate.ts"; const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError); @@ -303,7 +304,7 @@ interface UnfilteredPulls { export const make = Effect.gen(function* () { const cli = yield* ForgejoCli.ForgejoCli; const fs = yield* FileSystem.FileSystem; - const { process } = yield* SourceControlHost.SourceControlHost; + const { git, process } = yield* SourceControlHost.SourceControlHost; const request = >( input: ForgejoCli.ForgejoApiInput, schema: S, @@ -488,6 +489,11 @@ export const make = Effect.gen(function* () { }, (effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)), ), + readChangeRequestTemplate: Effect.fn("ForgejoSourceControlProvider.readChangeRequestTemplate")( + function ({ cwd, treeish }) { + return ForgejoChangeRequestTemplate.detect(cwd, treeish, git.execute); + }, + ), getChangeRequest: Effect.fn("ForgejoSourceControlProvider.getChangeRequest")(function (input) { return getPull(input).pipe( Effect.map(toForgejoChangeRequest), diff --git a/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts new file mode 100644 index 0000000000000..87f27e315406c --- /dev/null +++ b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts @@ -0,0 +1,100 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; + +import * as ForgejoCli from "./ForgejoCli.ts"; +import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts"; + +const templateRepository = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { git } = yield* SourceControlHost.SourceControlHost; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-forgejo-pr-template-" }); + const runGit = (args: ReadonlyArray) => + git.execute({ operation: "forgejoChangeRequestTemplate.test.git", cwd, args }); + yield* runGit(["init", "--initial-branch=main", "--template="]); + yield* runGit(["config", "user.email", "test@example.com"]); + yield* runGit(["config", "user.name", "Test User"]); + const provider = yield* ForgejoSourceControlProvider.make; + + return { + runGit, + writeTemplate: (relativePath: string, body: string) => + Effect.gen(function* () { + const file = path.join(cwd, relativePath); + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, body); + }), + commit: Effect.gen(function* () { + yield* runGit(["add", "-A"]); + yield* runGit(["commit", "--allow-empty", "-m", "Set pull request template"]); + }), + read: (treeish: string) => + provider.readChangeRequestTemplate?.({ cwd, treeish }) ?? Effect.succeedNone, + }; +}); + +const testLayer = Layer.mergeAll( + TestSourceControlHost.layerWithRealGit(), + Layer.mock(ForgejoCli.ForgejoCli)({}), + NodeServices.layer, +); + +it.live("reads the Gitea template committed to the target branch", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + yield* repo.commit; + yield* repo.runGit(["branch", "feature"]); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Expected on the PR"); + yield* repo.commit; + yield* repo.runGit(["checkout", "feature"]); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Working tree only"); + + assert.deepStrictEqual(yield* repo.read("main"), Option.some("## Expected on the PR")); + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.none()); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +it.live("uses the first non-empty Markdown template in Forgejo's lookup order", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + yield* repo.writeTemplate("pull_request_template.md", " \n"); + yield* repo.writeTemplate(".forgejo/PULL_REQUEST_TEMPLATE.md", "## Forgejo"); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Gitea"); + yield* repo.commit; + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.some("## Forgejo")); + + yield* repo.writeTemplate("pull_request_template.md", "## Root"); + yield* repo.commit; + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.some("## Root")); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +it.live("rejects a committed template symlink and caps the fallback blob", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + const fallback = "x".repeat(9_000); + yield* repo.writeTemplate(".github/pull_request_template.md", fallback); + yield* repo.writeTemplate("link-target", "README.md"); + yield* repo.commit; + const linkBlob = yield* repo.runGit(["rev-parse", "HEAD:link-target"]); + yield* repo.runGit([ + "update-index", + "--add", + "--cacheinfo", + `120000,${linkBlob.stdout.trim()},pull_request_template.md`, + ]); + yield* repo.runGit(["commit", "-m", "Record a template symlink"]); + + assert.deepStrictEqual( + yield* repo.read("HEAD"), + Option.some(`${fallback.slice(0, 8_000)}\n\n[truncated]`), + ); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); diff --git a/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts new file mode 100644 index 0000000000000..0ffbc33956b7d --- /dev/null +++ b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts @@ -0,0 +1,63 @@ +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; + +// Forgejo's Markdown lookup order also preserves Gitea's root, .gitea, .github order. +const TEMPLATE_PATHS = ["", ".forgejo/", ".gitea/", ".github/", "docs/"].flatMap((directory) => [ + `${directory}PULL_REQUEST_TEMPLATE.md`, + `${directory}pull_request_template.md`, +]); +const TEMPLATE_MAX_BYTES = 8_000; +const TREE_LIST_MAX_BYTES = 100_000; +const TRUNCATION_MARKER = "[truncated]"; + +type ExecuteGit = SourceControlHost.SourceControlHost["Service"]["git"]["execute"]; + +export const detect = Effect.fn("forgejoChangeRequestTemplate.detect")( + function* (cwd: string, treeish: string, executeGit: ExecuteGit) { + const listing = yield* executeGit({ + operation: "forgejoChangeRequestTemplate.listTemplates", + cwd, + args: ["ls-tree", "-z", "--full-tree", treeish, "--", ...TEMPLATE_PATHS], + maxOutputBytes: TREE_LIST_MAX_BYTES, + appendTruncationMarker: true, + }); + if (listing.stdoutTruncated) { + return Option.none(); + } + + // Read only regular blobs from the target tree, including when the worktree has a symlink. + const objectsByPath = new Map(); + for (const record of listing.stdout.split("\0")) { + const entry = /^100(?:644|755) blob ([0-9a-f]{40,64})\t(.+)$/.exec(record); + if (entry?.[1] && entry[2]) { + objectsByPath.set(entry[2], entry[1]); + } + } + + for (const path of TEMPLATE_PATHS) { + const objectId = objectsByPath.get(path); + if (!objectId) { + continue; + } + const blob = yield* executeGit({ + operation: "forgejoChangeRequestTemplate.readTemplate", + cwd, + args: ["cat-file", "blob", objectId], + maxOutputBytes: TEMPLATE_MAX_BYTES, + appendTruncationMarker: true, + }); + const template = blob.stdout.trim(); + if (template.length > 0) { + return Option.some( + blob.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER) + ? `${template}\n\n${TRUNCATION_MARKER}` + : template, + ); + } + } + return Option.none(); + }, + Effect.orElseSucceed(() => Option.none()), +); From 6ba17d97a19021a96bfa648b4534bbc561f4a606 Mon Sep 17 00:00:00 2001 From: SSH Date: Sun, 22 Nov 2026 18:16:31 -0500 Subject: [PATCH 126/162] fix(claude): show steer replies and progress lines written as thinking (#41085) Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 86 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 18 ++-- 2 files changed, 95 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 62139c5a91fdc..a4aea2ff1ffa9 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -8464,6 +8464,92 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // Default display sends the first pre-tool thinking block empty; a blank update is never promoted. + const update = "Found it: the memory file is the cause."; + it.effect.each([ + { + model: "claude-opus-5-5", + texts: ["", update], + expected: ["assistant_message"], + shown: [update], + }, + { model: "claude-opus-5", texts: ["", update], expected: ["reasoning"], shown: [update] }, + { + model: "claude-opus-5-5", + texts: ["Planning the check", " \n "], + expected: ["reasoning", "reasoning"], + }, + ] as ReadonlyArray<{ + readonly model: string; + readonly texts: ReadonlyArray; + readonly expected: ReadonlyArray; + readonly shown?: ReadonlyArray; + }>)( + "shows $model thinking $texts before a tool call as $expected", + ({ model, texts, expected, shown }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`thinking-before-tool-${model}`), + text: "Check the file", + attachments: [], + }), + ); + const snapshot = (uuid: string, content: ReadonlyArray>) => + claudeSdkFrame({ + type: "assistant", + uuid, + session_id: WAKE_NATIVE_SESSION, + parent_tool_use_id: null, + message: { id: "reply-message", model, content }, + }); + const frames = [ + ...texts.map((thinking, index) => + snapshot(`thinking-snapshot-${index}`, [ + { type: "thinking", thinking, signature: "sig" }, + ]), + ), + snapshot("tool-snapshot", [ + { type: "tool_use", id: "tool-1", name: "Bash", input: { command: "ls" } }, + ]), + makeResultFrame({ uuid: "tool-result", result: "" }), + ]; + for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame); + yield* Queue.take(harness.terminalReceipts); + const latest = new Map( + harness.events.flatMap((event) => + event.type === "turn_item.updated" && + (event.turnItem.type === "reasoning" || event.turnItem.type === "assistant_message") + ? [[event.turnItem.id, event.turnItem] as const] + : [], + ), + ); + const items = [...latest.values()]; + assert.deepEqual( + items.map((item) => item.type), + [...expected], + ); + assert.deepEqual( + items.map((item) => item.text), + [...(shown ?? texts)], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + describe("a model change after a Claude Code update", () => { /** An install as the Claude installer lays it out: one file per version and a link. */ const makeInstall = Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 30243178fce41..a4dc7c5006a8d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2690,7 +2690,7 @@ function textFromClaudeContent(content: SDKAssistantMessage["message"]["content" return content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join(""); } -// Claude 5.1+ emits at most one pre-tool text block as thinking; treat only a second consecutive thinking block as text. +// Claude 5.1+ emits pre-tool text as thinking; treat a second thinking block as text (the first may be empty in default display). function claudeWritesUpdatesAsThinking(model: string): boolean { const match = /claude-[a-z]+-(\d+)(?:-(\d{1,2}))?(?!\d)/u.exec(model); if (match === null) return false; @@ -11225,6 +11225,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if ( block.type === "tool_use" && update !== null && + update.text.trim() !== "" && update.messageId === message.message.id && update.followsThinking && claudeWritesUpdatesAsThinking(message.message.model) @@ -11249,14 +11250,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( emitEmpty: false, }); const previous = context.reasoning.lastThinking; - context.reasoning.lastThinking = completedText.trim() - ? { - messageId: message.message.id, - itemId, - text: completedText, - followsThinking: previous !== null && previous.messageId === message.message.id, - } - : null; + // Empty thinking from default display still precedes a pre-tool update. + context.reasoning.lastThinking = { + messageId: message.message.id, + itemId, + text: completedText, + followsThinking: previous !== null && previous.messageId === message.message.id, + }; } // A repeated snapshot frame must not re-emit streamed text under its uuid. if (streamedSnapshotReply !== null && unstreamedSnapshotText.join("").length === 0) { From fb23f12f1fb1895c1e14441f797a9da6ae61e75e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 15:17:46 -0800 Subject: [PATCH 127/162] feat(server): outside agents poll and stream milestones as MCP events (#40774) --- apps/server/src/mcp/McpHttpServer.ts | 44 +- apps/server/src/mcp/McpInvocationContext.ts | 7 + .../src/milestones/MilestoneEvents.test.ts | 303 ++ apps/server/src/milestones/MilestoneEvents.ts | 82 + .../src/milestones/MilestoneHub.test.ts | 120 + apps/server/src/milestones/MilestoneHub.ts | 230 ++ .../OrchestrationMilestones.test.ts | 257 ++ .../src/milestones/OrchestrationMilestones.ts | 244 ++ apps/server/src/server.ts | 9 + docs/user/outside-agents.md | 8 + packages/contracts/src/index.ts | 1 + packages/contracts/src/milestones.ts | 120 + patches/effect@4.1.5.patch | 2479 +++++++++++++++++ pnpm-lock.yaml | 517 ++-- pnpm-workspace.yaml | 2 + 15 files changed, 4163 insertions(+), 260 deletions(-) create mode 100644 apps/server/src/milestones/MilestoneEvents.test.ts create mode 100644 apps/server/src/milestones/MilestoneEvents.ts create mode 100644 apps/server/src/milestones/MilestoneHub.test.ts create mode 100644 apps/server/src/milestones/MilestoneHub.ts create mode 100644 apps/server/src/milestones/OrchestrationMilestones.test.ts create mode 100644 apps/server/src/milestones/OrchestrationMilestones.ts create mode 100644 packages/contracts/src/milestones.ts create mode 100644 patches/effect@4.1.5.patch diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index fa04f45d39062..ff55a2ea5459c 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -16,8 +16,9 @@ import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import type * as Types from "effect/Types"; import { AiError, McpProtocol, McpSchema, McpServer, Tool, Toolkit } from "effect/ai"; -import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; +import { HttpBody, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; import { + AuthSessionId, DeviceToolError, OrchestratorMcpFailure, PreviewAutomationError, @@ -30,10 +31,12 @@ import { import packageJson from "../../package.json" with { type: "json" }; import { parseBearerToken } from "../auth/EnvironmentAuth.ts"; +import * as SessionStore from "../auth/SessionStore.ts"; import * as ServerConfig from "../config.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as DeviceService from "../device/DeviceService.ts"; import * as HtmlRender from "../htmlRender/HtmlRender.ts"; +import * as MilestoneEvents from "../milestones/MilestoneEvents.ts"; import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; @@ -290,6 +293,27 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { ); const pullRequests = yield* Effect.serviceOption(PullRequestService.PullRequestService); const projections = yield* Effect.serviceOption(ProjectionStore.ProjectionStoreV2); + const sessions = yield* Effect.serviceOption(SessionStore.SessionStore); + // Auth runs once per request, so a response that streams on, such as `events/stream`, ends + // when the outside client's session is revoked or expires. + const endWithSession = ( + response: HttpServerResponse.HttpServerResponse, + client: McpInvocationContext.McpClientCaller | undefined, + ) => { + const body = response.body; + if (client === undefined || Option.isNone(sessions) || body._tag !== "Stream") return response; + const invalidated = sessions.value + .awaitInvalidation(AuthSessionId.make(client.sessionId)) + .pipe(Effect.ignore); + return HttpServerResponse.setBody( + response, + HttpBody.stream( + Stream.interruptWhen(body.stream, invalidated), + body.contentType, + body.contentLength, + ), + ); + }; // Every request reads it, and a remote added mid-thread shows the tools within a minute. const forgeOfThread = yield* Cache.make({ capacity: 1_000, @@ -363,6 +387,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { return yield* httpEffect.pipe( Effect.provideService(McpInvocationContext.McpInvocationContext, admitted), Effect.map(normalizeMcpHttpResponse), + Effect.map((response) => endWithSession(response, admitted.client)), Effect.map((response) => linkExpiresAt === undefined ? response @@ -1469,4 +1494,19 @@ export const layerToolSearch = Layer.mergeAll( layerDeferredListing, ).pipe(Layer.provide(layerToolExposure)); -export const layer = layerMcpTransport(Layer.mergeAll(layerTools, layerToolSearch)); +/** + * Milestones as MCP events (SEP-3415) for outside clients to poll or stream. Protocol-level, so no + * thread lists them. + */ +export const layerMilestoneEvents = Layer.effectDiscard( + Effect.gen(function* () { + const annotations = Context.make(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromThreads); + for (const options of yield* MilestoneEvents.make) { + yield* McpServer.registerEvent({ ...options, annotations }); + } + }), +); + +export const layer = layerMcpTransport( + Layer.mergeAll(layerTools, layerToolSearch, layerMilestoneEvents), +); diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index bfc35be9baadd..f1a070e86b9e3 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -216,6 +216,13 @@ export const hiddenWithoutBackgroundWait = (): boolean => { ); }; +/** `McpSchema.EnabledWhen` for tools only a client outside a thread drives, such as the CLI. */ +export const hiddenFromThreads = (): boolean => { + const fiber = Fiber.getCurrent(); + const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext); + return scope?.thread === undefined; +}; + /** `McpSchema.EnabledWhen` for tools that only serve links, hidden while the beta is off. */ export const hiddenWhileLinksOff = (): boolean => { const fiber = Fiber.getCurrent(); diff --git a/apps/server/src/milestones/MilestoneEvents.test.ts b/apps/server/src/milestones/MilestoneEvents.test.ts new file mode 100644 index 0000000000000..bdf102b4dce6f --- /dev/null +++ b/apps/server/src/milestones/MilestoneEvents.test.ts @@ -0,0 +1,303 @@ +import { NodeHttpServer } from "@effect/platform-node"; +import { expect, it } from "@effect/vitest"; +import { + EnvironmentId, + type MilestoneEvent, + MilestoneId, + ProjectId, + ProviderInstanceId, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { HttpBody, HttpClient, HttpRouter } from "effect/http"; + +import * as SessionStore from "../auth/SessionStore.ts"; +import * as McpHttpServer from "../mcp/McpHttpServer.ts"; +import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; +import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as MilestoneHub from "./MilestoneHub.ts"; + +const environmentId = EnvironmentId.make("environment-milestone-events-test"); +const clientToken = "clientTokenWithoutDots"; +const threadToken = "threadTokenWithoutDots"; +const scopes: Record = { + [clientToken]: { + environmentId, + requestNamespace: "client-session", + thread: undefined, + client: { sessionId: "client-session", label: "Bot", access: "read-only" }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }, + [threadToken]: { + environmentId, + requestNamespace: "provider-session", + thread: { + threadId: ThreadId.make("thread-agent"), + providerSessionId: "provider-session", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }, +}; + +const settled = ( + id: string, + options: { readonly project?: string; readonly at?: string } = {}, +): MilestoneEvent => ({ + id: MilestoneId.make(id), + type: "thread.run_settled", + occurredAt: options.at ?? "1970-01-01T00:00:00.000Z", + projectId: ProjectId.make(options.project ?? "project:a"), + threadId: ThreadId.make(`thread:${id}`), + parentThreadId: null, + actor: { type: "agent" }, + isSubagentChild: false, + runId: RunId.make(`run:${id}`), + outcome: "completed", +}); + +type JsonRpcResponse = { + readonly result?: Record; + readonly error?: { readonly code: number; readonly data?: unknown }; +}; + +const serve = Effect.gen(function* () { + const revoked = yield* Deferred.make(); + yield* HttpRouter.serve( + McpHttpServer.layerMcpTransport(McpHttpServer.layerMilestoneEvents).pipe( + Layer.provide(ServerSettings.layerTest()), + Layer.provide( + Layer.mock(SessionStore.SessionStore)({ + cookieName: "t3-session", + legacyCookieName: undefined, + awaitInvalidation: (sessionId) => + sessionId === "client-session" ? Deferred.await(revoked) : Effect.never, + }), + ), + Layer.provide( + Layer.mock(McpSessionRegistry.McpSessionRegistry)({ + resolve: (presented) => + Effect.succeed(scopes[presented] as McpInvocationContext.McpThreadInvocationScope), + }), + ), + ), + { disableListenLog: true, disableLogger: true }, + ).pipe(Layer.build); + const http = yield* HttpClient.HttpClient; + const post = ( + method: string, + params: Record = {}, + options: { readonly token?: string; readonly name?: string | null; readonly id?: number } = {}, + ) => { + const name = options.name === undefined ? params.name : options.name; + return http.post("/mcp", { + headers: { + accept: "application/json, text/event-stream", + authorization: `Bearer ${options.token ?? clientToken}`, + "mcp-method": method, + "mcp-protocol-version": "2026-07-28", + ...(typeof name === "string" ? { "mcp-name": name } : {}), + }, + body: HttpBody.text( + JSON.stringify({ + jsonrpc: "2.0", + id: options.id ?? 1, + method, + params: { + ...params, + _meta: { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientCapabilities": { + extensions: { "io.modelcontextprotocol/events": {} }, + }, + "io.modelcontextprotocol/clientInfo": { name: "bot", version: "1.0.0" }, + }, + }, + }), + "application/json", + ), + }); + }; + const call = (...args: Parameters) => + post(...args).pipe( + Effect.flatMap((response) => response.json), + Effect.map((body) => body as JsonRpcResponse), + ); + const poll = (args: Record) => + call("events/poll", { name: "thread.run_settled", ...args }).pipe( + Effect.map(({ result }) => ({ + cursor: result!.cursor as string, + truncated: result!.truncated as boolean, + hasMore: result!.hasMore as boolean, + ids: (result!.events as ReadonlyArray<{ eventId: string }>).map((event) => event.eventId), + })), + ); + const stream = (args: Record, id = 7) => + post("events/stream", { name: "thread.run_settled", ...args }, { id }).pipe( + Effect.flatMap((response) => + response.stream.pipe( + Stream.decodeText, + Stream.splitLines, + Stream.filter((line) => line.startsWith("data: ")), + Stream.map( + (line) => + JSON.parse(line.slice("data: ".length)) as { + readonly method: string; + readonly params: Record; + }, + ), + Stream.toQueue({ capacity: "unbounded" }), + ), + ), + ); + return { post, call, poll, stream, revoke: Deferred.succeed(revoked, undefined) }; +}); + +const layerTest = Layer.mergeAll(MilestoneHub.layer, NodeHttpServer.layerTest); + +it.effect("advertises the extension and lists each milestone type to outside clients only", () => + Effect.gen(function* () { + const { call } = yield* serve; + const discovered = yield* call("server/discover"); + expect(discovered.result!.capabilities.extensions).toEqual({ + "io.modelcontextprotocol/events": {}, + }); + + const { events } = (yield* call("events/list")).result!; + expect(events).toHaveLength(6); + const settledType = events.find( + (event: { name: string }) => event.name === "thread.run_settled", + ); + expect(settledType.delivery).toEqual(["poll", "push"]); + expect(Object.keys(settledType.inputSchema.properties)).toEqual([ + "projectIds", + "threadIds", + "includeSubagentChildren", + ]); + expect(settledType.payloadSchema.properties.outcome).toBeDefined(); + expect((yield* call("events/list", {}, { token: threadToken })).result!.events).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("polls from now, then pages forward and says when a cursor fell behind", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { poll } = yield* serve; + yield* hub.publish(settled("before")); + + // A null cursor starts from now: nothing earlier is replayed. + const bootstrap = yield* poll({ cursor: null }); + expect(bootstrap).toMatchObject({ ids: [], truncated: false, hasMore: false }); + + yield* hub.publish(settled("a")); + yield* hub.publish(settled("b", { project: "project:b" })); + yield* hub.publish(settled("c")); + const first = yield* poll({ + cursor: bootstrap.cursor, + arguments: { projectIds: ["project:a"] }, + maxEvents: 1, + }); + expect(first).toMatchObject({ ids: ["a"], hasMore: true, truncated: false }); + const rest = yield* poll({ cursor: first.cursor, arguments: { projectIds: ["project:a"] } }); + expect(rest).toMatchObject({ ids: ["c"], hasMore: false }); + expect(yield* poll({ cursor: rest.cursor })).toMatchObject({ ids: [] }); + + // A cursor from before a restart replays what is kept, and says some may be missing. + expect(yield* poll({ cursor: "previous-boot.3" })).toMatchObject({ + ids: ["before", "a", "b", "c"], + truncated: true, + }); + yield* TestClock.adjust("10 minutes"); + yield* hub.publish(settled("fresh", { at: "1970-01-01T00:10:00.000Z" })); + expect(yield* poll({ cursor: bootstrap.cursor, maxAgeMs: 60_000 })).toMatchObject({ + ids: ["fresh"], + truncated: true, + }); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("rejects a mismatched Mcp-Name, an unknown event and webhook delivery", () => + Effect.gen(function* () { + const { post, call } = yield* serve; + const params = { name: "thread.run_settled", cursor: null }; + const missing = yield* post("events/poll", params, { name: null }); + expect(missing.status).toBe(400); + expect(((yield* missing.json) as JsonRpcResponse).error?.code).toBe(-32020); + const mismatched = yield* post("events/poll", params, { name: "thread.needs_input" }); + expect(mismatched.status).toBe(400); + + expect((yield* call("events/poll", { name: "nope", cursor: null })).error).toMatchObject({ + code: -32023, + data: { kind: "event" }, + }); + expect( + (yield* call("events/subscribe", { + name: "thread.run_settled", + delivery: { mode: "webhook", url: "https://example.com/hook", secret: "whsec_x" }, + })).error, + ).toMatchObject({ code: -32026, data: { feature: "deliveryMode", value: "webhook" } }); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("streams live milestones after active, replays from a cursor and sends heartbeats", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { stream } = yield* serve; + yield* hub.publish(settled("a")); + + const live = yield* stream({ cursor: null, heartbeatMs: 5_000 }, 7); + const active = yield* Queue.take(live); + expect(active).toMatchObject({ + method: "notifications/events/active", + params: { truncated: false, heartbeatMs: 5_000 }, + }); + expect(active.params._meta["io.modelcontextprotocol/subscriptionId"]).toBe(7); + + yield* hub.publish(settled("b", { project: "project:b" })); + const event = yield* Queue.take(live); + expect(event).toMatchObject({ + method: "notifications/events/event", + params: { + eventId: "b", + name: "thread.run_settled", + data: { id: "b", projectId: "project:b" }, + _meta: { "io.modelcontextprotocol/subscriptionId": 7 }, + }, + }); + + // The heartbeat is due 5 seconds after the last message, however late the loop reads the clock. + yield* TestClock.adjust("5 seconds"); + expect(yield* Queue.take(live)).toMatchObject({ + method: "notifications/events/heartbeat", + params: { cursor: event.params.cursor }, + }); + + const replay = yield* stream({ cursor: "previous-boot.1" }, 8); + expect(yield* Queue.takeN(replay, 3)).toMatchObject([ + { method: "notifications/events/active", params: { truncated: true } }, + { method: "notifications/events/event", params: { eventId: "a" } }, + { method: "notifications/events/event", params: { eventId: "b" } }, + ]); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("ends an open stream when the client's session is revoked", () => + Effect.gen(function* () { + const { stream, revoke } = yield* serve; + const live = yield* stream({ cursor: null }); + expect(yield* Queue.take(live)).toMatchObject({ method: "notifications/events/active" }); + + yield* revoke; + expect((yield* Effect.exit(Queue.take(live)))._tag).toBe("Failure"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); diff --git a/apps/server/src/milestones/MilestoneEvents.ts b/apps/server/src/milestones/MilestoneEvents.ts new file mode 100644 index 0000000000000..5b07d64b3aa59 --- /dev/null +++ b/apps/server/src/milestones/MilestoneEvents.ts @@ -0,0 +1,82 @@ +import { + type MilestoneEvent as MilestoneEventValue, + MilestoneEvent, + ProjectId, + ThreadId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import type { McpServer } from "effect/ai"; + +import * as MilestoneHub from "./MilestoneHub.ts"; + +// Matches the hub's buffer, so a poll can drain everything it keeps at once. +const MAX_EVENTS = 1_000; +const DEFAULT_EVENTS = 100; + +const Parameters = Schema.Struct({ + projectIds: Schema.optional(Schema.Array(ProjectId)), + threadIds: Schema.optional(Schema.Array(ThreadId)), + includeSubagentChildren: Schema.optional( + Schema.Boolean.annotate({ description: "Also subagent threads." }), + ), +}); + +const DESCRIPTIONS: Record = { + "thread.run_settled": "A thread's turn ended: completed, failed, interrupted or cancelled.", + "thread.needs_input": "An agent waits on a person to answer a question or approve an action.", + "thread.input_resolved": "A question or approval an agent waited on was answered, or lapsed.", + "thread.guest_request": "A guest on a shared thread asked for something.", + "thread.guest_request_resolved": "A guest's request was sent, dismissed, or its link closed.", + "pr.watch_wake": "A watched pull request changed and woke its thread.", +}; + +const occurrence = ({ event }: MilestoneHub.PositionedMilestone) => ({ + eventId: event.id, + timestamp: event.occurredAt, + data: event, +}); + +/** + * Each milestone type as an MCP event type (SEP-3415), for outside clients to poll or stream. + * Cursors are the hub's, so a client that was away catches up on what the hub still keeps. + */ +export const make = Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + return MilestoneEvent.members.map((payload) => { + const type = payload.fields.type.literal; + const filterOf = (args: typeof Parameters.Type) => ({ ...args, types: [type] }); + return { + name: type, + description: DESCRIPTIONS[type], + parameters: Parameters, + payload, + poll: (args, request) => + hub + .read({ + cursor: request.cursor, + maxAgeMs: request.maxAgeMs, + filter: filterOf(args), + limit: Math.min(request.maxEvents ?? DEFAULT_EVENTS, MAX_EVENTS), + }) + .pipe(Effect.map((page) => ({ ...page, events: page.events.map(occurrence) }))), + stream: (args, request) => + hub + .follow({ cursor: request.cursor, maxAgeMs: request.maxAgeMs, filter: filterOf(args) }) + .pipe( + Effect.map(({ cursor, truncated, items }) => ({ + cursor, + truncated, + items: items.pipe( + Stream.map((item): McpServer.EventStreamItem => + item._tag === "Milestone" + ? { _tag: "Event", cursor: item.cursor, ...occurrence(item) } + : item, + ), + ), + })), + ), + } satisfies McpServer.EventOptions; + }); +}); diff --git a/apps/server/src/milestones/MilestoneHub.test.ts b/apps/server/src/milestones/MilestoneHub.test.ts new file mode 100644 index 0000000000000..0361c81f4f7e0 --- /dev/null +++ b/apps/server/src/milestones/MilestoneHub.test.ts @@ -0,0 +1,120 @@ +import { assert, it } from "@effect/vitest"; +import { type MilestoneEvent, MilestoneId, ProjectId, RunId, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import * as MilestoneHub from "./MilestoneHub.ts"; + +const settled = ( + id: string, + options: { readonly child?: boolean; readonly project?: string } = {}, +): MilestoneEvent => ({ + id: MilestoneId.make(id), + type: "thread.run_settled", + occurredAt: "2026-11-20T00:00:00.000Z", + projectId: ProjectId.make(options.project ?? "project:a"), + threadId: ThreadId.make(`thread:${id}`), + parentThreadId: options.child === true ? ThreadId.make("thread:parent") : null, + actor: { type: "agent" }, + isSubagentChild: options.child === true, + runId: RunId.make(`run:${id}`), + outcome: "completed", +}); +const ids = (events: Iterable) => [...events].map((event) => event.id); + +it.effect("fans out to every subscriber, muting subagent children unless asked for", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const muted = yield* hub.subscribe(); + const everything = yield* hub.subscribe({ includeSubagentChildren: true }); + const projectB = yield* hub.subscribe({ projectIds: [ProjectId.make("project:b")] }); + + yield* hub.publish(settled("a")); + yield* hub.publish(settled("child", { child: true })); + // A repeat of an id is the same milestone. + yield* hub.publish(settled("a")); + yield* hub.publish(settled("b", { project: "project:b" })); + + assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(muted, 2))), ["a", "b"]); + assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(everything, 3))), [ + "a", + "child", + "b", + ]); + assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(projectB, 1))), ["b"]); + assert.deepStrictEqual(ids((yield* hub.recent()).events), ["a", "b"]); + }).pipe(Effect.scoped, Effect.provide(MilestoneHub.layer)), +); + +it.effect("pages forward from a kept id and says when the answer is cut short", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + for (let index = 0; index < 1_005; index++) yield* hub.publish(settled(`e${index}`)); + + const after = yield* hub.recent({ sinceId: MilestoneId.make("e1000"), limit: 3 }); + assert.deepStrictEqual(ids(after.events), ["e1001", "e1002", "e1003"]); + assert.isTrue(after.truncated); + const rest = yield* hub.recent({ sinceId: MilestoneId.make("e1003") }); + assert.deepStrictEqual([ids(rest.events), rest.truncated], [["e1004"], false]); + + // The oldest fell out of the buffer, so a caller that last saw it missed some. + const gone = yield* hub.recent({ sinceId: MilestoneId.make("e2"), limit: 2 }); + assert.deepStrictEqual([ids(gone.events), gone.truncated], [["e1003", "e1004"], true]); + const newest = yield* hub.recent({ limit: 1_000 }); + assert.deepStrictEqual( + [newest.events.length, newest.events[0]?.id, newest.truncated], + [1_000, "e5", false], + ); + }).pipe(Effect.provide(MilestoneHub.layer)), +); + +it.effect("skips expired milestones even when they arrive after newer ones", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + yield* TestClock.adjust("10 minutes"); + const { cursor } = yield* hub.read({ cursor: null, limit: 1 }); + yield* hub.publish({ ...settled("fresh"), occurredAt: "1970-01-01T00:10:00.000Z" }); + yield* hub.publish({ ...settled("expired"), occurredAt: "1970-01-01T00:08:59.000Z" }); + yield* hub.publish({ ...settled("at-cutoff"), occurredAt: "1970-01-01T00:09:00.000Z" }); + + const first = yield* hub.read({ cursor, maxAgeMs: 60_000, limit: 1 }); + assert.deepStrictEqual(ids(first.events.map(({ event }) => event)), ["fresh"]); + assert.isTrue(first.hasMore); + assert.isTrue(first.truncated); + const rest = yield* hub.read({ cursor: first.cursor, maxAgeMs: 60_000, limit: 1 }); + assert.deepStrictEqual(ids(rest.events.map(({ event }) => event)), ["at-cutoff"]); + assert.isFalse(rest.hasMore); + }).pipe(Effect.provide(MilestoneHub.layer)), +); + +it.effect("a follower's replay ends at the position it checked, past its last match", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { cursor } = yield* hub.read({ cursor: null, limit: 1 }); + yield* hub.publish(settled("a")); + yield* hub.publish(settled("b", { project: "project:b" })); + + const { items } = yield* hub.follow({ + cursor, + filter: { projectIds: [ProjectId.make("project:a")] }, + }); + const [milestone, position] = yield* Stream.runCollect(Stream.take(items, 2)); + assert.strictEqual(milestone?._tag === "Milestone" ? milestone.event.id : undefined, "a"); + assert.strictEqual(position?._tag, "Position"); + assert.strictEqual((yield* hub.read({ cursor: null, limit: 1 })).cursor, position?.cursor); + }).pipe(Effect.scoped, Effect.provide(MilestoneHub.layer)), +); + +it.effect("tells a follower that fell behind the subscriber backlog where its gap is", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { items } = yield* hub.follow({ cursor: null }); + // Published before the follower reads, so the backlog drops the oldest. + for (let index = 0; index < 300; index++) yield* hub.publish(settled(`e${index}`)); + + const [gap, first] = yield* Stream.runCollect(Stream.take(items, 2)); + assert.strictEqual(gap?._tag, "Gap"); + assert.strictEqual(first?._tag === "Milestone" ? first.event.id : undefined, "e44"); + }).pipe(Effect.scoped, Effect.provide(MilestoneHub.layer)), +); diff --git a/apps/server/src/milestones/MilestoneHub.ts b/apps/server/src/milestones/MilestoneHub.ts new file mode 100644 index 0000000000000..c7649fa38cceb --- /dev/null +++ b/apps/server/src/milestones/MilestoneHub.ts @@ -0,0 +1,230 @@ +import { + type MilestoneEvent, + type MilestoneFilter, + type MilestoneId, + milestoneMatches, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as PubSub from "effect/PubSub"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +// Enough for a client that was away for a while to catch up; older news is in the stores. +const KEPT = 1_000; +// Ids outlive the events they name, so a late repeat of an evicted milestone is still one. +const IDS_KEPT = 4 * KEPT; +// A subscriber this far behind loses its oldest milestones, not the server's memory. +const SUBSCRIBER_BACKLOG = 256; +const RECENT_LIMIT = 200; + +/** A milestone and the cursor that reads on after it. */ +export interface PositionedMilestone { + readonly event: MilestoneEvent; + readonly cursor: string; +} + +/** + * Where a cursor read starts. `null` starts from now. A cursor from before a restart or no longer + * kept starts at the oldest kept milestone; `maxAgeMs` skips those older than that. + */ +export interface MilestoneReadOptions { + readonly cursor: string | null; + readonly maxAgeMs?: number | undefined; + readonly filter?: MilestoneFilter | undefined; +} + +/** What a follower reads after its start: a milestone, a position passed without one, or a gap. */ +export type MilestoneFollowItem = + | ({ readonly _tag: "Milestone" } & PositionedMilestone) + | { readonly _tag: "Position"; readonly cursor: string } + | { readonly _tag: "Gap"; readonly cursor: string }; + +export class MilestoneHub extends Context.Service< + MilestoneHub, + { + /** Publishing an id seen before does nothing, so a feeder may repeat itself. */ + readonly publish: (event: MilestoneEvent) => Effect.Effect; + /** + * Milestones published from now on that match `filter`. Subscribed when this runs, so a caller + * catching up subscribes first, then reads `recent`, and drops ids it already has. + */ + readonly subscribe: ( + filter?: MilestoneFilter, + ) => Effect.Effect, never, Scope.Scope>; + /** + * Kept milestones, oldest first: those after `sinceId`, or the newest. `truncated` says the + * answer is incomplete: `sinceId` is no longer kept, or `limit` cut it short. + */ + readonly recent: (options?: { + readonly sinceId?: MilestoneId | undefined; + readonly limit?: number | undefined; + readonly filter?: MilestoneFilter | undefined; + }) => Effect.Effect<{ + readonly events: ReadonlyArray; + readonly truncated: boolean; + }>; + /** + * Matching milestones after a cursor, at most `limit`. `cursor` reads on from there: after the + * last one returned when `hasMore`, otherwise from now. `truncated` says some were skipped. + */ + readonly read: (options: MilestoneReadOptions & { readonly limit: number }) => Effect.Effect<{ + readonly events: ReadonlyArray; + readonly cursor: string; + readonly truncated: boolean; + readonly hasMore: boolean; + }>; + /** The milestones `read` would return, then live ones, each once. */ + readonly follow: (options: MilestoneReadOptions) => Effect.Effect< + { + readonly cursor: string; + readonly truncated: boolean; + readonly items: Stream.Stream; + }, + never, + Scope.Scope + >; + } +>()("t3/milestones/MilestoneHub") {} + +interface Kept { + readonly event: MilestoneEvent; + readonly seq: number; +} + +const make = Effect.gen(function* () { + const pubsub = yield* PubSub.sliding(SUBSCRIBER_BACKLOG); + const kept: Array = []; + const seen = new Set(); + let seq = 0; + // Sequence numbers restart with the server; the epoch tells an old cursor from a new one. + const epoch = (yield* Clock.currentTimeMillis).toString(36); + const cursorAt = (at: number) => `${epoch}.${at}`; + const seqOf = (cursor: string) => { + const [cursorEpoch, at] = cursor.split("."); + const value = Number(at); + return cursorEpoch === epoch && Number.isSafeInteger(value) && value >= 0 && value <= seq + ? value + : undefined; + }; + + const remember = (event: MilestoneEvent) => { + if (seen.has(event.id)) return undefined; + seen.add(event.id); + if (seen.size > IDS_KEPT) seen.delete(seen.values().next().value!); + const entry = { event, seq: ++seq }; + kept.push(entry); + if (kept.length > KEPT) kept.shift(); + return entry; + }; + + // The kept milestones after the cursor, and whether milestones after it were skipped. + const after = (options: MilestoneReadOptions, now: number) => { + if (options.cursor === null) return { entries: [], truncated: false }; + const from = seqOf(options.cursor); + const oldest = kept[0]?.seq ?? seq + 1; + let entries = from === undefined ? kept : kept.filter((entry) => entry.seq > from); + let truncated = from === undefined || from < oldest - 1; + if (options.maxAgeMs !== undefined) { + // Kept in publication order, which `occurredAt` need not follow, so each one is checked. + const floor = now - options.maxAgeMs; + const young = entries.filter((entry) => Date.parse(entry.event.occurredAt) >= floor); + truncated ||= young.length < entries.length; + entries = young; + } + return { entries, truncated }; + }; + + const positioned = (entry: Kept): PositionedMilestone => ({ + event: entry.event, + cursor: cursorAt(entry.seq), + }); + + const subscribe = Effect.fn("MilestoneHub.subscribe")(function* (filter?: MilestoneFilter) { + const subscription = yield* PubSub.subscribe(pubsub); + return Stream.fromSubscription(subscription).pipe( + Stream.map((entry) => entry.event), + Stream.filter((event) => milestoneMatches(event, filter)), + ); + }); + + const recent: MilestoneHub["Service"]["recent"] = Effect.fn("MilestoneHub.recent")(function* ( + options = {}, + ) { + const limit = Math.max(1, Math.min(options.limit ?? RECENT_LIMIT, KEPT)); + const at = + options.sinceId === undefined + ? -1 + : kept.findIndex((entry) => entry.event.id === options.sinceId); + const gap = options.sinceId !== undefined && at === -1; + const matching = kept + .slice(at + 1) + .map((entry) => entry.event) + .filter((event) => milestoneMatches(event, options.filter)); + // Paging forward from a known id; otherwise the newest, as there is no place to start. + const events = + options.sinceId !== undefined && !gap ? matching.slice(0, limit) : matching.slice(-limit); + return yield* Effect.succeed({ events, truncated: gap || events.length < matching.length }); + }); + + const read: MilestoneHub["Service"]["read"] = Effect.fn("MilestoneHub.read")(function* (options) { + const from = after(options, yield* Clock.currentTimeMillis); + const matching = from.entries.filter((entry) => milestoneMatches(entry.event, options.filter)); + const events = matching.slice(0, Math.max(1, options.limit)); + const hasMore = events.length < matching.length; + return { + events: events.map(positioned), + cursor: hasMore ? cursorAt(events.at(-1)!.seq) : cursorAt(seq), + truncated: from.truncated, + hasMore, + }; + }); + + return MilestoneHub.of({ + publish: Effect.fn("MilestoneHub.publish")(function* (event) { + const entry = remember(event); + if (entry === undefined) return; + yield* PubSub.publish(pubsub, entry); + }), + subscribe, + recent, + read, + follow: Effect.fn("MilestoneHub.follow")(function* (options) { + // Subscribed before reading the buffer, so nothing published in between is lost. + const live = Stream.fromSubscription(yield* PubSub.subscribe(pubsub)); + const caught = yield* read({ ...options, limit: KEPT }); + const first = caught.events[0]; + let last = seqOf(caught.cursor)!; + const items = live.pipe( + Stream.flatMap((entry) => { + if (entry.seq <= last) return Stream.empty; + // A follower that fell behind the subscriber backlog lost the milestones in between. + const gap = entry.seq > last + 1; + last = entry.seq; + const item: MilestoneFollowItem = milestoneMatches(entry.event, options.filter) + ? { _tag: "Milestone", ...positioned(entry) } + : { _tag: "Position", cursor: cursorAt(entry.seq) }; + return Stream.fromIterable( + gap ? [{ _tag: "Gap" as const, cursor: cursorAt(entry.seq - 1) }, item] : [item], + ); + }), + ); + return { + // The position before the first replayed milestone, which each one then advances. + cursor: first === undefined ? caught.cursor : cursorAt(seqOf(first.cursor)! - 1), + truncated: caught.truncated, + items: Stream.fromIterable([ + ...caught.events.map((event): MilestoneFollowItem => ({ _tag: "Milestone", ...event })), + // Replay checked past its last match; told after it, so no client skips a replayed one. + ...(first !== undefined && caught.events.at(-1)!.cursor !== caught.cursor + ? [{ _tag: "Position" as const, cursor: caught.cursor }] + : []), + ]).pipe(Stream.concat(items)), + }; + }), + }); +}); + +export const layer = Layer.effect(MilestoneHub, make); diff --git a/apps/server/src/milestones/OrchestrationMilestones.test.ts b/apps/server/src/milestones/OrchestrationMilestones.test.ts new file mode 100644 index 0000000000000..7930b2ab8097b --- /dev/null +++ b/apps/server/src/milestones/OrchestrationMilestones.test.ts @@ -0,0 +1,257 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + EventId, + GuestMessageId, + GuestShareId, + MessageId, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type OrchestrationV2Run, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + RuntimeRequestId, + ThreadId, + type ThreadGuestMessage, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as EffectOutbox from "../orchestration-v2/EffectOutbox.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as MilestoneHub from "./MilestoneHub.ts"; +import * as OrchestrationMilestones from "./OrchestrationMilestones.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "gpt-5.1-codex" }; +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed for milestones"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = OrchestrationMilestones.layer.pipe( + Layer.provideMerge(MilestoneHub.layer), + Layer.provideMerge( + Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "milestones" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), + ), + ), +); + +it.effect("tells each thread transition once, with its lineage", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const feeder = yield* OrchestrationMilestones.OrchestrationMilestones; + const hub = yield* MilestoneHub.MilestoneHub; + const parentThreadId = ThreadId.make("thread:milestone-parent"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-milestone-parent"), + threadId: parentThreadId, + projectId: ProjectId.make("project:milestones"), + title: "Parent", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-milestone-parent"), + threadId: parentThreadId, + messageId: MessageId.make("message:milestone-parent"), + text: "Delegate the research", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const parentRun = (yield* projections.getThreadProjection(parentThreadId)).runs[0]!; + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate-milestone-task"), + parentThreadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Research the sources", + completionWake: "settled_only", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "agent", + creationSource: "mcp", + }); + const childThreadId = (yield* projections.getThreadProjection(parentThreadId)).subagents[0]! + .childThreadId!; + const childRun = (yield* projections.getThreadRecords(childThreadId, ["runs"])).runs[0]!; + const parent = yield* projections.getThread(parentThreadId); + const now = yield* DateTime.now; + const base = (id: string, threadId: ThreadId) => ({ + id: EventId.make(id), + threadId, + occurredAt: now, + }); + const ended = (id: string, run: OrchestrationV2Run, status: OrchestrationV2Run["status"]) => + ({ + ...base(id, run.threadId), + type: "run.updated", + runId: run.id, + payload: { ...run, status, startedAt: now, completedAt: now }, + }) satisfies OrchestrationV2DomainEvent; + const request = (id: string, status: "pending" | "resolved") => + ({ + ...base(id, parentThreadId), + type: "runtime-request.updated", + payload: { + id: RuntimeRequestId.make("request:milestone"), + nodeId: parentRun.rootNodeId!, + providerTurnId: null, + nativeRequestRef: null, + kind: "command", + status, + responseCapability: { type: "message" }, + createdAt: now, + resolvedAt: status === "pending" ? null : now, + }, + }) satisfies OrchestrationV2DomainEvent; + const shareId = GuestShareId.make("share:milestone"); + const guestMessage = (id: string, status: ThreadGuestMessage["status"]) => ({ + id: GuestMessageId.make(id), + text: "Can you also check the docs?", + status, + submittedAt: DateTime.formatIso(now), + }); + const shared = ( + id: string, + messages: ReadonlyArray | null, + ): OrchestrationV2DomainEvent => { + const payload: OrchestrationV2AppThread = { + ...parent, + guestShare: + messages === null + ? null + : { + id: shareId, + host: "tunnel.example", + createdAt: DateTime.formatIso(now), + expiresAt: DateTime.formatIso(now), + guestName: "Sam", + messages, + }, + }; + return { ...base(id, parentThreadId), type: "thread.guest-share-updated", payload }; + }; + const wake = { + ...base("event:wake", parentThreadId), + type: "message.updated", + payload: { + id: MessageId.make("message:pr-wake"), + threadId: parentThreadId, + runId: null, + nodeId: null, + role: "user", + text: "Checks finished on #7.", + attachments: [], + streaming: false, + createdAt: now, + updatedAt: now, + createdBy: "system", + creationSource: "server", + notification: { + source: { + kind: "monitor", + pullRequest: { + host: "github.com", + repository: "me/app", + number: 7, + watchStartedAt: DateTime.formatIso(now), + headSha: "abc", + watchEnded: true, + }, + }, + outcome: "completed", + summary: "#7: checks passed", + }, + }, + } satisfies OrchestrationV2DomainEvent; + + for (const event of [ + ended("event:parent-done", parentRun, "completed"), + // A later update of a settled run is not a second settlement. + ended("event:parent-done-again", parentRun, "completed"), + ended("event:child-failed", childRun, "failed"), + request("event:asked", "pending"), + request("event:answered", "resolved"), + shared("event:guest-asked", [guestMessage("guest:one", "pending")]), + shared("event:guest-sent", [guestMessage("guest:one", "sent")]), + shared("event:guest-asked-again", [ + guestMessage("guest:one", "sent"), + guestMessage("guest:two", "pending"), + ]), + shared("event:guest-closed", null), + wake, + wake, + ]) { + yield* feeder.handle(event); + } + + const { events } = yield* hub.recent({ filter: { includeSubagentChildren: true } }); + assert.deepStrictEqual( + events.map((event) => [ + event.id, + event.threadId, + event.parentThreadId, + event.isSubagentChild, + ]), + [ + [`thread.run_settled:${parentRun.id}`, parentThreadId, null, false], + [`thread.run_settled:${childRun.id}`, childThreadId, parentThreadId, true], + ["thread.needs_input:request:milestone", parentThreadId, null, false], + ["thread.input_resolved:request:milestone", parentThreadId, null, false], + ["thread.guest_request:guest:one", parentThreadId, null, false], + ["thread.guest_request_resolved:guest:one", parentThreadId, null, false], + ["thread.guest_request:guest:two", parentThreadId, null, false], + ["thread.guest_request_resolved:guest:two", parentThreadId, null, false], + ["pr.watch_wake:message:pr-wake", parentThreadId, null, false], + ], + ); + const [, child, asked, answered, , sent, , closed, woke] = events; + assert.deepInclude(child, { outcome: "failed", projectId: parent.projectId }); + assert.deepInclude(asked, { kind: "approval" }); + assert.deepInclude(answered, { resolution: "resolved", actor: { type: "user" } }); + assert.deepInclude(sent, { resolution: "sent" }); + assert.deepInclude(closed, { resolution: "closed" }); + assert.deepInclude(woke, { + pullRequests: [{ host: "github.com", repository: "me/app", number: 7 }], + watchEnded: true, + summary: "#7: checks passed", + }); + // A subscriber that did not ask for children never hears of the child's run. + assert.notInclude( + (yield* hub.recent()).events.map((event) => event.threadId), + childThreadId, + ); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/milestones/OrchestrationMilestones.ts b/apps/server/src/milestones/OrchestrationMilestones.ts new file mode 100644 index 0000000000000..c50c460ec4814 --- /dev/null +++ b/apps/server/src/milestones/OrchestrationMilestones.ts @@ -0,0 +1,244 @@ +import { + type GuestMessageId, + type GuestShareId, + type MilestoneActor, + type MilestoneEvent, + MilestoneId, + type MilestoneInputKind, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type OrchestrationV2RuntimeRequest, + type ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as MilestoneHub from "./MilestoneHub.ts"; + +const inputKind = (kind: OrchestrationV2RuntimeRequest["kind"]): MilestoneInputKind | null => { + switch (kind) { + case "user_input": + case "mcp-elicitation": + return "user_input"; + case "command": + case "file-read": + case "file-change": + case "permission": + return "approval"; + default: + return null; + } +}; + +/** Turns orchestration events into thread, guest and pull request watch milestones. */ +export class OrchestrationMilestones extends Context.Service< + OrchestrationMilestones, + { + readonly start: () => Effect.Effect; + readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect; + } +>()("t3/milestones/OrchestrationMilestones") {} + +const make = Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const hub = yield* MilestoneHub.MilestoneHub; + // A record updated again after a restart is not news unless its change is from after it. + const since = yield* DateTime.now; + const isNew = (at: DateTime.Utc | string) => + DateTime.isGreaterThanOrEqualTo(typeof at === "string" ? DateTime.makeUnsafe(at) : at, since); + /** Each thread's waiting guest messages, so a resolution is told once and a closed link is seen. */ + const guestPending = new Map>(); + + const envelope = ( + id: string, + thread: OrchestrationV2AppThread, + occurredAt: DateTime.Utc, + actor: MilestoneActor, + ) => ({ + id: MilestoneId.make(id), + occurredAt: DateTime.formatIso(occurredAt), + projectId: thread.projectId, + threadId: thread.id, + parentThreadId: thread.lineage.parentThreadId, + actor, + isSubagentChild: thread.lineage.relationshipToParent === "subagent", + }); + + const guestMilestones = ( + thread: OrchestrationV2AppThread, + occurredAt: DateTime.Utc, + ): ReadonlyArray => { + const share = thread.guestShare ?? null; + const before = guestPending.get(thread.id) ?? new Map(); + const pending = new Map(); + const out: Array = []; + const resolved = ( + shareId: GuestShareId, + guestMessageId: GuestMessageId, + resolution: "sent" | "dismissed" | "closed", + ) => + out.push({ + ...envelope(`thread.guest_request_resolved:${guestMessageId}`, thread, occurredAt, { + type: "user", + }), + type: "thread.guest_request_resolved", + shareId, + guestMessageId, + resolution, + }); + if (share !== null) { + const guest: MilestoneActor = { + type: "guest", + id: share.id, + ...(share.guestName === null ? {} : { label: share.guestName }), + }; + for (const message of share.messages) { + if (message.status !== "pending") { + if (before.has(message.id)) resolved(share.id, message.id, message.status); + continue; + } + pending.set(message.id, share.id); + if (before.has(message.id) || !isNew(message.submittedAt)) continue; + out.push({ + ...envelope(`thread.guest_request:${message.id}`, thread, occurredAt, guest), + type: "thread.guest_request", + shareId: share.id, + guestMessageId: message.id, + }); + } + } + // Gone from the share without an answer: the link was closed or replaced. + for (const [guestMessageId, shareId] of before) { + if (share?.messages.some((message) => message.id === guestMessageId) !== true) { + resolved(shareId, guestMessageId, "closed"); + } + } + if (pending.size === 0) guestPending.delete(thread.id); + else guestPending.set(thread.id, pending); + return out; + }; + + // Runs for every domain event, token deltas included; most return before reading anything. + const handle: OrchestrationMilestones["Service"]["handle"] = Effect.fnUntraced( + function* (event) { + const out: Array = []; + switch (event.type) { + case "run.updated": { + const run = event.payload; + // A queued run cancelled before it started did no work worth telling of. + if (run.startedAt === null || run.completedAt === null || !isNew(run.completedAt)) return; + if ( + run.status !== "completed" && + run.status !== "failed" && + run.status !== "interrupted" && + run.status !== "cancelled" + ) { + return; + } + const thread = yield* projections.getThread(event.threadId); + out.push({ + ...envelope(`thread.run_settled:${run.id}`, thread, run.completedAt, { + type: "agent", + id: run.providerInstanceId, + }), + type: "thread.run_settled", + runId: run.id, + outcome: run.status, + }); + break; + } + case "runtime-request.updated": { + const request = event.payload; + const kind = inputKind(request.kind); + if (kind === null) return; + if (request.status === "pending") { + if (!isNew(request.createdAt)) return; + const thread = yield* projections.getThread(event.threadId); + out.push({ + ...envelope(`thread.needs_input:${request.id}`, thread, request.createdAt, { + type: "agent", + }), + type: "thread.needs_input", + requestId: request.id, + kind, + }); + } else { + const at = request.resolvedAt ?? event.occurredAt; + if (!isNew(at)) return; + const thread = yield* projections.getThread(event.threadId); + out.push({ + ...envelope(`thread.input_resolved:${request.id}`, thread, at, { + type: request.status === "resolved" ? "user" : "system", + }), + type: "thread.input_resolved", + requestId: request.id, + kind, + resolution: request.status, + }); + } + break; + } + case "thread.guest-share-updated": + out.push(...guestMilestones(event.payload, event.occurredAt)); + break; + case "message.updated": { + const message = event.payload; + const source = message.notification?.source; + if (source?.kind !== "monitor" || source.pullRequest === undefined) return; + if (!isNew(message.createdAt)) return; + const stamps = [source.pullRequest, ...(source.otherPullRequests ?? [])]; + const thread = yield* projections.getThread(event.threadId); + out.push({ + ...envelope(`pr.watch_wake:${message.id}`, thread, message.createdAt, { + type: "system", + label: "pull request watch", + }), + type: "pr.watch_wake", + pullRequests: stamps.map(({ host, repository, number }) => ({ + host, + repository, + number, + })), + outcome: message.notification!.outcome, + summary: message.notification!.summary, + watchEnded: stamps.some((stamp) => stamp.watchEnded === true), + }); + break; + } + default: + return; + } + yield* Effect.forEach(out, hub.publish, { discard: true }); + }, + (effect, event) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logWarning("deriving a milestone failed", { threadId: event.threadId, cause }), + ), + ), + ); + + const start: OrchestrationMilestones["Service"]["start"] = Effect.fn( + "OrchestrationMilestones.start", + )(function* () { + yield* forkParked( + Stream.runForEach(engine.streamDomainEvents, handle).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration milestone stream failed", { cause }), + ), + ), + ); + }); + + return OrchestrationMilestones.of({ start, handle }); +}); + +export const layer = Layer.effect(OrchestrationMilestones, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d06186beb1988..8e0a2ea2f655f 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -9,6 +9,8 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; import * as DelegatedTaskQuestionReactor from "./orchestration-v2/DelegatedTaskQuestionReactor.ts"; +import * as MilestoneHub from "./milestones/MilestoneHub.ts"; +import * as OrchestrationMilestones from "./milestones/OrchestrationMilestones.ts"; // Effect wraps this raw Node HTTP server after its startup and write-error guards attach. // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; @@ -753,12 +755,19 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( yield* service.start(); }), ).pipe(Layer.provide(DelegatedTaskQuestionReactor.layer), Layer.provide(ProjectionStoreV2.layer)), + Layer.effectDiscard( + Effect.gen(function* () { + yield* (yield* OrchestrationMilestones.OrchestrationMilestones).start(); + }), + ).pipe(Layer.provide(OrchestrationMilestones.layer), Layer.provide(ProjectionStoreV2.layer)), ProviderUsageLimitsIngestion.layer, layerProviderInstallationRefresh, ProviderInstallation.layer, ReplayMarkers.layer, Layer.effectDiscard(ProjectSettingsOverrideSweep.sweep), ).pipe( + // One hub, which the feeders above publish to and future consumers read. + Layer.provideMerge(MilestoneHub.layer), Layer.provideMerge(layerOrchestrationApplication), Layer.provideMerge(layerTaskFolders), Layer.provideMerge(RuntimeLayer.layerEventInfrastructure), diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 9c164f91c9962..8bc6b50d24def 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -135,6 +135,14 @@ Any agent that supports remote MCP servers over HTTP with OAuth can connect. Giv it the MCP URL and choose OAuth, and the agent finds the sign-in settings itself. Agents without OAuth support cannot connect. +A bot that supports MCP Events (`io.modelcontextprotocol/events`) can learn +when something happens without reading threads over and over: a turn ended, an +agent waits on a person, a guest asked something, a watched pull request woke +its thread. Each of these is an event type it can poll or stream, narrowed to +projects or threads. The environment keeps its latest 1,000 milestones in +memory, so a bot that was away longer, or reconnects after a restart, is told +some may be missing and should reread the threads it cares about. + ## Scripts on the host On the machine that runs the environment, `t3 thread` uses the same tools diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index e1b3346386ffc..7a159c816ef11 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -67,6 +67,7 @@ export * from "./previewAutomation.ts"; export * from "./previewCapture.ts"; export * from "./usage.ts"; export * from "./scheduledTask.ts"; +export * from "./milestones.ts"; export * from "./worktreeMcp.ts"; export * from "./resourceTelemetry.ts"; export * from "./rpc.ts"; diff --git a/packages/contracts/src/milestones.ts b/packages/contracts/src/milestones.ts new file mode 100644 index 0000000000000..56e259b2b9fab --- /dev/null +++ b/packages/contracts/src/milestones.ts @@ -0,0 +1,120 @@ +import * as Schema from "effect/Schema"; + +import { + GuestMessageId, + GuestShareId, + IsoDateTime, + ProjectId, + RunId, + RuntimeRequestId, + ThreadId, + TrimmedNonEmptyString, +} from "./baseSchemas.ts"; +import { ThreadPullRequestKey } from "./threadPullRequest.ts"; + +/** + * Milestones are the coarse state changes worth telling someone about: a turn ended, an agent + * waits on a person, a guest asked something, a watched pull request woke its thread. + * They are derived from the authoritative stores and kept only in memory, so a consumer that + * needs the full state reads it from those stores. + */ +export const MilestoneId = TrimmedNonEmptyString.pipe(Schema.brand("MilestoneId")); +export type MilestoneId = typeof MilestoneId.Type; + +/** Who caused a milestone, as far as the server knows. */ +export const MilestoneActor = Schema.Struct({ + type: Schema.Literals(["user", "agent", "system", "guest"]), + id: Schema.optional(TrimmedNonEmptyString), + label: Schema.optional(TrimmedNonEmptyString), +}); +export type MilestoneActor = typeof MilestoneActor.Type; + +const MilestoneEnvelope = Schema.Struct({ + /** Stable for one transition, so publishing it twice is one milestone. */ + id: MilestoneId, + occurredAt: IsoDateTime, + projectId: Schema.NullOr(ProjectId), + threadId: Schema.NullOr(ThreadId), + parentThreadId: Schema.NullOr(ThreadId), + actor: MilestoneActor, + /** A subagent's thread. Muted unless asked for. */ + isSubagentChild: Schema.Boolean, +}); + +/** `approval` covers command, file and permission prompts; `user_input` covers questions. */ +export const MilestoneInputKind = Schema.Literals(["user_input", "approval"]); +export type MilestoneInputKind = typeof MilestoneInputKind.Type; + +export const MilestoneEvent = Schema.Union([ + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("thread.run_settled"), + runId: RunId, + outcome: Schema.Literals(["completed", "failed", "interrupted", "cancelled"]), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("thread.needs_input"), + requestId: RuntimeRequestId, + kind: MilestoneInputKind, + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("thread.input_resolved"), + requestId: RuntimeRequestId, + kind: MilestoneInputKind, + resolution: Schema.Literals(["resolved", "expired", "cancelled"]), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("thread.guest_request"), + shareId: GuestShareId, + guestMessageId: GuestMessageId, + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("thread.guest_request_resolved"), + shareId: GuestShareId, + guestMessageId: GuestMessageId, + /** `closed` when the link was closed or replaced with the request still waiting. */ + resolution: Schema.Literals(["sent", "dismissed", "closed"]), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + type: Schema.Literal("pr.watch_wake"), + pullRequests: Schema.Array(ThreadPullRequestKey), + outcome: Schema.Literals(["completed", "failed", "cancelled", "updated", "unknown"]), + summary: Schema.String, + /** The watch ended with this wake, as a merge, a close or a read failure ends it. */ + watchEnded: Schema.Boolean, + }), +]); +export type MilestoneEvent = typeof MilestoneEvent.Type; + +export const MilestoneEventType = Schema.Literals([ + "thread.run_settled", + "thread.needs_input", + "thread.input_resolved", + "thread.guest_request", + "thread.guest_request_resolved", + "pr.watch_wake", +]); +export type MilestoneEventType = typeof MilestoneEventType.Type; + +export const MilestoneFilter = Schema.Struct({ + types: Schema.optional(Schema.Array(MilestoneEventType)), + projectIds: Schema.optional(Schema.Array(ProjectId)), + threadIds: Schema.optional(Schema.Array(ThreadId)), + /** Absent reads as false: subagent threads churn and are rarely news. */ + includeSubagentChildren: Schema.optional(Schema.Boolean), +}); +export type MilestoneFilter = typeof MilestoneFilter.Type; + +/** Whether `event` is one `filter` asks for. Each given list must contain the event's value. */ +export const milestoneMatches = (event: MilestoneEvent, filter: MilestoneFilter = {}): boolean => + (filter.includeSubagentChildren === true || !event.isSubagentChild) && + (filter.types === undefined || filter.types.includes(event.type)) && + (filter.projectIds === undefined || + (event.projectId !== null && filter.projectIds.includes(event.projectId))) && + (filter.threadIds === undefined || + (event.threadId !== null && filter.threadIds.includes(event.threadId))); diff --git a/patches/effect@4.1.5.patch b/patches/effect@4.1.5.patch new file mode 100644 index 0000000000000..6d1bf0a6a9fa8 --- /dev/null +++ b/patches/effect@4.1.5.patch @@ -0,0 +1,2479 @@ +diff --git a/dist/ai/McpSchema.d.ts b/dist/ai/McpSchema.d.ts +index 8f86c27..aed42ae 100644 +--- a/dist/ai/McpSchema.d.ts ++++ b/dist/ai/McpSchema.d.ts +@@ -941,6 +941,52 @@ export declare const HEADER_MISMATCH_ERROR_CODE: -32020; + * @since 4.0.6 + */ + export declare const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE: -32022; ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const NOT_FOUND_ERROR_CODE: -32023; ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const FORBIDDEN_ERROR_CODE: -32024; ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const RESOURCE_EXHAUSTED_ERROR_CODE: -32025; ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const UNSUPPORTED_ERROR_CODE: -32026; ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const CALLBACK_ENDPOINT_ERROR_CODE: -32027; + declare const ParseError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"NotFound">; ++ readonly code: Schema.tag<-32023>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class NotFound extends NotFound_base { ++} ++declare const Forbidden_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Forbidden">; ++ readonly code: Schema.tag<-32024>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Forbidden extends Forbidden_base { ++} ++declare const ResourceExhausted_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"ResourceExhausted">; ++ readonly code: Schema.tag<-32025>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class ResourceExhausted extends ResourceExhausted_base { ++} ++declare const Unsupported_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Unsupported">; ++ readonly code: Schema.tag<-32026>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Unsupported extends Unsupported_base { ++} ++declare const CallbackEndpointError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"CallbackEndpointError">; ++ readonly code: Schema.tag<-32027>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class CallbackEndpointError extends CallbackEndpointError_base { ++} + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1880,6 +2001,66 @@ declare const Skill_base: Schema.Class; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type; ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventDescriptor: Schema.Struct<{ ++ readonly name: Schema.String; ++ readonly description: Schema.decodeTo>, Schema.optionalKey, never, never>; ++ readonly delivery: Schema.$Array>; ++ readonly inputSchema: Schema.$Record; ++ readonly payloadSchema: Schema.$Record; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type; ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventOccurrence: Schema.Struct<{ ++ readonly eventId: Schema.String; ++ readonly name: Schema.String; ++ readonly timestamp: Schema.String; ++ readonly data: Schema.$Record; ++ readonly cursor: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type; + declare const PromptArgument_base: Schema.Opaque Effect.Effect Layer.Layer; ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence
    { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. Webhook delivery is not supported, so ++ * `events/subscribe` answers `Unsupported`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll` and `events/stream`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const registerEvent: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Effect.Effect>; ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const event: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Layer.Layer>; + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/McpServer.js b/dist/ai/McpServer.js +index 4bf6bca..0973460 100644 +--- a/dist/ai/McpServer.js ++++ b/dist/ai/McpServer.js +@@ -413,6 +413,9 @@ const notFound = (method, target) => { + return new McpCore.SkillNotFound({ + uri: target + }); ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target); + } + }; + const isHidden = error => error instanceof Hidden; +@@ -2637,6 +2640,96 @@ export const registerSkill = /*#__PURE__*/Effect.fnUntraced(function* (options) + * @since 4.1.1 + */ + export const skill = options => Layer.effectDiscard(registerSkill(options)); ++// ============================================================================= ++// Events ++// ============================================================================= ++const DEFAULT_NEXT_POLL_MS = 30_000; ++/** ++* Registers an event type under the MCP Events extension (SEP-3415). ++* ++* **Details** ++* ++* The server declares `io.modelcontextprotocol/events` on revision ++* `2026-07-28` once any event type is registered, and answers `events/list`, ++* `events/poll` and `events/stream`. A push stream runs `stream` for its ++* lifetime inside the request's middleware, sends heartbeats carrying the ++* last cursor, and ends when the client goes away. Services read by `poll` ++* and `stream` are request-level, as for tools. ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const registerEvent = Effect.fnUntraced(function* (options) { ++ const { name, poll, stream } = options; ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)); ++ } ++ const registry = yield* McpServer; ++ const { core, globalMiddleware } = internalState.get(registry); ++ const services = yield* Effect.context(); ++ const annotations = options.annotations ?? Context.empty(); ++ const { invoke, visible } = makeInvoke(services, globalMiddleware); ++ const parameters = options.parameters ?? Schema.Struct({}); ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)); ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)); ++ const argumentsOf = (args) => decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))); ++ const encodeEvent = (event) => encodePayload(event.data).pipe(Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), Effect.map((data) => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` }))); ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [...(poll === undefined ? [] : ["poll"]), ...(stream === undefined ? [] : ["push"])], ++ inputSchema: toolJsonSchema(parameters, false), ++ payloadSchema: toolJsonSchema(options.payload, false), ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ poll: poll === undefined ? undefined : (request, invocation) => invoke(Effect.gen(function* () { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }); ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ }; ++ }), invocation, { method: "events/poll", target: name, payload: request }), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => invoke(Effect.scoped(Effect.gen(function* () { ++ const subscription = yield* stream(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }); ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context(); ++ const items = subscription.items.pipe(Stream.mapEffect((item) => item._tag === "Event" ++ ? encodeEvent(item).pipe(Effect.map((event) => ({ ...event, _tag: "Event", cursor: item.cursor })), Effect.catch((error) => Effect.succeed({ _tag: "Error", error }))) ++ : Effect.succeed(item)), Stream.provideContext(context)); ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }); ++ })), invocation, { method: "events/stream", target: name, payload: request }) ++ }); ++}); ++/** ++* Creates a layer that registers an event type under the MCP Events ++* extension (SEP-3415). ++* ++* @see {@link registerEvent} for the Effect-level event registration API ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const event = (options) => Layer.effectDiscard(registerEvent(options)); + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/internal/mcpCore.js b/dist/ai/internal/mcpCore.js +index 4c416a8..50d2d34 100644 +--- a/dist/ai/internal/mcpCore.js ++++ b/dist/ai/internal/mcpCore.js +@@ -75,6 +75,15 @@ export const ClientNotification = /*#__PURE__*/Data.taggedEnum(); + * @internal + */ + export const ServerNotification = /*#__PURE__*/Data.taggedEnum(); ++/** ++ * @internal ++ */ ++export const eventNotFound = name => new McpSchema.NotFound({ ++ message: `Event '${name}' not found`, ++ data: { ++ kind: "event" ++ } ++}); + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a, b) => { + const rootA = a.slice(0, -"/SKILL.md".length); +@@ -90,6 +99,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + const resourceTemplateRegistrations = []; + const promptRegistrations = new Map(); + const skillRegistrations = new Map(); ++ const eventRegistrations = new Map(); + const skillFiles = new Set(); + const completionRegistrations = new Map(); + const filterList = (registrations, invocation) => Effect.map(Effect.filter(Arr.filter(registrations, entry => entry.isVisible(invocation.protocol)), entry => entry.visible === undefined ? Effect.succeed(true) : entry.visible(invocation)), entries => entries.map(entry => entry.descriptor)); +@@ -234,11 +244,22 @@ export const make = /*#__PURE__*/Effect.sync(() => { + return Array.from(children.values()).sort((a, b) => a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0); + }) + }; ++ const events = { ++ register: registration => Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration); ++ }), ++ list: invocation => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => Effect.suspend(() => { ++ const registration = eventRegistrations.get(name); ++ return registration !== undefined && registration.isVisible(invocation.protocol) ? Effect.succeed(registration) : Effect.fail(eventNotFound(name)); ++ }) ++ }; + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })); + return { + tools, +@@ -246,6 +267,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + prompts, + completions, + skills, ++ events, + registrationPresence + }; + }); +diff --git a/dist/ai/internal/mcpEvents.d.ts b/dist/ai/internal/mcpEvents.d.ts +new file mode 100644 +index 0000000..cb0ff5c +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.d.ts +@@ -0,0 +1 @@ ++export {}; +diff --git a/dist/ai/internal/mcpEvents.js b/dist/ai/internal/mcpEvents.js +new file mode 100644 +index 0000000..d875046 +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.js +@@ -0,0 +1,265 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.js"; ++import * as Clock from "../../Clock.js"; ++import * as Duration from "../../Duration.js"; ++import * as Effect from "../../Effect.js"; ++import * as Option from "../../Option.js"; ++import * as Queue from "../../Queue.js"; ++import * as Result from "../../Result.js"; ++import * as Rpc from "../../rpc/Rpc.js"; ++import * as RpcGroup from "../../rpc/RpcGroup.js"; ++import * as Schema from "../../Schema.js"; ++import * as Stream from "../../Stream.js"; ++import * as PublicMcpSchema from "../McpSchema.js"; ++import * as McpProtocol from "./mcpProtocol.js"; ++import * as Stateless from "./mcpSchema/v2026_07_28.js"; ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events"; ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = (extensions, servesEvents) => servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions; ++const methodNotFound = (method) => new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++}); ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core, method) => Effect.flatMap(core.registrationPresence, (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method))); ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value) => new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++}); ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++const optional = Stateless.optional; ++const Cursor = Schema.NullOr(Schema.String); ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest(Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) { ++} ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++}; ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++}), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) { ++} ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make(EventsActiveNotification, EventsEventNotification, EventsHeartbeatNotification, EventsErrorNotification, EventsTerminatedNotification) { ++} ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++const DEFAULT_HEARTBEAT_MS = 30_000; ++const MIN_HEARTBEAT_MS = 1_000; ++const MAX_HEARTBEAT_MS = 300_000; ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16; ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested) => Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)); ++const isJson = Schema.is(Schema.Json); ++/** ++ * @internal ++ */ ++export const wireError = (failure) => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}); ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function* (options) { ++ const { heartbeatMs, name, subscription } = options; ++ let cursor = subscription.cursor; ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0; ++ const send = (tag, payload) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at; ++ })); ++ const active = (truncated) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }); ++ yield* active(subscription.truncated); ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }); ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)); ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result); ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }); ++ } ++ return; ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }); ++ continue; ++ } ++ const item = next.success.value; ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor; ++ const { _meta, _tag, ...occurrence } = item; ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }); ++ break; ++ } ++ case "Position": { ++ cursor = item.cursor; ++ break; ++ } ++ case "Gap": { ++ cursor = item.cursor; ++ yield* active(true); ++ break; ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }); ++ break; ++ } ++ } ++ } ++}, Effect.scoped); +diff --git a/dist/ai/internal/mcpProtocol/v2026_07_28.js b/dist/ai/internal/mcpProtocol/v2026_07_28.js +index af1ceed..467dd8a 100644 +--- a/dist/ai/internal/mcpProtocol/v2026_07_28.js ++++ b/dist/ai/internal/mcpProtocol/v2026_07_28.js +@@ -17,6 +17,7 @@ import * as Schema from "../../../Schema.js"; + import * as Scope from "../../../Scope.js"; + import * as PublicMcpSchema from "../../McpSchema.js"; + import * as McpCore from "../mcpCore.js"; ++import * as McpEvents from "../mcpEvents.js"; + import * as McpProtocol from "../mcpProtocol.js"; + import * as McpSchema from "../mcpSchema/v2026_07_28.js"; + import * as McpSkills from "../mcpSkills.js"; +@@ -242,7 +243,7 @@ const unsupported = operation => new PublicMcpSchema.McpReverseOperationUnsuppor + /** + * @internal + */ +-export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs); ++export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs, McpEvents.StatelessRpcs); + /** + * @internal + */ +@@ -260,6 +261,8 @@ export const makeHandlers = (core, _lifecycle, context) => { + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult); + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult); + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult); ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult); ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult); + const sendNotification = context.sendNotification; + const supportsSubscriptions = sendNotification !== undefined; + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -277,7 +280,7 @@ export const makeHandlers = (core, _lifecycle, context) => { + completions: {}, + logging: {} + }; +- const declared = McpSkills.declareExtension(extensions, presence.skills); ++ const declared = McpEvents.declareExtension(McpSkills.declareExtension(extensions, presence.skills), presence.events); + if (declared !== undefined) capabilities.extensions = declared; + if (presence.tools) capabilities.tools = { + listChanged: supportsSubscriptions +@@ -297,6 +300,20 @@ export const makeHandlers = (core, _lifecycle, context) => { + serverInfo: context.serverInfo + }; + }); ++ const requireEvents = (method) => McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))); ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function* (registration, args) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest); ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers); ++ } ++ }); ++ // Webhook delivery is not implemented, so subscribing refuses every event type. ++ const refuseWebhook = Effect.fnUntraced(function* (method, name) { ++ yield* requireEvents(method); ++ yield* core.events.get(name, yield* getInvocation); ++ return yield* McpEvents.unsupportedDelivery("webhook"); ++ }); + const requireSkills = method => McpSkills.requireSkills(core, method).pipe(Effect.catch(error => failWithHttpStatus(404, error))); + const getInvocation = PublicMcpSchema.McpRequestContext.useSync(McpProtocol.invocationFromRequestContext); + const getInputInvocation = Effect.fnUntraced(function* (request) { +@@ -592,6 +609,77 @@ export const makeHandlers = (core, _lifecycle, context) => { + }, context.serverInfo); + return yield* decodeReadResourceDirectoryResult(result); + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/list"); ++ yield* McpProtocol.rejectCursor(request.cursor); ++ const events = yield* core.events.list(yield* getInvocation); ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push"); ++ return delivery.length === 0 ? [] : [{ ...event, delivery }]; ++ }); ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo); ++ return yield* decodeListEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/poll"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation); ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ })), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo); ++ return yield* decodePollEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function* (request, { client, requestId }) { ++ yield* requireEvents("events/stream"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId }; ++ const send = (tag, payload) => sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }); ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs); ++ yield* Effect.raceFirst(registration.stream({ arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, invocation, (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send })), context.awaitClientEnd ?? Effect.never); ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo); ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }); ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function* (request) { ++ return yield* refuseWebhook("events/subscribe", request.name); ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function* (request) { ++ return yield* refuseWebhook("events/unsubscribe", request.name); ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function* (_request) { + return yield* Effect.void; + }) +@@ -613,10 +701,10 @@ const runtime = { + export const protocol = /*#__PURE__*/McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: /*#__PURE__*/McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/dist/ai/internal/mcpRuntime.js b/dist/ai/internal/mcpRuntime.js +index 88238ff..274e513 100644 +--- a/dist/ai/internal/mcpRuntime.js ++++ b/dist/ai/internal/mcpRuntime.js +@@ -39,6 +39,10 @@ const routingNameKey = method => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name"; + case "resources/read": + return "uri"; +@@ -340,7 +344,8 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && (input.method === "subscriptions/listen" || input.method === "events/stream") + }; + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/src/ai/McpSchema.ts b/src/ai/McpSchema.ts +index ba6c830..1e58fb9 100644 +--- a/src/ai/McpSchema.ts ++++ b/src/ai/McpSchema.ts +@@ -740,6 +740,57 @@ export const HEADER_MISMATCH_ERROR_CODE = -32020 as const + */ + export const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE = -32022 as const + ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const NOT_FOUND_ERROR_CODE = -32023 as const ++ ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const FORBIDDEN_ERROR_CODE = -32024 as const ++ ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const RESOURCE_EXHAUSTED_ERROR_CODE = -32025 as const ++ ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const UNSUPPORTED_ERROR_CODE = -32026 as const ++ ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const CALLBACK_ENDPOINT_ERROR_CODE = -32027 as const ++ + /** + * Represents an MCP/JSON-RPC error for invalid JSON that could not be parsed. + * +@@ -852,6 +903,74 @@ export class InternalError extends Schema.Error("effect/ai/McpSch + static readonly notImplemented = new InternalError({ message: "Not implemented" }) + } + ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class NotFound extends Schema.Error("effect/ai/McpSchema/NotFound")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("NotFound"), ++ code: Schema.tag(NOT_FOUND_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Forbidden extends Schema.Error("effect/ai/McpSchema/Forbidden")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Forbidden"), ++ code: Schema.tag(FORBIDDEN_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class ResourceExhausted extends Schema.Error("effect/ai/McpSchema/ResourceExhausted")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("ResourceExhausted"), ++ code: Schema.tag(RESOURCE_EXHAUSTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Unsupported extends Schema.Error("effect/ai/McpSchema/Unsupported")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Unsupported"), ++ code: Schema.tag(UNSUPPORTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or ++ * could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class CallbackEndpointError ++ extends Schema.Error("effect/ai/McpSchema/CallbackEndpointError")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("CallbackEndpointError"), ++ code: Schema.tag(CALLBACK_ENDPOINT_ERROR_CODE) ++ }) ++{} ++ + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1501,6 +1620,76 @@ export class Skill extends Schema.Class( + _meta: optional(UnknownObject) + }) {} + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * How a client receives an event type's occurrences under the MCP Events ++ * extension (SEP-3415): by `events/poll`, an `events/stream` push stream, or ++ * a webhook registered with `events/subscribe`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDelivery = Schema.Literals(["poll", "push", "webhook"]) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type ++ ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDescriptor = Schema.Struct({ ++ name: Schema.String, ++ description: optional(Schema.String), ++ delivery: Schema.Array(EventDelivery), ++ inputSchema: UnknownObject, ++ payloadSchema: UnknownObject, ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type ++ ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventOccurrence = Schema.Struct({ ++ eventId: Schema.String, ++ name: Schema.String, ++ timestamp: Schema.String, ++ data: UnknownObject, ++ cursor: optional(Schema.NullOr(Schema.String)), ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type ++ + // ============================================================================= + // Prompts + // ============================================================================= +diff --git a/src/ai/McpServer.ts b/src/ai/McpServer.ts +index 4c2e191..3bf4321 100644 +--- a/src/ai/McpServer.ts ++++ b/src/ai/McpServer.ts +@@ -344,6 +344,9 @@ export type MiddlewareMethod = + | "skills/list" + | "skills/get" + | "resources/directory/read" ++ | "events/list" ++ | "events/poll" ++ | "events/stream" + + /** + * Request metadata passed to MCP middleware. +@@ -819,7 +822,14 @@ const internalError = new InternalError({ message: "Internal error" }) + const rejectWith = (error: McpErrorBase) => + Effect.fail(new McpCore.RequestRejected({ code: error.code, message: error.message, data: error.data, error })) + +-type CallMethod = "tools/call" | "resources/read" | "prompts/get" | "completion/complete" | "skills/get" ++type CallMethod = ++ | "tools/call" ++ | "resources/read" ++ | "prompts/get" ++ | "completion/complete" ++ | "skills/get" ++ | "events/poll" ++ | "events/stream" + + type ListMethod = Exclude + +@@ -829,6 +839,8 @@ interface NotFoundErrors { + readonly "prompts/get": McpCore.PromptNotFound + readonly "completion/complete": InvalidParams + readonly "skills/get": McpCore.SkillNotFound ++ readonly "events/poll": McpSchema.NotFound ++ readonly "events/stream": McpSchema.NotFound + } + + const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod] => { +@@ -843,6 +855,9 @@ const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod + return new InvalidParams({ message: "Unknown completion reference or argument" }) + case "skills/get": + return new McpCore.SkillNotFound({ uri: target }) ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target) + } + } + +@@ -4134,6 +4149,276 @@ export const registerSkill: (options: SkillOptions) => Effect.Effect => + Layer.effectDiscard(registerSkill(options)) + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. Webhook delivery is not supported, so ++ * `events/subscribe` answers `Unsupported`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++const DEFAULT_NEXT_POLL_MS = 30_000 ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll` and `events/stream`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const registerEvent: < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions) => Effect.Effect> = ++ Effect.fnUntraced(function*(options: EventOptions, Schema.Codec, any>) { ++ const { name, poll, stream } = options ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)) ++ } ++ const registry = yield* McpServer ++ const { core, globalMiddleware } = internalState.get(registry)! ++ const services = yield* Effect.context() ++ const annotations = options.annotations ?? Context.empty() ++ const { invoke, visible } = makeInvoke(services, globalMiddleware) ++ const parameters = options.parameters ?? Schema.Struct({}) ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)) ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)) ++ const argumentsOf = (args: unknown) => ++ decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))) ++ const encodeEvent = (event: EventOccurrence) => ++ encodePayload(event.data).pipe( ++ Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), ++ Effect.map((data): McpCore.EncodedEvent => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), ++ Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` })) ++ ) ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [...(poll === undefined ? [] : ["poll" as const]), ...(stream === undefined ? [] : ["push" as const])], ++ inputSchema: toolJsonSchema(parameters, false) as Record, ++ payloadSchema: toolJsonSchema(options.payload, false) as Record, ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ poll: poll === undefined ? undefined : (request, invocation) => ++ invoke( ++ Effect.gen(function*() { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }) ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ } ++ }), ++ invocation, ++ { method: "events/poll", target: name, payload: request } ++ ), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => ++ invoke( ++ Effect.scoped(Effect.gen(function*() { ++ const subscription = yield* stream(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }) ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context() ++ const items = subscription.items.pipe( ++ Stream.mapEffect((item): Effect.Effect => ++ item._tag === "Event" ++ ? encodeEvent(item).pipe( ++ Effect.map((event) => ({ ...event, _tag: "Event" as const, cursor: item.cursor })), ++ Effect.catch((error) => Effect.succeed({ _tag: "Error" as const, error })) ++ ) ++ : Effect.succeed(item) ++ ), ++ Stream.provideContext(context) ++ ) ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }) ++ })), ++ invocation, ++ { method: "events/stream", target: name, payload: request } ++ ) ++ }) ++ }) as any ++ ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const event = < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions): Layer.Layer> => ++ Layer.effectDiscard(registerEvent(options)) ++ + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/src/ai/internal/mcpCore.ts b/src/ai/internal/mcpCore.ts +index 643982d..597701f 100644 +--- a/src/ai/internal/mcpCore.ts ++++ b/src/ai/internal/mcpCore.ts +@@ -8,6 +8,7 @@ import * as Data from "../../Data.ts" + import * as Effect from "../../Effect.ts" + import type * as McpProtocol from "../McpProtocol.ts" + import * as McpSchema from "../McpSchema.ts" ++import type * as Stream from "../../Stream.ts" + + /** + * @internal +@@ -330,6 +331,118 @@ export interface SkillRegistration { + readonly directory: (uri: string) => ReadonlyArray | undefined + } + ++/** ++ * A failure an event handler reports to the client as a JSON-RPC error, such ++ * as `McpSchema.Forbidden` or `McpSchema.InvalidParams`. ++ * ++ * @internal ++ */ ++export interface EventFailure { ++ readonly code: number ++ readonly message: string ++ readonly data?: unknown ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollRequest { ++ readonly arguments: Readonly> ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * An occurrence with its payload already encoded for the wire. ++ * ++ * @internal ++ */ ++export interface EncodedEvent { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: Readonly> ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollOutcome { ++ readonly events: ReadonlyArray ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly hasMore: boolean ++ readonly nextPollMs: number ++} ++ ++/** ++ * @internal ++ */ ++export interface EventStreamRequest { ++ readonly arguments: Readonly> ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries after `notifications/events/active`: occurrences, ++ * a position checked without a match (carried by the next heartbeat), a gap ++ * (a fresh `active` with `truncated`), or a recoverable error. ++ * ++ * @internal ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EncodedEvent) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventFailure } ++ ++/** ++ * A push subscription the handler accepted. A failure of `items` ends it with ++ * `notifications/events/terminated`. ++ * ++ * @internal ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly items: Stream.Stream ++} ++ ++/** ++ * @internal ++ */ ++export interface EventRegistration { ++ readonly descriptor: McpSchema.EventDescriptor ++ readonly isVisible: (profile: NegotiatedProtocolProfile) => boolean ++ readonly visible?: Visible | undefined ++ readonly poll?: ++ | (( ++ request: EventPollRequest, ++ invocation: McpInvocation ++ ) => Effect.Effect) ++ | undefined ++ // Runs for the subscription's lifetime: `deliver` takes over once the ++ // handler accepts it, so a failure before that is the request's error. ++ readonly stream?: ++ | (( ++ request: EventStreamRequest, ++ invocation: McpInvocation, ++ deliver: (subscription: EventSubscription) => Effect.Effect ++ ) => Effect.Effect) ++ | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface Events { ++ readonly register: (registration: EventRegistration) => Effect.Effect ++ readonly list: (invocation: McpInvocation) => Effect.Effect, RequestRejected> ++ readonly get: (name: string, invocation: McpInvocation) => Effect.Effect ++} ++ + /** + * @internal + */ +@@ -507,11 +620,13 @@ export interface McpCore { + readonly prompts: Prompts + readonly completions: Completions + readonly skills: Skills ++ readonly events: Events + readonly registrationPresence: Effect.Effect<{ + readonly tools: boolean + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +@@ -523,6 +638,12 @@ export interface McpCore { + */ + export type Visible = (invocation: McpInvocation) => Effect.Effect + ++/** ++ * @internal ++ */ ++export const eventNotFound = (name: string): McpSchema.NotFound => ++ new McpSchema.NotFound({ message: `Event '${name}' not found`, data: { kind: "event" } }) ++ + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a: string, b: string): boolean => { + const rootA = a.slice(0, -"/SKILL.md".length) +@@ -539,6 +660,7 @@ export const make: Effect.Effect = Effect.sync(() => { + const resourceTemplateRegistrations: Array = [] + const promptRegistrations = new Map() + const skillRegistrations = new Map() ++ const eventRegistrations = new Map() + const skillFiles = new Set() + const completionRegistrations = new Map< + string, +@@ -717,12 +839,28 @@ export const make: Effect.Effect = Effect.sync(() => { + }) + } + ++ const events: Events = { ++ register: (registration) => ++ Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration) ++ }), ++ list: (invocation) => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => ++ Effect.suspend(() => { ++ const registration = eventRegistrations.get(name) ++ return registration !== undefined && registration.isVisible(invocation.protocol) ++ ? Effect.succeed(registration) ++ : Effect.fail(eventNotFound(name)) ++ }) ++ } ++ + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })) + +- return { tools, resources, prompts, completions, skills, registrationPresence } ++ return { tools, resources, prompts, completions, skills, events, registrationPresence } + }) +diff --git a/src/ai/internal/mcpEvents.ts b/src/ai/internal/mcpEvents.ts +new file mode 100644 +index 0000000..54b2ca8 +--- /dev/null ++++ b/src/ai/internal/mcpEvents.ts +@@ -0,0 +1,315 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.ts" ++import * as Clock from "../../Clock.ts" ++import * as Duration from "../../Duration.ts" ++import * as Effect from "../../Effect.ts" ++import * as Option from "../../Option.ts" ++import * as Queue from "../../Queue.ts" ++import * as Result from "../../Result.ts" ++import * as Rpc from "../../rpc/Rpc.ts" ++import * as RpcGroup from "../../rpc/RpcGroup.ts" ++import * as Schema from "../../Schema.ts" ++import * as Stream from "../../Stream.ts" ++import * as PublicMcpSchema from "../McpSchema.ts" ++import type * as McpCore from "./mcpCore.ts" ++import * as McpProtocol from "./mcpProtocol.ts" ++import * as Stateless from "./mcpSchema/v2026_07_28.ts" ++ ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events" ++ ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = ( ++ extensions: Readonly> | undefined, ++ servesEvents: boolean ++): Readonly> | undefined => ++ servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions ++ ++const methodNotFound = (method: string) => ++ new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++ }) ++ ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core: McpCore.McpCore, method: string) => ++ Effect.flatMap( ++ core.registrationPresence, ++ (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method)) ++ ) ++ ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value: PublicMcpSchema.EventDelivery) => ++ new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++ }) ++ ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++ ++const optional = Stateless.optional ++const Cursor = Schema.NullOr(Schema.String) ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) ++ ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) {} ++ ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++} ++ ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++ }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), ++ [Stateless.UnknownObject] ++ ), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs ++ extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) ++{} ++ ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make( ++ EventsActiveNotification, ++ EventsEventNotification, ++ EventsHeartbeatNotification, ++ EventsErrorNotification, ++ EventsTerminatedNotification ++) {} ++ ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++ ++const DEFAULT_HEARTBEAT_MS = 30_000 ++const MIN_HEARTBEAT_MS = 1_000 ++const MAX_HEARTBEAT_MS = 300_000 ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16 ++ ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested: number | undefined): number => ++ Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)) ++ ++const isJson = Schema.is(Schema.Json) ++ ++/** ++ * @internal ++ */ ++export const wireError = (failure: McpCore.EventFailure): Stateless.McpError => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}) ++ ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function*(options: { ++ readonly name: string ++ readonly subscription: McpCore.EventSubscription ++ readonly heartbeatMs: number ++ readonly send: (tag: string, payload: Readonly>) => Effect.Effect ++}) { ++ const { heartbeatMs, name, subscription } = options ++ let cursor = subscription.cursor ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0 ++ const send = (tag: string, payload: Readonly>) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at ++ })) ++ const active = (truncated: boolean) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }) ++ yield* active(subscription.truncated) ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }) ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)) ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result) ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }) ++ } ++ return ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }) ++ continue ++ } ++ const item = next.success.value ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor ++ const { _meta, _tag, ...occurrence } = item ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }) ++ break ++ } ++ case "Position": { ++ cursor = item.cursor ++ break ++ } ++ case "Gap": { ++ cursor = item.cursor ++ yield* active(true) ++ break ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }) ++ break ++ } ++ } ++ } ++}, Effect.scoped) +diff --git a/src/ai/internal/mcpProtocol.ts b/src/ai/internal/mcpProtocol.ts +index 5393651..f40915b 100644 +--- a/src/ai/internal/mcpProtocol.ts ++++ b/src/ai/internal/mcpProtocol.ts +@@ -484,6 +484,7 @@ export interface HandlerInstallationContext { + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +diff --git a/src/ai/internal/mcpProtocol/v2026_07_28.ts b/src/ai/internal/mcpProtocol/v2026_07_28.ts +index a701ec8..9b9a6fd 100644 +--- a/src/ai/internal/mcpProtocol/v2026_07_28.ts ++++ b/src/ai/internal/mcpProtocol/v2026_07_28.ts +@@ -22,6 +22,7 @@ import type * as Types from "../../../Types.ts" + import type * as PublicMcpProtocol from "../../McpProtocol.ts" + import * as PublicMcpSchema from "../../McpSchema.ts" + import * as McpCore from "../mcpCore.ts" ++import * as McpEvents from "../mcpEvents.ts" + import * as McpProtocol from "../mcpProtocol.ts" + import * as McpSchema from "../mcpSchema/v2026_07_28.ts" + import * as McpSkills from "../mcpSkills.ts" +@@ -344,7 +345,11 @@ const unsupported = ( + /** + * @internal + */ +-export const handlerRpcs = McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs) ++export const handlerRpcs = McpSchema.ClientRequestRpcs.merge( ++ McpSchema.ClientNotificationRpcs, ++ McpSkills.StatelessRpcs, ++ McpEvents.StatelessRpcs ++) + + /** + * @internal +@@ -370,6 +375,8 @@ export const makeHandlers = ( + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult) + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult) + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult) ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult) ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult) + const sendNotification = context.sendNotification + const supportsSubscriptions = sendNotification !== undefined + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -384,7 +391,10 @@ export const makeHandlers = ( + } + const getDiscovery = Effect.map(context.registrationPresence, (presence) => { + const capabilities: Types.Mutable = { completions: {}, logging: {} } +- const declared = McpSkills.declareExtension(extensions, presence.skills) ++ const declared = McpEvents.declareExtension( ++ McpSkills.declareExtension(extensions, presence.skills), ++ presence.events ++ ) + if (declared !== undefined) capabilities.extensions = declared + if (presence.tools) capabilities.tools = { listChanged: supportsSubscriptions } + if (presence.resources) { +@@ -393,6 +403,24 @@ export const makeHandlers = ( + if (presence.prompts) capabilities.prompts = { listChanged: supportsSubscriptions } + return { supportedVersions: context.supportedVersions, capabilities, serverInfo: context.serverInfo } + }) ++ const requireEvents = (method: string) => ++ McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))) ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function*( ++ registration: McpCore.EventRegistration, ++ args: unknown ++ ) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest) ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers) ++ } ++ }) ++ // Webhook delivery is not implemented, so subscribing refuses every event type. ++ const refuseWebhook = Effect.fnUntraced(function*(method: string, name: string) { ++ yield* requireEvents(method) ++ yield* core.events.get(name, yield* getInvocation) ++ return yield* McpEvents.unsupportedDelivery("webhook") ++ }) + const requireSkills = (method: string) => + McpSkills.requireSkills(core, method).pipe( + Effect.catch((error) => failWithHttpStatus(404, error)) +@@ -728,6 +756,92 @@ export const makeHandlers = ( + const result = yield* projectCompleteResult({ ...cacheHint("skills"), resources }, context.serverInfo) + return yield* decodeReadResourceDirectoryResult(result) + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function*(request: typeof McpEvents.ListEvents.payloadSchema.Type) { ++ yield* requireEvents("events/list") ++ yield* McpProtocol.rejectCursor(request.cursor) ++ const events = yield* core.events.list(yield* getInvocation) ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push") ++ return delivery.length === 0 ? [] : [{ ...event, delivery }] ++ }) ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo) ++ return yield* decodeListEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function*(request: typeof McpEvents.PollEvents.payloadSchema.Type) { ++ yield* requireEvents("events/poll") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation) ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => ++ omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ }) ++ ), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo) ++ return yield* decodePollEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function*( ++ request: typeof McpEvents.StreamEvents.payloadSchema.Type, ++ { client, requestId }: { readonly client: Rpc.ServerClient; readonly requestId: RpcMessage.RequestId } ++ ) { ++ yield* requireEvents("events/stream") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId } ++ const send = (tag: string, payload: Readonly>) => ++ sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }) ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs) ++ yield* Effect.raceFirst( ++ registration.stream( ++ { arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, ++ invocation, ++ (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send }) ++ ), ++ context.awaitClientEnd ?? Effect.never ++ ) ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo) ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }) ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function*(request: typeof McpEvents.SubscribeEvents.payloadSchema.Type) { ++ return yield* refuseWebhook("events/subscribe", request.name) ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function*( ++ request: typeof McpEvents.UnsubscribeEvents.payloadSchema.Type ++ ) { ++ return yield* refuseWebhook("events/unsubscribe", request.name) ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function*( + _request: typeof McpSchema.CancelledNotification.payloadSchema.Type + ) { +@@ -751,10 +865,10 @@ const runtime = { + export const protocol = McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/src/ai/internal/mcpRuntime.ts b/src/ai/internal/mcpRuntime.ts +index 9d4c96e..eb0590c 100644 +--- a/src/ai/internal/mcpRuntime.ts ++++ b/src/ai/internal/mcpRuntime.ts +@@ -53,6 +53,10 @@ const routingNameKey = (method: string): "name" | "uri" | undefined => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name" + case "resources/read": + return "uri" +@@ -479,7 +483,9 @@ export const make = Effect.fnUntraced(function*( + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && ++ (input.method === "subscriptions/listen" || input.method === "events/stream") + } + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 863e897d51b22..471dec4be9987 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -377,6 +377,7 @@ patchedDependencies: alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 + effect@4.1.5: 76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337 electron-updater@6.8.9: 91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155 expo-audio@58.0.11: 92414572bf24ffd0c45de44c45f11f6c48bc0af13b8b9a56f77a67bc0e915c1e expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 @@ -434,7 +435,7 @@ importers: version: 0.15.4 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 @@ -458,7 +459,7 @@ importers: version: 0.10.2(patch_hash=cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) electron: specifier: 44.10.1 version: 44.10.1(supports-color@8.1.1) @@ -489,7 +490,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -550,7 +551,7 @@ importers: version: 0.4.4(patch_hash=7a808b92da8460750b85818552e13be3fb73d111691c7db76965970351e124e4)(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)(supports-color@8.1.1)(typescript@6.0.3) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0) '@expo-google-fonts/dm-sans': specifier: ^0.4.2 version: 0.4.2 @@ -628,7 +629,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) expo: specifier: 58.0.23 version: 58.0.23(d226faf1ca90e630d8c56a2108dee32d) @@ -815,10 +816,10 @@ importers: version: 7.29.7(supports-color@8.1.1) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@pierre/trees': specifier: 1.0.0-beta.6 version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(shiki@4.2.0) @@ -860,10 +861,10 @@ importers: version: 1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/platform-node-shared': specifier: 4.1.5 - version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) + version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) '@ff-labs/fff-node': specifier: 0.11.0 version: 0.11.0(patch_hash=93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252) @@ -944,7 +945,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -984,10 +985,10 @@ importers: devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@handy-computer/models': specifier: 0.2.3 version: 0.2.3 @@ -1092,7 +1093,7 @@ importers: version: 3.2.2(react@19.3.0) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0) '@fontsource-variable/inter': specifier: ^5.3.0 version: 5.3.0 @@ -1197,7 +1198,7 @@ importers: version: 3.4.17 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) entities: specifier: 8.1.0 version: 8.1.0 @@ -1267,10 +1268,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@tailwindcss/vite': specifier: 4.3.3 version: 4.3.3(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)) @@ -1336,7 +1337,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../packages/contracts @@ -1348,11 +1349,11 @@ importers: version: link:../packages/shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1364,28 +1365,28 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) + version: 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) '@alchemy.run/drizzle': specifier: 'catalog:' - version: 2.0.0-beta.85(aaf71186a61e3f73fb98ecfca2947754) + version: 2.0.0-beta.85(9d8ed2cd275ad880a7ad7c23a0ac97be) '@alchemy.run/planetscale': specifier: 'catalog:' - version: 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) + version: 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) '@clerk/backend': specifier: 3.27.0 version: 3.27.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@distilled.cloud/cloudflare': specifier: 'catalog:' - version: 1.0.0-rc.18(effect@4.1.5) + version: 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@effect/sql-pg': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5) + version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@effect/sql-sqlite-do': specifier: 'catalog:' - version: 4.1.5(effect@4.1.5) + version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@noble/curves': specifier: 'catalog:' version: 1.9.1 @@ -1403,26 +1404,26 @@ importers: version: link:../../packages/shared alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) drizzle-orm: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@alchemy.run/test': specifier: 'catalog:' - version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(adf93af6036c4c597e35df2cca6d42d0) + version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(f73ef3f521055a56671f9dfc623ae3a6) '@cloudflare/workers-types': specifier: ^4.20260601.1 version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@electric-sql/pglite': specifier: 0.3.15 version: 0.3.15 @@ -1431,7 +1432,7 @@ importers: version: 24.12.4 drizzle-kit: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)) + version: 1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf) vite: specifier: npm:@voidzero-dev/vite-plus-core@1.4.0 version: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' @@ -1443,16 +1444,16 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) + version: 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) jose: specifier: 'catalog:' version: 6.2.2 @@ -1462,10 +1463,10 @@ importers: version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1480,14 +1481,14 @@ importers: version: 1.89.0 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1544,7 +1545,7 @@ importers: version: link:../source-control-definitions effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) gt-i18n: specifier: 1.0.40 version: 1.0.40 @@ -1560,7 +1561,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/mdast': specifier: ^4.0.4 version: 4.0.4 @@ -1584,11 +1585,11 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1597,17 +1598,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1619,17 +1620,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1647,14 +1648,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1678,14 +1679,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1715,14 +1716,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1746,14 +1747,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1777,7 +1778,7 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) jsonc-parser: specifier: 3.3.1 version: 3.3.1 @@ -1787,10 +1788,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1817,14 +1818,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1854,14 +1855,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1891,14 +1892,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1928,14 +1929,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1953,7 +1954,7 @@ importers: version: 1.15.13 '@opencode/client': specifier: 2.0.28 - version: 2.0.28(effect@4.1.5) + version: 2.0.28(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@opencode/protocol': specifier: 2.0.28 version: 2.0.28 @@ -1971,14 +1972,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2002,14 +2003,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2024,7 +2025,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2036,11 +2037,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2055,14 +2056,14 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2095,14 +2096,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2123,7 +2124,7 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -2184,10 +2185,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/hast': specifier: ^3.0.5 version: 3.0.5 @@ -2223,14 +2224,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2257,14 +2258,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2285,11 +2286,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2301,7 +2302,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2316,11 +2317,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2374,14 +2375,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2408,11 +2409,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2427,7 +2428,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2442,17 +2443,17 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) yaml: specifier: ^2.9.0 version: 2.9.0 devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2476,14 +2477,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2507,11 +2508,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2526,7 +2527,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2538,7 +2539,7 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@types/node': specifier: 24.12.4 @@ -2554,14 +2555,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2579,11 +2580,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2601,7 +2602,7 @@ importers: version: 0.15.5(e2e@0.23.0) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) '@electron/asar': specifier: ^4.3.0 version: 4.3.0 @@ -2625,7 +2626,7 @@ importers: version: 0.23.0 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) playwright-core: specifier: 1.64.1 version: 1.64.1 @@ -2641,7 +2642,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/plist': specifier: 'catalog:' version: 3.0.5 @@ -13167,27 +13168,27 @@ snapshots: dependencies: json-schema: 0.4.0 - '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(rolldown@1.2.13)(typescript@6.0.3)': + '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(rolldown@1.2.13)(typescript@6.0.3)': dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@cloudflare/unenv-preset': 2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261026.1) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@puppeteer/browsers': 3.2.6(yauzl@3.4.0) capnp-es: 0.0.16(typescript@6.0.3) - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) magic-string: 0.30.21 mime: 4.1.1 sharp: 0.35.5(@types/node@24.12.4) @@ -13195,8 +13196,8 @@ snapshots: workerd: 1.20261026.1 yauzl: 3.4.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) rolldown: 1.2.13 vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: @@ -13204,27 +13205,27 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/cloudflare@2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1)': - dependencies: - '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) - '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(rolldown@1.2.13)(typescript@6.0.3) - '@alchemy.run/docker': 2.0.0-beta.85(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5) - '@effect/sql-d1': 4.1.1(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@alchemy.run/cloudflare@2.0.0-beta.85(2402ddc9484fce072797810bc31b583f)': + dependencies: + '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(rolldown@1.2.13)(typescript@6.0.3) + '@alchemy.run/docker': 2.0.0-beta.85(e480f1b1bda9582dded73d242d5d6dc9) + '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) + '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) pathe: 2.0.3 picomatch: 4.0.7 rolldown: 1.2.13 tinyglobby: 0.2.17 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: - '@effect/sql-libsql' @@ -13236,26 +13237,26 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/docker@2.0.0-beta.85(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/docker@2.0.0-beta.85(e480f1b1bda9582dded73d242d5d6dc9)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) rolldown: 1.2.13 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - '@alchemy.run/drizzle@2.0.0-beta.85(aaf71186a61e3f73fb98ecfca2947754)': + '@alchemy.run/drizzle@2.0.0-beta.85(9d8ed2cd275ad880a7ad7c23a0ac97be)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@effect/sql-d1': 4.1.1(effect@4.1.5) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - effect: 4.1.5 + '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) optionalDependencies: - '@alchemy.run/cloudflare': 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) - '@effect/sql-pg': 4.1.5(effect@4.1.5) - drizzle-kit: 1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)) + '@alchemy.run/cloudflare': 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + drizzle-kit: 1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf) transitivePeerDependencies: - mysql2 - pg @@ -13265,13 +13266,13 @@ snapshots: chokidar: 5.0.0 rolldown: 1.2.13 - '@alchemy.run/planetscale@2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0)': + '@alchemy.run/planetscale@2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) optionalDependencies: pg: 8.23.0 transitivePeerDependencies: @@ -13284,21 +13285,21 @@ snapshots: '@types/react': 19.3.0 react-devtools-core: 6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@alchemy.run/sql@2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0)': + '@alchemy.run/sql@2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) optionalDependencies: - '@effect/sql-pg': 4.1.5(effect@4.1.5) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) pg: 8.23.0 - '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(adf93af6036c4c597e35df2cca6d42d0)': + '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(f73ef3f521055a56671f9dfc623ae3a6)': dependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) optionalDependencies: - '@effect/vitest': 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@effect/vitest': 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) vitest: 5.0.5(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/browser-preview@5.0.5)(@vitest/ui@5.0.5)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0) transitivePeerDependencies: - bufferutil @@ -14277,45 +14278,45 @@ snapshots: '@dimforge/rapier3d-compat@0.12.0': {} - '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) '@dnd-kit/accessibility@3.1.1(react@19.3.0)': dependencies: @@ -14361,64 +14362,64 @@ snapshots: e2e: 0.23.0 playwright-core: 1.64.1 - '@effect/atom-react@4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0)': + '@effect/atom-react@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0)': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) react: 19.3.0 scheduler: 0.28.0 - '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)': + '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13)': + '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13)': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) swagger2openapi: 7.0.8(encoding@0.1.13) transitivePeerDependencies: - encoding - '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6)': + '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6)': + '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6)': dependencies: '@types/ws': 8.18.2 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6)': + '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) redis: 6.2.1 undici: 8.12.4 transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/sql-d1@4.1.1(effect@4.1.5)': + '@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: '@cloudflare/workers-types': 5.20261026.1 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@effect/sql-pg@4.1.5(effect@4.1.5)': + '@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) - '@effect/sql-sqlite-do@4.1.5(effect@4.1.5)': + '@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) '@effect/tsgo-darwin-arm64@0.67.1': optional: true @@ -14451,9 +14452,9 @@ snapshots: '@effect/tsgo-win32-arm64': 0.67.1 '@effect/tsgo-win32-x64': 0.67.1 - '@effect/vitest@4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': + '@effect/vitest@4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) vite-plus: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) transitivePeerDependencies: - '@arethetypeswrong/core' @@ -15929,22 +15930,22 @@ snapshots: dependencies: cross-spawn: 7.0.6 - '@opencode/client@2.0.28(effect@4.1.5)': + '@opencode/client@2.0.28(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': dependencies: '@opencode/protocol': 2.0.28 '@opencode/schema': 2.0.28 optionalDependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) '@opencode/protocol@2.0.28': dependencies: '@opencode/schema': 2.0.28 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) '@opencode/schema@2.0.28': dependencies: '@standard-schema/spec': 1.1.0 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) '@oslojs/asn1@1.0.0': dependencies: @@ -18033,12 +18034,12 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 - alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): + alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@alchemy.run/sigil': 0.1.0-alpha.1(@types/react@19.3.0)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6)) capnweb: 0.12.0 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) fflate: 0.8.3 pathe: 2.0.3 picomatch: 4.0.7 @@ -18046,8 +18047,8 @@ snapshots: tinyglobby: 0.2.17 yaml: 2.9.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: @@ -19006,21 +19007,21 @@ snapshots: dotenv@16.6.1: {} - drizzle-kit@1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)): + drizzle-kit@1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf): optionalDependencies: - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): + drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): optionalDependencies: '@cloudflare/workers-types': 4.20260604.1 - '@effect/sql-d1': 4.1.1(effect@4.1.5) - '@effect/sql-pg': 4.1.5(effect@4.1.5) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) '@electric-sql/pglite': 0.3.15 '@libsql/client': 0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@types/sql.js': 1.4.11 bun-types: 1.3.14 - effect: 4.1.5 + effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) expo-sqlite: 58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) pg: 8.23.0 sql.js: 1.15.0 @@ -19059,7 +19060,7 @@ snapshots: ee-first@1.1.1: {} - effect@4.1.5: {} + effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337): {} ejs@3.1.10: dependencies: diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 7e3c147d69351..fdaafa748a67e 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -285,6 +285,8 @@ patchedDependencies: react-native-svg@15.16.1: patches/react-native-svg@15.16.1.patch # Android: double-tap zoom no longer cancels itself, and taps near a link open it. react-native-pdf-jsi@6.1.0: patches/react-native-pdf-jsi@6.1.0.patch + # The MCP Events extension (SEP-3415) on effect/ai, until Effect ships it. + effect@4.1.5: patches/effect@4.1.5.patch # Unmet peers fail resolution, so a pin outside a dependency's peer range is # caught when the lockfile changes instead of scrolling past as a warning. From 9d35540ace7c6b1255a1b29035cab232a79b387e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 15:46:48 -0800 Subject: [PATCH 128/162] fix(mobile): pasted iOS photos keep their encoding and repeats are dropped (#41101) --- .../ios/T3ComposerEditorModule.swift | 1 + .../ios/T3ComposerEditorView.swift | 40 ++++++++++++++++--- .../t3-composer-editor/tests/ios/main.swift | 24 ++++++++++- .../components/ComposerAttachmentStrip.tsx | 21 +++++++++- .../src/features/threads/ThreadComposer.tsx | 12 +++++- apps/mobile/src/i18n/translations/de.json | 1 + apps/mobile/src/i18n/translations/en.json | 1 + apps/mobile/src/i18n/translations/es.json | 1 + apps/mobile/src/i18n/translations/fr.json | 1 + apps/mobile/src/i18n/translations/ja.json | 1 + apps/mobile/src/i18n/translations/ko.json | 1 + apps/mobile/src/i18n/translations/pt-BR.json | 1 + apps/mobile/src/i18n/translations/ru.json | 1 + apps/mobile/src/i18n/translations/sv.json | 1 + apps/mobile/src/i18n/translations/zh.json | 1 + apps/mobile/src/lib/composer-image-schema.ts | 1 + apps/mobile/src/lib/composerImages.test.ts | 6 +++ apps/mobile/src/lib/composerImages.ts | 9 ++++- .../src/native/T3ComposerEditor.ios.tsx | 5 +++ apps/mobile/src/native/T3ComposerEditor.tsx | 1 + .../src/native/T3ComposerEditor.types.ts | 2 + .../src/state/use-composer-drafts.test.ts | 25 +++++++++--- apps/mobile/src/state/use-composer-drafts.ts | 16 ++++---- 23 files changed, 148 insertions(+), 25 deletions(-) diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift index c54a1a84e9644..d07908a4b27fa 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift @@ -117,6 +117,7 @@ public class T3ComposerEditorModule: Module { "onComposerBlur", "onComposerSubmit", "onComposerPasteImages", + "onComposerPasteImagesPending", "onComposerContextPress", "onComposerPasteContext", "onComposerPasteText", diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift index 253376fe5e4d3..2f24b0d98752c 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift @@ -86,6 +86,8 @@ private final class ComposerTextView: UITextView { ]) var onPasteImages: (([String]) -> Void)? + /// Change in how many pasted images are still loading: +n when a paste is accepted, -n once it settles. + var onPasteImagesPending: ((Int) -> Void)? var onPasteContext: (([String: String]) -> Void)? var onPasteText: ((String, NSRange) -> Void)? var clipboardFragment = "" @@ -308,6 +310,8 @@ private final class ComposerTextView: UITextView { } func loadImages(from providers: [NSItemProvider]) { + guard !providers.isEmpty else { return } + onPasteImagesPending?(providers.count) let group = DispatchGroup() let lock = NSLock() var images = [(data: Data, fileExtension: String)?](repeating: nil, count: providers.count) @@ -325,10 +329,11 @@ private final class ComposerTextView: UITextView { store((object as? UIImage)?.pngData().map { ($0, "png") }) } } - // Decoding a GIF to UIImage keeps only its first frame, so pass its bytes through. - if provider.hasItemConformingToTypeIdentifier(UTType.gif.identifier) { - _ = provider.loadDataRepresentation(forTypeIdentifier: UTType.gif.identifier) { data, _ in - if let data { store((data, "gif")) } else { loadPNG() } + // Re-encoding a photo as PNG inflates it several times and keeps only a GIF's first frame, + // so pass the provider's own encoding through when it is one the attachment path reads. + if let original = Self.passthroughImageType(of: provider) { + _ = provider.loadDataRepresentation(forTypeIdentifier: original.type.identifier) { data, _ in + if let data { store((data, original.fileExtension)) } else { loadPNG() } } } else { loadPNG() @@ -336,7 +341,11 @@ private final class ComposerTextView: UITextView { } group.notify(queue: .main) { [weak self] in - guard let self, !self.isReadOnly else { + guard let self else { + return + } + defer { self.onPasteImagesPending?(-providers.count) } + guard !self.isReadOnly else { return } let urls = images.compactMap { $0 }.compactMap { @@ -418,6 +427,23 @@ private final class ComposerTextView: UITextView { return sourceOffset } + private static let passthroughImageTypes: [(type: UTType, fileExtension: String)] = [ + (.gif, "gif"), (.jpeg, "jpg"), (.heic, "heic"), (.png, "png"), (.webP, "webp"), + ] + + /// Providers list representations best first, so the first supported one is the original. + private static func passthroughImageType( + of provider: NSItemProvider + ) -> (type: UTType, fileExtension: String)? { + for identifier in provider.registeredTypeIdentifiers { + guard let registered = UTType(identifier) else { continue } + if let match = passthroughImageTypes.first(where: { registered.conforms(to: $0.type) }) { + return match + } + } + return nil + } + private static func writeTemporaryImage(_ image: UIImage) -> String? { image.pngData().flatMap { writeTemporaryImage($0, fileExtension: "png") } } @@ -507,6 +533,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro let onComposerBlur = EventDispatcher() let onComposerSubmit = EventDispatcher() let onComposerPasteImages = EventDispatcher() + let onComposerPasteImagesPending = EventDispatcher() let onComposerContextPress = EventDispatcher() let onComposerPasteContext = EventDispatcher() let onComposerPasteText = EventDispatcher() @@ -537,6 +564,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro textView.onPasteImages = { [weak self] urls in self?.onComposerPasteImages(["uris": urls]) } + textView.onPasteImagesPending = { [weak self] delta in + self?.onComposerPasteImagesPending(["delta": delta]) + } textView.onPasteContext = { [weak self] context in guard let self else { return } let selection = self.sourceSelection() diff --git a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift index 6b69f29d308d5..83c1920bfd133 100644 --- a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift +++ b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift @@ -271,6 +271,17 @@ gifEditor.onPasteImages = { urls in exit(0) } +// A provider that finishes on a later main-queue turn, like a full-size photo still loading. +private let deferredPNG = image.pngData()! +private let deferredProvider = NSItemProvider() +deferredProvider.registerDataRepresentation(forTypeIdentifier: UTType.png.identifier, visibility: .all) { completion in + DispatchQueue.main.async { completion(deferredPNG, nil) } + return nil +} +private var pendingDeltas: [Int] = [] +private let deferredEditor = ComposerTextView() +deferredEditor.onPasteImagesPending = { pendingDeltas.append($0) } + // Inline provider completion places the attachment callback before this main-queue check. DispatchQueue.main.async { check(pastedImages.count == 1, "An accepted provider-based paste must emit exactly one attachment batch") @@ -287,7 +298,16 @@ DispatchQueue.main.async { "The attachment must contain the pasted image's pixels") check(pasteEditor.text == "Keep this draft", "Image paste must preserve the draft text") print("Composer provider-paste checks passed") - check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path") - gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)]) + deferredEditor.onPasteImages = { urls in + urls.compactMap(URL.init(string:)).forEach { try? FileManager.default.removeItem(at: $0) } + DispatchQueue.main.async { + check(pendingDeltas == [1, -1], "A finished paste must settle its preparation: \(pendingDeltas)") + print("Composer paste-preparation checks passed") + check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path") + gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)]) + } + } + deferredEditor.paste(itemProviders: [deferredProvider]) + check(pendingDeltas == [1], "Preparation must be reported before the provider finishes: \(pendingDeltas)") } dispatchMain() diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index ba7d9790c4120..95a2d928e4c10 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -10,6 +10,7 @@ import { Paths } from "expo-file-system"; import { Image, Pressable, ScrollView, View } from "react-native"; import { AppText as Text } from "./ui/AppText"; +import { AppActivityIndicator } from "./ui/AppActivityIndicator"; import { MaterializedPreviewKey, materializedPreviewAtom } from "../lib/composerImagePreview"; import { PierreEntryIcon } from "./PierreEntryIcon"; import { @@ -44,6 +45,8 @@ export interface ComposerAttachmentStripProps { readonly imageSize?: number; readonly imageBorderRadius?: number; readonly removeButtonPlacement?: "overlay" | "gutter"; + /** Pasted images still being prepared, shown as placeholders after the attachments. */ + readonly pendingImageCount?: number; } type ComposerAttachmentThumbnailProps = { @@ -301,7 +304,8 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) { const removeButtonPlacement = props.removeButtonPlacement ?? "overlay"; const removeButtonGutter = removeButtonPlacement === "gutter" ? 10 : 0; - if (props.attachments.length === 0) { + const pendingImageCount = props.pendingImageCount ?? 0; + if (props.attachments.length === 0 && pendingImageCount === 0) { return null; } @@ -353,6 +357,21 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) { ))} + {Array.from({ length: pendingImageCount }, (_, index) => ( + + + + ))} diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 025b91326762b..b2ebef9a42523 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -270,6 +270,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const [isFocused, setIsFocused] = useState(false); const pendingPastedTextAttachmentCountRef = useRef(0); const pendingNativeImagePasteCountRef = useRef(0); + const [pendingNativeImageCount, setPendingNativeImageCount] = useState(0); const [pendingPastedTextAttachmentCount, setPendingPastedTextAttachmentCount] = useState(0); const settingsRoutePresentedRef = useRef(false); const settingsSheetPresentation = useThreadSettingsSheetPresentation({ @@ -478,7 +479,8 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps const isToolbarVisible = isVoiceInputPresented; const hasEditingAttachments = (queuedEdit !== null && queuedEdit.existingAttachments.length > 0) || - stripAttachments.length > 0; + stripAttachments.length > 0 || + pendingNativeImageCount > 0; const attachmentBlockReason = composerAttachmentUploadBlockReason( { environmentId: props.environmentId, @@ -652,7 +654,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps /> ) : null} - {stripAttachments.length > 0 ? ( + {stripAttachments.length > 0 || pendingNativeImageCount > 0 ? ( undefined : props.onRemoveDraftImage} onPressPreview={isSubmissionLocked ? undefined : onPressPreview} onPressVideo={isSubmissionLocked ? undefined : onPressVideo} @@ -903,10 +906,15 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps onPasteImages={(uris) => { if (isSubmissionLocked) return; pendingNativeImagePasteCountRef.current += 1; + setPendingNativeImageCount((count) => count + uris.length); void nativeImageSubmit.pasteImages(uris).finally(() => { pendingNativeImagePasteCountRef.current -= 1; + setPendingNativeImageCount((count) => count - uris.length); }); }} + onPasteImagesPending={(delta) => + setPendingNativeImageCount((count) => count + delta) + } onPasteText={(paste) => { if (isSubmissionLocked) return; const insertPaste = () => { diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 1fe7fdc60bce9..2073cb88f9e72 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Wiederholen", "b1687c7b2b91e569": "{name} öffnen", "2ffc366d6a7f88db": "{name} entfernen", + "ff43c1538698d479": "Eingefügtes Bild wird vorbereitet", "c04cd8ec791956cb": "Die lokale Datei ist nicht verfügbar. Hänge sie erneut an.", "68883cb3342998e5": "Verbinde dich erneut mit der Umgebung und versuche es noch einmal.", "43f6af4554b019cf": "Anhang konnte nicht geöffnet werden", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 84c6fd8dfd893..9fc46efb5af54 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Retry", "b1687c7b2b91e569": "Open {name}", "2ffc366d6a7f88db": "Remove {name}", + "ff43c1538698d479": "Preparing pasted image", "c04cd8ec791956cb": "The local file is unavailable. Attach it again.", "68883cb3342998e5": "Reconnect to the environment and try again.", "43f6af4554b019cf": "Could not open attachment", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index d3fb1c8188ddb..39ca2122a2fe1 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Reintentar", "b1687c7b2b91e569": "Abrir {name}", "2ffc366d6a7f88db": "Quitar {name}", + "ff43c1538698d479": "Preparando la imagen pegada", "c04cd8ec791956cb": "El archivo local no está disponible. Vuelve a adjuntarlo.", "68883cb3342998e5": "Vuelve a conectarte al entorno e inténtalo de nuevo.", "43f6af4554b019cf": "No se pudo abrir el adjunto", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 2d4f3cb8084fc..f7110d948813a 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Réessayer", "b1687c7b2b91e569": "Ouvrir {name}", "2ffc366d6a7f88db": "Retirer {name}", + "ff43c1538698d479": "Préparation de l’image collée", "c04cd8ec791956cb": "Le fichier local n’est pas disponible. Joignez-le à nouveau.", "68883cb3342998e5": "Reconnectez-vous à l’environnement et réessayez.", "43f6af4554b019cf": "Impossible d’ouvrir la pièce jointe", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 68bcbddda6f02..be00bd9f904d6 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "再試行", "b1687c7b2b91e569": "{name} を開く", "2ffc366d6a7f88db": "{name} を削除", + "ff43c1538698d479": "貼り付けた画像を準備中", "c04cd8ec791956cb": "ローカルファイルを利用できません。もう一度添付してください。", "68883cb3342998e5": "環境に再接続して、もう一度お試しください。", "43f6af4554b019cf": "添付ファイルを開けませんでした", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index ce3e8aba332c7..b991e15bd45a7 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "다시 시도", "b1687c7b2b91e569": "{name} 열기", "2ffc366d6a7f88db": "{name} 제거", + "ff43c1538698d479": "붙여넣은 이미지 준비 중", "c04cd8ec791956cb": "로컬 파일을 사용할 수 없습니다. 다시 첨부하세요.", "68883cb3342998e5": "환경에 다시 연결한 후 다시 시도하세요.", "43f6af4554b019cf": "첨부 파일을 열 수 없습니다", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 8cb5744485eaa..d2ea67494f79f 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Tentar novamente", "b1687c7b2b91e569": "Abrir {name}", "2ffc366d6a7f88db": "Remover {name}", + "ff43c1538698d479": "Preparando a imagem colada", "c04cd8ec791956cb": "O arquivo local não está disponível. Anexe-o novamente.", "68883cb3342998e5": "Reconecte-se ao ambiente e tente novamente.", "43f6af4554b019cf": "Não foi possível abrir o anexo", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 7dcacfc04efc6..f3d6056940a69 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Повторить", "b1687c7b2b91e569": "Открыть {name}", "2ffc366d6a7f88db": "Удалить {name}", + "ff43c1538698d479": "Подготовка вставленного изображения", "c04cd8ec791956cb": "Локальный файл недоступен. Прикрепите его снова.", "68883cb3342998e5": "Переподключитесь к окружению и повторите попытку.", "43f6af4554b019cf": "Не удалось открыть вложение", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 6e18ff09a8318..e6bc78fa18ef7 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "Försök igen", "b1687c7b2b91e569": "Öppna {name}", "2ffc366d6a7f88db": "Ta bort {name}", + "ff43c1538698d479": "Förbereder inklistrad bild", "c04cd8ec791956cb": "Den lokala filen är inte tillgänglig. Bifoga den igen.", "68883cb3342998e5": "Återanslut till miljön och försök igen.", "43f6af4554b019cf": "Kunde inte öppna bilagan", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 1bea8cf8142f2..937acbb510cbe 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -1360,6 +1360,7 @@ "1c79d42e902ff431": "重试", "b1687c7b2b91e569": "打开 {name}", "2ffc366d6a7f88db": "移除 {name}", + "ff43c1538698d479": "正在准备粘贴的图片", "c04cd8ec791956cb": "本地文件不可用。请重新附加。", "68883cb3342998e5": "请重新连接环境后重试。", "43f6af4554b019cf": "无法打开附件", diff --git a/apps/mobile/src/lib/composer-image-schema.ts b/apps/mobile/src/lib/composer-image-schema.ts index b8ccf9b9055c0..b60e38cf143d9 100644 --- a/apps/mobile/src/lib/composer-image-schema.ts +++ b/apps/mobile/src/lib/composer-image-schema.ts @@ -10,6 +10,7 @@ export const DraftComposerImageAttachmentSchema = Schema.Struct({ sizeBytes: Schema.Number, fileUri: Schema.optional(Schema.String.check(Schema.isNonEmpty())), dataUrl: Schema.optional(Schema.String.check(Schema.isNonEmpty())), + contentDigest: Schema.optional(Schema.String), uploadedAttachmentId: Schema.optional(Schema.String), uploadEnvironmentId: Schema.optional(EnvironmentId), }).check( diff --git a/apps/mobile/src/lib/composerImages.test.ts b/apps/mobile/src/lib/composerImages.test.ts index de05411a8f327..669e24aaf7990 100644 --- a/apps/mobile/src/lib/composerImages.test.ts +++ b/apps/mobile/src/lib/composerImages.test.ts @@ -116,6 +116,11 @@ vi.mock("expo-file-system", () => ({ Paths: { document: "file:///documents" }, })); +vi.mock("expo-crypto", () => ({ + CryptoDigestAlgorithm: { SHA256: "SHA-256" }, + digestStringAsync: async (_algorithm: string, data: string) => `sha256:${data}`, +})); + vi.mock("./uuid", () => ({ uuidv4: () => "attachment-id", })); @@ -154,6 +159,7 @@ describe("native pasted image cleanup", () => { mimeType: "image/jpeg", fileUri: `${STORED}-pasted-image.jpeg`, previewUri: `${STORED}-pasted-image.jpeg`, + contentDigest: "sha256:aGVsbG8=", }), ]); expect(attachments[0]).not.toHaveProperty("dataUrl"); diff --git a/apps/mobile/src/lib/composerImages.ts b/apps/mobile/src/lib/composerImages.ts index a719085189128..fe671928ffdf3 100644 --- a/apps/mobile/src/lib/composerImages.ts +++ b/apps/mobile/src/lib/composerImages.ts @@ -34,6 +34,8 @@ export interface DraftComposerImageAttachment extends Omit { try { const { File } = await import("expo-file-system"); @@ -692,12 +695,16 @@ export async function convertPastedImagesToAttachments(input: { continue; } const name = `pasted-image.${mimeType.split("/")[1] ?? "png"}`; + const { CryptoDigestAlgorithm, digestStringAsync } = await import("expo-crypto"); + const contentDigest = await digestStringAsync(CryptoDigestAlgorithm.SHA256, base64); const fileUri = await persistComposerAttachmentFile( sourceUri, name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, ); - attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType })); + attachments.push( + await ownedComposerImageAttachment({ fileUri, name, mimeType, contentDigest }), + ); } catch (cause) { console.warn("Failed to read pasted image", uri, cause); error = m(msg("Could not read a pasted image.")); diff --git a/apps/mobile/src/native/T3ComposerEditor.ios.tsx b/apps/mobile/src/native/T3ComposerEditor.ios.tsx index 7e8eba1d01b28..0602f4cb308a6 100644 --- a/apps/mobile/src/native/T3ComposerEditor.ios.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.ios.tsx @@ -64,6 +64,8 @@ type NativePasteImagesEvent = NativeSyntheticEvent<{ readonly uris: ReadonlyArray; }>; +type NativePasteImagesPendingEvent = NativeSyntheticEvent<{ readonly delta: number }>; + type NativePasteTextEvent = NativeSyntheticEvent<{ readonly value: string; readonly eventCount: number; @@ -107,6 +109,7 @@ interface NativeComposerEditorProps extends ViewProps { readonly onComposerChange: (event: NativeEditorEvent) => void; readonly onComposerSelectionChange?: (event: NativeSelectionEvent) => void; readonly onComposerPasteImages?: (event: NativePasteImagesEvent) => void; + readonly onComposerPasteImagesPending?: (event: NativePasteImagesPendingEvent) => void; readonly onComposerContextPress?: ( event: NativeSyntheticEvent<{ source: string; start: number; end: number }>, ) => void; @@ -148,6 +151,7 @@ export function ComposerEditor({ onChangeText, onSelectionChange, onPasteImages, + onPasteImagesPending, onPasteText, onFocus, onBlur, @@ -394,6 +398,7 @@ export function ComposerEditor({ forceNativeEventRender((sequence) => sequence + 1); }} onComposerPasteImages={(event) => onPasteImages?.(event.nativeEvent.uris)} + onComposerPasteImagesPending={(event) => onPasteImagesPending?.(event.nativeEvent.delta)} onComposerContextPress={(event) => props.onContextPress?.(event.nativeEvent)} onComposerPasteContext={(event) => { const paste = event.nativeEvent; diff --git a/apps/mobile/src/native/T3ComposerEditor.tsx b/apps/mobile/src/native/T3ComposerEditor.tsx index fa29f3248cabe..91f102238d79d 100644 --- a/apps/mobile/src/native/T3ComposerEditor.tsx +++ b/apps/mobile/src/native/T3ComposerEditor.tsx @@ -12,6 +12,7 @@ export function ComposerEditor({ skills: _skills, selection, onPasteImages, + onPasteImagesPending: _onPasteImagesPending, onPasteText: _onPasteText, style, textStyle, diff --git a/apps/mobile/src/native/T3ComposerEditor.types.ts b/apps/mobile/src/native/T3ComposerEditor.types.ts index f2ffa034cdb11..bc7eda7b2984e 100644 --- a/apps/mobile/src/native/T3ComposerEditor.types.ts +++ b/apps/mobile/src/native/T3ComposerEditor.types.ts @@ -69,6 +69,8 @@ export interface ComposerEditorProps { readonly readResetGeneration?: () => number; readonly onSelectionChange?: (selection: ComposerEditorSelection) => void; readonly onPasteImages?: (uris: ReadonlyArray) => void; + /** iOS: change in pasted images still loading natively, +n on paste and -n once they settle. */ + readonly onPasteImagesPending?: (delta: number) => void; readonly onContextPress?: (reference: { readonly source: string; readonly start: number; diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index 8c1870f76836b..a951c13839ee4 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -131,7 +131,7 @@ const composerDraftFileMocks = vi.hoisted(() => { }); const composerAttachmentCleanupMocks = vi.hoisted(() => ({ - remove: vi.fn(async () => undefined), + remove: vi.fn(async (_uri: string) => undefined), releaseUploads: vi.fn(async () => undefined), })); @@ -1222,7 +1222,8 @@ describe("mobile composer drafts", () => { appAtomRegistry.get(composerDraftsAtom)[pasteKey]?.attachments.map(({ id }) => id), ).toEqual(["red", "blue"]); - const makeStoredPaste = (id: string) => ({ + // Each paste is stored under a new file name, so only the content digest catches a repeat. + const makeStoredPaste = (id: string, contentDigest?: string) => ({ id, type: "image" as const, name: "pasted-image.png", @@ -1230,13 +1231,27 @@ describe("mobile composer drafts", () => { sizeBytes: 3, fileUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, previewUri: `file:///documents/t3-composer-attachments/${id}-pasted-image.png`, + ...(contentDigest === undefined ? {} : { contentDigest }), }); const storedKey = "new-task:environment-1:project-stored-pastes"; - appendComposerDraftAttachments(storedKey, [makeStoredPaste("red")]); - appendComposerDraftAttachments(storedKey, [makeStoredPaste("green")]); + appendComposerDraftAttachments(storedKey, [makeStoredPaste("red", "digest-red")]); + const repeatCleanup = Promise.withResolvers(); + onTestFinished(() => { + composerAttachmentCleanupMocks.remove.mockImplementation(async () => undefined); + }); + composerAttachmentCleanupMocks.remove.mockImplementation(async (uri) => { + if (uri === makeStoredPaste("red-2").fileUri) repeatCleanup.resolve(); + return undefined; + }); + appendComposerDraftAttachments(storedKey, [ + makeStoredPaste("green", "digest-green"), + makeStoredPaste("red-2", "digest-red"), + makeStoredPaste("legacy"), + ]); expect( appAtomRegistry.get(composerDraftsAtom)[storedKey]?.attachments.map(({ id }) => id), - ).toEqual(["red", "green"]); + ).toEqual(["red", "green", "legacy"]); + await repeatCleanup.promise; }); it("keeps shared attachment files until every draft releases them", async () => { diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index 10d8fd7a4f271..8bf91eaf923d0 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -1425,16 +1425,14 @@ export function appendComposerDraftText(draftKey: string, value: string): void { }); } -// Pasted images all share one name, so an image's inline bytes decide whether it is a repeat. +// Pasted images all share one name, so an image's bytes decide whether it is a repeat. function isSameAttachment(a: DraftComposerAttachment, b: DraftComposerAttachment): boolean { - return ( - a.mimeType === b.mimeType && - a.sizeBytes === b.sizeBytes && - a.name === b.name && - (a.type !== "image" || - b.type !== "image" || - (a.dataUrl === b.dataUrl && a.fileUri === b.fileUri)) - ); + if (a.mimeType !== b.mimeType || a.sizeBytes !== b.sizeBytes || a.name !== b.name) return false; + if (a.type !== "image" || b.type !== "image") return true; + if (a.contentDigest !== undefined && b.contentDigest !== undefined) { + return a.contentDigest === b.contentDigest; + } + return a.dataUrl === b.dataUrl && a.fileUri === b.fileUri; } /** From 7b47a2173d9fc18a5ccf89be8bde3e3cd96bf9b2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 16:06:44 -0800 Subject: [PATCH 129/162] fix(server): a Claude resume runs one turn, not a phantom wake after it (#41120) --- .../Adapters/ClaudeAdapterV2.test.ts | 21 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 21 ++++++++++++++++--- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index a4aea2ff1ffa9..3d017de3925fa 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -346,6 +346,27 @@ describe("ClaudeAdapterV2 native resume history", () => { ])("selects the native history head for $name", ({ messages, head }) => { assert.equal(ClaudeAdapterV2.claudeResumeSessionAt(messages), head); }); + + it("recognizes history that ends on a failed request", () => { + const failed = { + uuid: "failed", + type: "assistant", + message: { content: "API Error: Request rejected (429)", model: "" }, + }; + assert.isTrue(ClaudeAdapterV2.claudeHistoryEndsOnFailedRequest([prompt, failed])); + assert.isFalse( + ClaudeAdapterV2.claudeHistoryEndsOnFailedRequest([ + prompt, + entry("stop", "user", "[Request interrupted by user]"), + ]), + ); + assert.isFalse( + ClaudeAdapterV2.claudeHistoryEndsOnFailedRequest([ + prompt, + entry("reply", "assistant", "Done"), + ]), + ); + }); }); describe("ClaudeAdapterV2 runtime query policy", () => { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index a4dc7c5006a8d..370b6b6c4c3f6 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1369,12 +1369,23 @@ const decodeClaudeHistoryMessages = Schema.decodeUnknownEffect( Schema.Struct({ type: Schema.String, uuid: Schema.String, - message: Schema.Struct({ content: Schema.Unknown }), + message: Schema.Struct({ content: Schema.Unknown, model: Schema.optional(Schema.Unknown) }), }), ), ), ); +// The placeholder reply the CLI records for a failed request. +export function claudeHistoryEndsOnFailedRequest( + messages: ReadonlyArray<{ + readonly type: string; + readonly message: { readonly content: unknown; readonly model?: unknown }; + }>, +): boolean { + const last = messages.at(-1); + return last?.type === "assistant" && last.message.model === ""; +} + // Claude's interactive reply-on-resume removes native abort rows before querying the saved history. export function claudeResumeSessionAt( messages: ReadonlyArray<{ @@ -1569,6 +1580,7 @@ export const layerQueryRunner: Layer.Layer< const { mcpServers, ...sdkOptions } = input.options; // Jobs the agent starts inherit the thread, so port discovery can attribute their servers. let resumeSessionAt = sdkOptions.resumeSessionAt; + let endsOnFailedRequest = false; if (input.resume && sdkOptions.resume !== undefined) { const messages = yield* runClaudeWorker({ method: "getSessionMessages", @@ -1585,14 +1597,17 @@ export const layerQueryRunner: Layer.Layer< resumeSessionAt === undefined ? messages.length : messages.findIndex((message) => message.uuid === resumeSessionAt) + 1; - resumeSessionAt = claudeResumeSessionAt(messages.slice(0, boundary)) ?? resumeSessionAt; + const history = messages.slice(0, boundary); + endsOnFailedRequest = claudeHistoryEndsOnFailedRequest(history); + resumeSessionAt = claudeResumeSessionAt(history) ?? resumeSessionAt; } const queryOptions = { ...sdkOptions, ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }), env: { ...(sdkOptions.env ?? hostEnvironment), - ...(input.resume + // The CLI would re-run a failed request by itself, then run the resume prompt as a second turn. + ...(input.resume && !endsOnFailedRequest ? { CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1", CLAUDE_CODE_RESUME_REASON: "user_resume", From 0591d32888dbd2f2f25915c245e6f1fe93dc4755 Mon Sep 17 00:00:00 2001 From: Bilal Bakr <62337003+Bil0000@users.noreply.github.com> Date: Mon, 23 Nov 2026 03:17:48 +0300 Subject: [PATCH 130/162] feat(issues): connect more than one Linear account (#39179) Co-authored-by: Julius Marminge --- ...ettingsSourceControlDetailRouteScreens.tsx | 33 ++- .../components/IssueTrackerSection.tsx | 50 +++-- apps/mobile/src/i18n/translations/de.json | 4 +- apps/mobile/src/i18n/translations/en.json | 4 +- apps/mobile/src/i18n/translations/es.json | 4 +- apps/mobile/src/i18n/translations/fr.json | 4 +- apps/mobile/src/i18n/translations/ja.json | 4 +- apps/mobile/src/i18n/translations/ko.json | 4 +- apps/mobile/src/i18n/translations/pt-BR.json | 4 +- apps/mobile/src/i18n/translations/ru.json | 4 +- apps/mobile/src/i18n/translations/sv.json | 4 +- apps/mobile/src/i18n/translations/zh.json | 4 +- .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/issue/IssueService.test.ts | 121 ++++++++++ apps/server/src/issue/IssueService.ts | 182 ++++++++++----- .../src/issue/IssueTrackerConnections.test.ts | 144 ++++++++++++ .../src/issue/IssueTrackerConnections.ts | 208 +++++++++++++++--- apps/server/src/issue/IssueTrackerHostLive.ts | 19 +- .../src/persistence/IssueTrackerBindings.ts | 102 +++++++-- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/109_IssueTrackerAccounts.ts | 18 ++ .../reconcileV2PreviewMigration.test.ts | 2 + .../settings/IssueTrackerSettings.tsx | 117 ++++++++-- apps/web/src/i18n/translations/de.json | 6 +- apps/web/src/i18n/translations/en.json | 6 +- apps/web/src/i18n/translations/es.json | 6 +- apps/web/src/i18n/translations/fr.json | 6 +- apps/web/src/i18n/translations/ja.json | 6 +- apps/web/src/i18n/translations/ko.json | 6 +- apps/web/src/i18n/translations/pt-BR.json | 6 +- apps/web/src/i18n/translations/ru.json | 6 +- apps/web/src/i18n/translations/sv.json | 6 +- apps/web/src/i18n/translations/zh.json | 6 +- docs/user/source-control.md | 4 +- .../client-runtime/src/issueLinks.test.ts | 20 ++ packages/client-runtime/src/issueLinks.ts | 25 ++- packages/client-runtime/src/issueList.test.ts | 29 +++ packages/client-runtime/src/issueList.ts | 13 +- .../src/state/issueTrackers.test.ts | 23 +- .../client-runtime/src/state/issueTrackers.ts | 52 ++++- packages/contracts/src/environment.ts | 2 + packages/contracts/src/issue.ts | 34 ++- .../src/server/IssueTrackerHost.ts | 56 ++++- 43 files changed, 1155 insertions(+), 202 deletions(-) create mode 100644 apps/server/src/issue/IssueTrackerConnections.test.ts create mode 100644 apps/server/src/persistence/Migrations/109_IssueTrackerAccounts.ts diff --git a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx index 957cf17a26178..94c5a682f537f 100644 --- a/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx +++ b/apps/mobile/src/features/settings/SettingsSourceControlDetailRouteScreens.tsx @@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react"; import type { StaticScreenProps } from "@react-navigation/native"; import { hasIssueTrackerTeams, + issueTrackerBindings, issueTrackerSummary, } from "@t3tools/client-runtime/state/issue-trackers"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; @@ -167,6 +168,7 @@ export function SettingsIssueTrackerRouteScreen({ }: StaticScreenProps<{ readonly environmentId: EnvironmentId; readonly tracker: string; + readonly accountId?: string; }>) { const gt = useGT(); const messages = useMessages(); @@ -176,9 +178,17 @@ export function SettingsIssueTrackerRouteScreen({ issueTrackerEnvironment.connections({ environmentId, input: {} }), ); const canEdit = useAtomValue(issueTrackerEnvironment.connect.permissionAtom(environmentId)); - const tracker = query.data?.trackers.find((entry) => entry.tracker === route.params.tracker); + const tracker = [...(query.data?.trackers ?? []), ...(query.data?.accounts ?? [])].find( + (entry) => entry.tracker === route.params.tracker && entry.accountId === route.params.accountId, + ); const disabled = !canWrite || !canEdit; const usable = tracker?.connected === true && tracker.account !== null; + const canAddAccount = + tracker !== undefined && + route.params.accountId === undefined && + (tracker.connected || + (query.data?.accounts ?? []).some((account) => account.tracker === tracker.tracker)) && + environment?.serverConfig.environment.capabilities.issueTrackerAccounts === true; return ( {!environment || !tracker ? ( @@ -186,7 +196,7 @@ export function SettingsIssueTrackerRouteScreen({ ) : ( <> - {issueTrackerSummary(tracker, query.data?.bindings ?? {}, messages)} + {issueTrackerSummary(tracker, issueTrackerBindings(query.data), messages)} - {usable && hasIssueTrackerTeams(tracker, query.data?.bindings ?? {}) ? ( + {usable && hasIssueTrackerTeams(tracker, issueTrackerBindings(query.data)) ? ( ) : null} + {canAddAccount ? ( + + + + ) : null} )} diff --git a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx index 285a9e801ab65..4428096bc7530 100644 --- a/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx +++ b/apps/mobile/src/features/settings/components/IssueTrackerSection.tsx @@ -1,6 +1,8 @@ import { boundIssueTrackerScopes, + issueTrackerBindInput, issueTrackerBindingFor, + issueTrackerBindings, issueTrackerScopeOptions, issueTrackerSummary, } from "@t3tools/client-runtime/state/issue-trackers"; @@ -80,7 +82,11 @@ function EnvironmentTrackers(props: { const query = useEnvironmentQuery( issueTrackerEnvironment.connections({ environmentId, input: {} }), ); - const trackers = query.data?.trackers ?? []; + const firstAccounts = query.data?.trackers ?? []; + const trackers = firstAccounts.flatMap((tracker) => [ + tracker, + ...(query.data?.accounts ?? []).filter((account) => account.tracker === tracker.tracker), + ]); if (trackers.length === 0) { return query.error ? ( @@ -94,16 +100,21 @@ function EnvironmentTrackers(props: { {trackers.map((tracker, index) => ( } - label={tracker.displayName} - description={issueTrackerSummary(tracker, query.data?.bindings ?? {}, messages)} + label={ + tracker.workspace + ? `${tracker.displayName} · ${tracker.workspace}` + : tracker.displayName + } + description={issueTrackerSummary(tracker, issueTrackerBindings(query.data), messages)} ready={tracker.connected && tracker.account !== null} separated={index > 0} onPress={() => navigation.navigate("SettingsIssueTracker", { environmentId, tracker: tracker.tracker, + ...(tracker.accountId === undefined ? {} : { accountId: tracker.accountId }), }) } /> @@ -133,6 +144,8 @@ export function IssueTrackerCredentialForm(props: { readonly environmentId: EnvironmentId; readonly tracker: IssueTrackerConnection; readonly disabled: boolean; + /** Saves the credential as a new account instead of replacing this one's. */ + readonly addAccount?: boolean; }) { const gt = useGT(); const { environmentId, tracker } = props; @@ -143,7 +156,12 @@ export function IssueTrackerCredentialForm(props: { const submit = async (token: string | null) => { setBusy(true); setFailure(null); - const result = await connect({ environmentId, input: { tracker: tracker.tracker, token } }); + const result = await connect({ + environmentId, + input: props.addAccount + ? { tracker: tracker.tracker, token, addAccount: true } + : { tracker: tracker.tracker, accountId: tracker.accountId, token }, + }); setBusy(false); if (!AsyncResult.isFailure(result)) { setDraft(""); @@ -154,14 +172,13 @@ export function IssueTrackerCredentialForm(props: { }; const helpUrl = tracker.credential.helpUrl; const locked = props.disabled || busy; + const replacing = tracker.connected && !props.addAccount; return ( void tryOpenExternalUrl(helpUrl)} /> ) : null} - {tracker.connected ? ( + {replacing ? (
    @@ -275,19 +297,22 @@ function ProjectBindings({ if (held && !saving && !refreshing && !refreshFailed) setPicks({}); const busy = saving || (held && refreshing); const bound = (projectId: ProjectId) => - picks[projectId] ?? boundIssueTrackerScopes(tracker.tracker, bindings[projectId]); + picks[projectId] ?? boundIssueTrackerScopes(tracker, bindings[projectId]); if (projects.length === 0 || !hasIssueTrackerTeams(tracker, bindings)) return null; const change = async (projectId: ProjectId, scopes: ReadonlyArray) => { if (busy) return; - const binding = issueTrackerBindingFor(tracker.tracker, bound(projectId), scopes); + const binding = issueTrackerBindingFor(tracker, bound(projectId), scopes); const before = picks[projectId]; setSaving(true); setPicks((current) => ({ ...current, - [projectId]: boundIssueTrackerScopes(tracker.tracker, binding ?? undefined), + [projectId]: boundIssueTrackerScopes(tracker, binding ?? undefined), })); - const result = await bind({ environmentId, input: { projectId, binding } }); + const result = await bind({ + environmentId, + input: issueTrackerBindInput(projectId, tracker, binding), + }); if (result._tag !== "Success") setPicks((current) => ({ ...current, [projectId]: before })); setSaving(false); }; @@ -302,7 +327,7 @@ function ProjectBindings({ )} /> {projects.map((project) => { - // A project bound to another tracker keeps that binding; this picker shows it unbound. + // A project bound to another tracker or account keeps that binding; this picker shows it unbound. const value = bound(project.id); const options = issueTrackerScopeOptions(tracker, value); return ( @@ -359,3 +384,49 @@ function ProjectBindings({ ); } + +/** A credential for another account of the tracker, kept beside this one. */ +function AddAccountRow({ + tracker, + onAdd, +}: { + readonly tracker: IssueTrackerConnection; + readonly onAdd: (token: string) => Promise; +}) { + const gt = useGT(); + const [adding, setAdding] = useState(false); + const inputId = `issue-tracker-${tracker.tracker}-add-account`; + if (!adding) { + return ( + setAdding(true)}> + + Add account + + } + /> + ); + } + return ( + {tracker.credential.label}} + description={gt("For the new {tracker} account.", { tracker: tracker.displayName })} + control={ + { + if (next.trim()) void onAdd(next.trim()).then((added) => added && setAdding(false)); + }} + /> + } + /> + ); +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 8d5cb7d817bb1..ecdb3d4220e67 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12490,5 +12490,9 @@ "27d76249d09eb69f": "Review-Leitfaden bereit", "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", - "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden" + "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", + "99d51127f573296b": "Weiteres Konto", + "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", + "99963c0142e17f00": "Für das neue {tracker}-Konto.", + "6d8e4ebc889bace9": "Konto hinzufügen" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 6c5ef49b77f43..0cc2d503fd620 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12499,5 +12499,9 @@ "27d76249d09eb69f": "Review guide ready", "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", - "9e91e9a77b664e4e": "Could not start a review guide" + "9e91e9a77b664e4e": "Could not start a review guide", + "99d51127f573296b": "Another account", + "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", + "99963c0142e17f00": "For the new {tracker} account.", + "6d8e4ebc889bace9": "Add account" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 1f4ed2cf548ee..daf936020ff3a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12485,5 +12485,9 @@ "27d76249d09eb69f": "Guía de revisión lista", "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", - "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión" + "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", + "99d51127f573296b": "Otra cuenta", + "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}.", + "99963c0142e17f00": "Para la nueva cuenta de {tracker}.", + "6d8e4ebc889bace9": "Añadir cuenta" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 72da8bf8e23b2..713eca77f3127 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12490,5 +12490,9 @@ "27d76249d09eb69f": "Guide de revue prêt", "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", - "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue" + "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", + "99d51127f573296b": "Autre compte", + "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", + "99963c0142e17f00": "Pour le nouveau compte {tracker}.", + "6d8e4ebc889bace9": "Ajouter un compte" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 28945ae29dca3..2b44f05d584e1 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12439,5 +12439,9 @@ "27d76249d09eb69f": "レビューガイドの準備ができました", "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", - "9e91e9a77b664e4e": "レビューガイドを開始できませんでした" + "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", + "99d51127f573296b": "別のアカウント", + "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", + "99963c0142e17f00": "新しい {tracker} アカウント用です。", + "6d8e4ebc889bace9": "アカウントを追加" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 35f6cc3549436..48dc094c371ad 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12434,5 +12434,9 @@ "27d76249d09eb69f": "검토 가이드 준비됨", "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", - "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다" + "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", + "99d51127f573296b": "다른 계정", + "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", + "99963c0142e17f00": "새 {tracker} 계정용입니다.", + "6d8e4ebc889bace9": "계정 추가" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 85fefb672d30c..9cc052192b4eb 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12490,5 +12490,9 @@ "27d76249d09eb69f": "Guia de revisão pronto", "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", - "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão" + "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", + "99d51127f573296b": "Outra conta", + "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}.", + "99963c0142e17f00": "Para a nova conta do {tracker}.", + "6d8e4ebc889bace9": "Adicionar conta" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index f4d45a79d0b52..1d8bc14fde51f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12490,5 +12490,9 @@ "27d76249d09eb69f": "Гид по ревью готов", "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", - "9e91e9a77b664e4e": "Не удалось запустить гид по ревью" + "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", + "99d51127f573296b": "Другой аккаунт", + "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", + "99963c0142e17f00": "Для нового аккаунта {tracker}.", + "6d8e4ebc889bace9": "Добавить аккаунт" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 99818c1f2ed37..234479a1b2558 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12497,5 +12497,9 @@ "27d76249d09eb69f": "Granskningsguiden är klar", "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", - "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide" + "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", + "99d51127f573296b": "Ett konto till", + "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare.", + "99963c0142e17f00": "För det nya {tracker}-kontot.", + "6d8e4ebc889bace9": "Lägg till konto" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 09d04201cd2f8..19eff455a318c 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12516,5 +12516,9 @@ "27d76249d09eb69f": "审查导览已就绪", "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", - "9e91e9a77b664e4e": "无法开始生成审查导览" + "9e91e9a77b664e4e": "无法开始生成审查导览", + "99d51127f573296b": "其他账号", + "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", + "99963c0142e17f00": "用于新的 {tracker} 账号。", + "6d8e4ebc889bace9": "添加账号" } diff --git a/docs/user/source-control.md b/docs/user/source-control.md index b6702c13de5d9..ba951c3fe9bda 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -416,7 +416,9 @@ To list Linear issues beside a project's, connect Linear with an API key under Settings → Source control & issues, then pick one or more teams for that project there. Pick another team at any time to add it; uncheck every team to unbind the project. Each team's issues appear in the Linear group of the issue list, sorted with the rest by last update, and -each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. +each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. To +connect another Linear workspace or user, add another account in the same place; each project +reads its teams through the account you picked them under. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 661dfe1a94cae..1f2683f92cd59 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + IssueTrackerAccountId, IssueTrackerKind, ProjectId, SourceControlProviderKind, @@ -138,6 +139,25 @@ describe("resolveIssueLinkTarget", () => { expect( resolveIssueLinkTarget({ url: "https://linear.app/acme/issue/WEB-17", projects }), ).toBeNull(); + + // A second account reaches its own workspace, through only the projects bound with it. + const accountId = IssueTrackerAccountId.make("second"); + const [p1, p2] = [ProjectId.make("p1"), ProjectId.make("p2")]; + const both = (url: string) => + resolveIssueLinkTarget({ + url, + projects, + trackers: { + ...trackers, + accounts: [{ ...trackers.trackers[0]!, accountId, workspace: "othercorp" }], + bindings: { [p1]: trackers.bindings[p1]! }, + accountBindings: { [p2]: { ...trackers.bindings[p2]!, accountId } }, + }, + })?.ref.projectId; + expect([ + both("https://linear.app/othercorp/issue/WEB-17"), + both("https://linear.app/acme/issue/WEB-17"), + ]).toEqual(["p2", "p1"]); }); it.each([ diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index db06b1b0a218f..a81ac7831396d 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -82,8 +82,8 @@ export function mayContainStandaloneIssueLink(text: string): boolean { /** * A standalone tracker link resolves through the project bound to its scope, else any bound to - * the tracker, and only when it names the workspace the credential reaches: team keys repeat - * across workspaces, so a link elsewhere stays an ordinary link. + * the tracker, and only through an account whose credential reaches the workspace it names: team + * keys repeat across workspaces, so a link elsewhere stays an ordinary link. */ function resolveStandaloneIssueLink( url: string, @@ -94,14 +94,23 @@ function resolveStandaloneIssueLink( const parsed = trackers === undefined ? null : parseStandaloneIssueLink(url); if (parsed === null || trackers === undefined) return null; const { tracker, link } = parsed; - const workspace = trackers.trackers.find( - (connection) => connection.tracker === tracker && connection.account !== null, - )?.workspace; - if (workspace?.toLowerCase() !== link.workspace.toLowerCase()) return null; - const { bindings } = trackers; + const accounts = new Set( + [...trackers.trackers, ...(trackers.accounts ?? [])] + .filter( + (connection) => + connection.tracker === tracker && + connection.account !== null && + connection.workspace?.toLowerCase() === link.workspace.toLowerCase(), + ) + .map((connection) => connection.accountId ?? null), + ); + if (accounts.size === 0) return null; + const bindings = { ...trackers.bindings, ...trackers.accountBindings }; const onTracker = projects.flatMap((project) => { const binding = bindings[project.id]; - return binding?.tracker === tracker ? [{ project, binding }] : []; + return binding?.tracker === tracker && accounts.has(binding.accountId ?? null) + ? [{ project, binding }] + : []; }); const preferFirst = (candidates: typeof onTracker) => candidates.find((candidate) => candidate.project.id === preferredProjectId) ?? candidates[0]; diff --git a/packages/client-runtime/src/issueList.test.ts b/packages/client-runtime/src/issueList.test.ts index 5085c10e51887..49bab599b4f51 100644 --- a/packages/client-runtime/src/issueList.test.ts +++ b/packages/client-runtime/src/issueList.test.ts @@ -144,6 +144,35 @@ describe("issueFilterScopes", () => { expect(issueFilterScopes(held, [])).toEqual([{ environmentId, input: scope }]); }); + it("offers the same team key of two Linear accounts as two scopes", () => { + const first = { + projectId: api, + tracker: "linear" as IssueTrackerKind, + host: "linear.app", + scope: "ENG", + }; + const second = hold( + answer({ + trackers: [tracker({})], + scopes: [first, { ...first, projectId: "home" as ProjectId }], + }), + ); + const other = hold( + answer({ trackers: [tracker({})], scopes: [{ ...first, projectId: "o" as ProjectId }] }), + ); + // Older servers name no scopes; their rows stand in, once per team on that server. + const older = hold( + answer({ trackers: [tracker({})], entries: [linearRow, { ...linearRow, key: "ENG-2" }] }), + ); + const count = (...pages: ReadonlyArray>) => + issueFilterScopes( + new Map(pages.map((page, index) => [`env-${index}` as EnvironmentId, page])), + [], + ).length; + expect([count(second), count(second, other), count(other, second)]).toEqual([2, 3, 3]); + expect([count(older), count(older, second), count(second, older)]).toEqual([1, 3, 3]); + }); + it("skips a tracker that cannot be read", () => { const held = new Map([ [ diff --git a/packages/client-runtime/src/issueList.ts b/packages/client-runtime/src/issueList.ts index 5e01c4683830d..1a99f54e0f580 100644 --- a/packages/client-runtime/src/issueList.ts +++ b/packages/client-runtime/src/issueList.ts @@ -170,6 +170,9 @@ export function issueFilterScopes( ) { const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> = []; + // A repository's scope is the same scope on every server. A bound tracker's scope is not: two + // accounts, or two servers, may both have an ENG team, so those are deduplicated per server only. + const fromRepository = new Set(); for (const [environmentId, page] of held) { for (const project of projects) { if (project.environmentId !== environmentId) continue; @@ -186,10 +189,9 @@ export function issueFilterScopes( ) ) continue; - scopes.push({ - environmentId, - input: { projectId: project.id, tracker: tracker.tracker, host, scope }, - }); + const input = { projectId: project.id, tracker: tracker.tracker, host, scope }; + fromRepository.add(input); + scopes.push({ environmentId, input }); } } // A tracker bound in settings (a Linear team) is no repository's; the answer names its scope, @@ -209,9 +211,12 @@ export function issueFilterScopes( ); if (!tracker?.configured) continue; if (!tracker.capabilities?.labels && !tracker.capabilities?.assignees) continue; + // An answer names each scope once per account; rows standing in for one repeat. if ( scopes.some( (s) => + (fromRepository.has(s.input) || + (page.answer.scopes === undefined && s.environmentId === environmentId)) && s.input.scope.toLowerCase() === input.scope.toLowerCase() && s.input.host?.toLowerCase() === host, ) diff --git a/packages/client-runtime/src/state/issueTrackers.test.ts b/packages/client-runtime/src/state/issueTrackers.test.ts index 32d459bf79ed8..ba2fba0ad1da4 100644 --- a/packages/client-runtime/src/state/issueTrackers.test.ts +++ b/packages/client-runtime/src/state/issueTrackers.test.ts @@ -1,7 +1,15 @@ -import { IssueTrackerKind, MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES } from "@t3tools/contracts"; +import { + IssueTrackerAccountId, + IssueTrackerKind, + MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES, +} from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { issueTrackerScopeOptions } from "./issueTrackers.ts"; +import { + boundIssueTrackerScopes, + issueTrackerBindingFor, + issueTrackerScopeOptions, +} from "./issueTrackers.ts"; describe("issueTrackerScopeOptions", () => { it("offers no new team once the binding is full, and keeps bound ones removable", () => { @@ -34,3 +42,14 @@ describe("issueTrackerScopeOptions", () => { expect(issueTrackerScopeOptions(tracker, ["ENG"]).every((scope) => scope.addable)).toBe(true); }); }); + +describe("boundIssueTrackerScopes", () => { + it("keeps each account's teams apart, and binds new picks with that account", () => { + const tracker = IssueTrackerKind.make("linear"); + const second = { tracker, accountId: IssueTrackerAccountId.make("second") }; + const binding = issueTrackerBindingFor(second, [], ["ENG", "OPS"]) ?? undefined; + expect(binding).toEqual({ ...second, scope: "ENG", additionalScopes: ["OPS"] }); + expect(boundIssueTrackerScopes(second, binding)).toEqual(["ENG", "OPS"]); + expect(boundIssueTrackerScopes({ tracker }, binding)).toEqual([]); + }); +}); diff --git a/packages/client-runtime/src/state/issueTrackers.ts b/packages/client-runtime/src/state/issueTrackers.ts index a4bb5187f8406..74c6bfb0674d8 100644 --- a/packages/client-runtime/src/state/issueTrackers.ts +++ b/packages/client-runtime/src/state/issueTrackers.ts @@ -2,10 +2,11 @@ import { MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES, WS_METHODS, issueTrackerBindingScopes, + type IssueTrackerBindProjectInput, type IssueTrackerConnection, type IssueTrackerConnectionList, - type IssueTrackerKind, type IssueTrackerProjectBinding, + type ProjectId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { Atom } from "effect/reactivity"; @@ -81,6 +82,21 @@ export function issueTrackerDetailText(detail: string, resolve: MFunctionType = return knownTrackerSentence(detail, SERVER_TRACKER_DETAILS, resolve); } +/** Every project's binding, whichever account it was made with. */ +export function issueTrackerBindings( + list: IssueTrackerConnectionList | null | undefined, +): IssueTrackerConnectionList["bindings"] { + return { ...list?.bindings, ...list?.accountBindings }; +} + +/** Whether a project binding reads through this account of the tracker. */ +function issueTrackerBindingIsFor( + binding: IssueTrackerProjectBinding, + tracker: Pick, +): boolean { + return binding.tracker === tracker.tracker && binding.accountId === tracker.accountId; +} + /** * The line under a tracker's name. A connected tracker lists nothing until a project is linked * to one of its scopes, so the line says how many are, and what to do when none is. @@ -98,8 +114,8 @@ export function issueTrackerSummary( ); if (tracker.account === null) return tracker.detail ?? resolve(msg("The saved credential was rejected.")); - const linked = Object.values(bindings).filter( - (binding) => binding.tracker === tracker.tracker, + const linked = Object.values(bindings).filter((binding) => + issueTrackerBindingIsFor(binding, tracker), ).length; return linked === 0 ? knownTrackerSentence( @@ -120,22 +136,42 @@ export function issueTrackerSummary( ); } +type TrackerAccount = Pick; + export function boundIssueTrackerScopes( - tracker: IssueTrackerKind, + tracker: TrackerAccount, binding: IssueTrackerProjectBinding | undefined, ): ReadonlyArray { - return binding?.tracker === tracker ? issueTrackerBindingScopes(binding) : []; + return binding !== undefined && issueTrackerBindingIsFor(binding, tracker) + ? issueTrackerBindingScopes(binding) + : []; } export function issueTrackerBindingFor( - tracker: IssueTrackerKind, + { tracker, accountId }: TrackerAccount, current: ReadonlyArray, scopes: ReadonlyArray, ): IssueTrackerProjectBinding | null { const kept = current.filter((key) => scopes.includes(key)); const [scope, ...additionalScopes] = [...kept, ...scopes.filter((key) => !kept.includes(key))]; if (scope === undefined) return null; - return additionalScopes.length === 0 ? { tracker, scope } : { tracker, scope, additionalScopes }; + return { + tracker, + ...(accountId === undefined ? {} : { accountId }), + scope, + ...(additionalScopes.length === 0 ? {} : { additionalScopes }), + }; +} + +/** The request that saves a project's picks under this account; an unbind names the account. */ +export function issueTrackerBindInput( + projectId: ProjectId, + { accountId }: TrackerAccount, + binding: IssueTrackerProjectBinding | null, +): IssueTrackerBindProjectInput { + return binding === null && accountId !== undefined + ? { projectId, binding, accountId } + : { projectId, binding }; } export function issueTrackerScopeOptions( @@ -156,6 +192,6 @@ export function hasIssueTrackerTeams( ): boolean { return ( tracker.scopes.length > 0 || - Object.values(bindings).some((binding) => binding.tracker === tracker.tracker) + Object.values(bindings).some((binding) => issueTrackerBindingIsFor(binding, tracker)) ); } diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index ae5bed14b44ba..b4f9f9c9d6865 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -224,6 +224,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ agentFeedback: Schema.optionalKey(Schema.Boolean), /** Answers `issues.linkedThreads`, the threads an issue is linked to. */ issueLinkedThreads: Schema.optionalKey(Schema.Boolean), + /** Keeps more than one account per standalone issue tracker; older servers keep one. */ + issueTrackerAccounts: Schema.optionalKey(Schema.Boolean), }); export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type; diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 93ed9daf6fba8..48ca2933b4039 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -30,6 +30,16 @@ export const IssueTrackerKind = TrimmedNonEmptyString.check( ).pipe(Schema.brand("IssueTrackerKind")); export type IssueTrackerKind = typeof IssueTrackerKind.Type; +/** + * One saved account of a standalone tracker. A tracker's first account has none: it predates + * accounts, and keeps its credential and bindings unchanged. + */ +export const IssueTrackerAccountId = TrimmedNonEmptyString.check( + Schema.isMaxLength(64), + Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/), +).pipe(Schema.brand("IssueTrackerAccountId")); +export type IssueTrackerAccountId = typeof IssueTrackerAccountId.Type; + export const IssueActor = PullRequestActor; export type IssueActor = typeof IssueActor.Type; @@ -590,6 +600,8 @@ export const MAX_ISSUE_TRACKER_ADDITIONAL_SCOPES = 250; */ export const IssueTrackerProjectBinding = Schema.Struct({ tracker: IssueTrackerKind, + /** The account the scope is read with; absent for the tracker's first account. */ + accountId: Schema.optional(IssueTrackerAccountId), scope: TrimmedNonEmptyString, additionalScopes: Schema.optionalKey( Schema.Array(TrimmedNonEmptyString).check( @@ -617,6 +629,8 @@ export type IssueTrackerScope = typeof IssueTrackerScope.Type; */ export const IssueTrackerConnection = Schema.Struct({ ...StandaloneIssueTrackerDescriptor.fields, + /** Which of the tracker's accounts this is; absent for its first. */ + accountId: Schema.optional(IssueTrackerAccountId), /** A credential is stored. It may still be rejected, which `account` being null reports. */ connected: Schema.Boolean, /** Who the credential signs in as, or null when there is none or it was refused. */ @@ -630,15 +644,29 @@ export const IssueTrackerConnection = Schema.Struct({ export type IssueTrackerConnection = typeof IssueTrackerConnection.Type; export const IssueTrackerConnectionList = Schema.Struct({ + /** Each standalone tracker's first account. */ trackers: Schema.Array(IssueTrackerConnection), - /** Which standalone tracker scopes each bound project reads; a project absent here reads none. */ + /** The accounts added beside a tracker's first, oldest first. Absent from older servers. */ + accounts: Schema.optional(Schema.Array(IssueTrackerConnection)), + /** + * Which standalone tracker scopes each project bound with a tracker's first account reads. A + * project bound with an added account is in `accountBindings` instead, so older clients never + * read another account's team as the first account's. + */ bindings: Schema.Record(ProjectId, IssueTrackerProjectBinding), + /** Projects bound with an added account. Absent from older servers. */ + accountBindings: Schema.optional(Schema.Record(ProjectId, IssueTrackerProjectBinding)), }); export type IssueTrackerConnectionList = typeof IssueTrackerConnectionList.Type; -/** A credential for one standalone tracker; `null` disconnects it and unbinds its projects. */ +/** + * A credential for one standalone tracker account; `null` disconnects it and unbinds its + * projects. `addAccount` saves the credential as a new account beside the existing ones. + */ export const IssueTrackerConnectInput = Schema.Struct({ tracker: IssueTrackerKind, + accountId: Schema.optional(IssueTrackerAccountId), + addAccount: Schema.optional(Schema.Boolean), token: Schema.NullOr(TrimmedNonEmptyString.check(Schema.isMaxLength(4_096))), }); export type IssueTrackerConnectInput = typeof IssueTrackerConnectInput.Type; @@ -647,6 +675,8 @@ export const IssueTrackerBindProjectInput = Schema.Struct({ projectId: ProjectId, /** Null unbinds. */ binding: Schema.NullOr(IssueTrackerProjectBinding), + /** On an unbind, the account the binding was made with; absent for a tracker's first. */ + accountId: Schema.optionalKey(IssueTrackerAccountId), }); export type IssueTrackerBindProjectInput = typeof IssueTrackerBindProjectInput.Type; diff --git a/packages/source-control-core/src/server/IssueTrackerHost.ts b/packages/source-control-core/src/server/IssueTrackerHost.ts index efc51b5046de2..eb85a2f711a5e 100644 --- a/packages/source-control-core/src/server/IssueTrackerHost.ts +++ b/packages/source-control-core/src/server/IssueTrackerHost.ts @@ -2,12 +2,12 @@ * What a standalone tracker package may ask of the server it runs in: the credential the user * saved in Settings. Git-host trackers never need it; their CLIs carry their own credentials. */ -import type { IssueTrackerKind } from "@t3tools/contracts"; +import type { IssueTrackerAccountId, IssueTrackerKind } from "@t3tools/contracts"; import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; +import * as Effect from "effect/Effect"; import type * as Option from "effect/Option"; -import type { IssueTrackerError } from "./IssueTracker.ts"; +import type { IssueTrackerApi, IssueTrackerError } from "./IssueTracker.ts"; export class IssueTrackerHost extends Context.Service< IssueTrackerHost, @@ -20,3 +20,53 @@ export class IssueTrackerHost extends Context.Service< }; } >()("@t3tools/source-control-core/server/IssueTrackerHost") {} + +/** + * The account a standalone tracker call is made as, set by the server around each call; null is + * the tracker's first account. A tracker never reads it: `credentials.get` does. + */ +export const IssueTrackerAccount = Context.Reference( + "@t3tools/source-control-core/server/IssueTrackerHost/IssueTrackerAccount", + { defaultValue: () => null }, +); + +/** The tracker with every call made as one account, so no call site can forget to name it. */ +export function asIssueTrackerAccount( + api: IssueTrackerApi, + accountId: IssueTrackerAccountId | null, +): IssueTrackerApi { + if (accountId === null) return api; + const as = (effect: Effect.Effect) => + Effect.provideService(effect, IssueTrackerAccount, accountId); + const { + getIssueLink, + create, + comment, + update, + setState, + setReaction, + listTemplates, + listCandidates, + } = api; + // Every key is required here, so a method added to IssueTrackerApi fails to compile until it + // is wrapped instead of silently running as the first account. + const wrapped: { readonly [K in keyof IssueTrackerApi]-?: IssueTrackerApi[K] | undefined } = { + kind: api.kind, + capabilities: api.capabilities, + getViewer: (input) => as(api.getViewer(input)), + listIssues: (input) => as(api.listIssues(input)), + getIssue: (input) => as(api.getIssue(input)), + getComments: (input) => as(api.getComments(input)), + getIssueLink: getIssueLink && ((input) => as(getIssueLink(input))), + create: create && ((input) => as(create(input))), + comment: comment && ((input) => as(comment(input))), + update: update && ((input) => as(update(input))), + setState: setState && ((input) => as(setState(input))), + setReaction: setReaction && ((input) => as(setReaction(input))), + listTemplates: listTemplates && ((input) => as(listTemplates(input))), + listCandidates: listCandidates && ((input) => as(listCandidates(input))), + }; + return Object.fromEntries( + Object.entries(wrapped).filter(([, value]) => value !== undefined), + ) as unknown as IssueTrackerApi; +} From 43af49bab0c85de2b964f020fbde569a1ef65daf Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 18:19:38 -0600 Subject: [PATCH 131/162] fix(server): keep inactive threads whose branch has an open PR (#41116) Co-authored-by: Julius Marminge --- .../ThreadSettlementService.test.ts | 62 +++++++++++++++++++ .../ThreadSettlementService.ts | 59 ++++++++++++++---- 2 files changed, 110 insertions(+), 11 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index 07bb2d64d80a5..80783a05f57ea 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -3,6 +3,7 @@ import { assert, describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import { DEFAULT_SERVER_SETTINGS, + GitManagerError, ProjectId, EventId, ProviderInstanceId, @@ -959,6 +960,67 @@ describe("ThreadSettlementServiceV2 worker", () => { }), ); + it.effect("keeps idle unlinked branch threads with an open PR under retention", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const earlier = "2026-08-19T00:00:00.000Z"; + const openPr = makeThread("idle-open", { + branch: "open", + latestUserMessageAt: DateTime.makeUnsafe(earlier), + }); + const reused = makeThread("idle-reused", { branch: "reused" }); + const link = persistedLink("open", DateTime.makeUnsafe("2026-06-20T00:00:00.000Z")); + const reusedOwner = makeThread("archived-reused-owner", { + branch: "reused", + archivedAt: DateTime.makeUnsafe("2026-07-02T00:00:00.000Z"), + pullRequests: [ + { + ...link, + snapshot: { ...link.snapshot!, state: "merged", mergedAt: "2026-07-01T00:00:00.000Z" }, + }, + ], + }); + const noPr = makeThread("idle-none", { branch: "none" }); + const merged = makeThread("idle-merged", { branch: "merged" }); + const failed = makeThread("idle-failed", { branch: "failed" }); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot([openPr, reused, reusedOwner, noPr, merged, failed]), + settings: { + ...DEFAULT_SERVER_SETTINGS, + sidebarAutoSettleAfterDays: 3, + sidebarAutoSettleKeepPullRequests: true, + }, + branchPullRequest: ({ branch, cwd }, options) => + branch === "open" + ? Effect.succeed(makeBranchPullRequest("open")) + : branch === "reused" + ? Effect.succeed( + options?.freshGitState === true + ? { ...makeBranchPullRequest("open"), number: 43 } + : { ...makeBranchPullRequest("merged"), mergedAt: "2026-07-01T00:00:00.000Z" }, + ) + : branch === "merged" + ? Effect.succeed({ ...makeBranchPullRequest("merged"), mergedAt: earlier }) + : branch === "failed" + ? Effect.fail( + new GitManagerError({ + operation: "branchPullRequest", + cwd, + detail: "failed", + }), + ) + : Effect.succeed(null), + }); + yield* Effect.gen(function* () { + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(service, fixture.activation, fixture.snapshotReads); + expect( + (yield* Ref.get(fixture.commands)).map((command) => command.threadId).toSorted(), + ).toEqual([failed.id, merged.id, noPr.id]); + }).pipe(Effect.provide(fixture.layer)); + }), + ); + it.effect("does not auto-settle a thread whose terminal has an active subprocess", () => Effect.gen(function* () { yield* TestClock.setTime(Date.parse(NOW)); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index ef0894f3ecbeb..308ec1795a315 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -442,6 +442,7 @@ export const make = Effect.gen(function* () { ), ); + const deferred = new Set(); const lookupCandidates = (yield* Effect.forEach( candidates, (thread) => { @@ -456,7 +457,17 @@ export const make = Effect.gen(function* () { autoSettleOnMerge: projectSettings.sidebarAutoSettleOnMerge, autoSettleKeepPullRequests: projectSettings.sidebarAutoSettleKeepPullRequests, }); - return settledAt === null ? Effect.succeed(thread) : settleThread(thread, null); + if (settledAt === null) return Effect.succeed(thread); + if ( + projectSettings.sidebarAutoSettleKeepPullRequests && + thread.branch !== null && + visibleThreadPullRequests(thread.pullRequests ?? []).length === 0 + ) { + // Retention needs the branch lookup to see whether an open PR keeps this thread. + deferred.add(thread.id); + return Effect.succeed(thread); + } + return settleThread(thread, null); }, { concurrency: 8 }, )) @@ -636,7 +647,10 @@ export const make = Effect.gen(function* () { } const refresh = group.filter((member) => shellClosedThreads.delete(member.id)).length > 0; const key = lookupKey(thread); - if (scheduledLookups !== null && !refresh && !scheduledLookups.has(key)) return undefined; + const hasDeferred = group.some((member) => deferred.has(member.id)); + if (scheduledLookups !== null && !refresh && !hasDeferred && !scheduledLookups.has(key)) { + return undefined; + } // Remembered git state is enough to rule a thread out; only an answer // that would settle it is confirmed against fresh git state. const remembered = yield* git.branchPullRequest( @@ -644,9 +658,16 @@ export const make = Effect.gen(function* () { { refresh, confirmTerminal: false }, ); noPullRequestRechecks.record(key, nowMs, remembered !== null); - if (ownedByAnotherThread(remembered)) return undefined; - if (refresh || remembered === null || remembered.state === "open") return remembered; - if (!(yield* wouldSettle(group, remembered))) return undefined; + if (refresh || remembered === null || remembered.state === "open") { + return ownedByAnotherThread(remembered) ? undefined : remembered; + } + // A deferred thread confirms first: a reused branch can have a new open PR. + if ( + !hasDeferred && + (ownedByAnotherThread(remembered) || !(yield* wouldSettle(group, remembered))) + ) { + return undefined; + } const fresh = yield* git.branchPullRequest( { cwd, branch: thread.branch }, { freshGitState: true }, @@ -661,13 +682,23 @@ export const make = Effect.gen(function* () { : noPullRequestRechecks.select( nowMs, [...groups] - .filter(([key]) => key.startsWith('["branch",')) + .filter( + ([key, group]) => + key.startsWith('["branch",') && !group.some((member) => deferred.has(member.id)), + ) .map(([key, group]) => ({ key, activityAtMs: Math.max(...group.map(threadActivityAtMs)), })), ); + const settleDeferred = (group: ReadonlyArray<(typeof lookupCandidates)[number]>) => + Effect.forEach( + group.filter((thread) => deferred.has(thread.id)), + (thread) => settleThread(thread, null), + { discard: true }, + ); + yield* Effect.forEach( groups.values(), (group) => @@ -679,10 +710,16 @@ export const make = Effect.gen(function* () { () => Effect.void, ), ); - if (pullRequest === undefined) return; - yield* Effect.forEach(group, (thread) => settleThread(thread, pullRequest), { - discard: true, - }); + if (pullRequest === undefined) return yield* settleDeferred(group); + yield* Effect.forEach( + group, + (thread) => + settleThread( + thread, + deferred.has(thread.id) && pullRequest?.state !== "open" ? null : pullRequest, + ), + { discard: true }, + ); }).pipe( Effect.catchCauseIf( (cause) => !Cause.hasInterruptsOnly(cause), @@ -690,7 +727,7 @@ export const make = Effect.gen(function* () { Effect.logWarning("automatic thread settlement skipped", { threadIds: group.map((thread) => thread.id), cause: Cause.pretty(cause), - }), + }).pipe(Effect.andThen(settleDeferred(group))), ), ), { concurrency: 8, discard: true }, From 1b59af07927ac8eba8efeffdbcaba8b92d645daf Mon Sep 17 00:00:00 2001 From: Ernest0N Date: Mon, 23 Nov 2026 04:38:19 +0400 Subject: [PATCH 132/162] fix(mobile): enlarge PR file Viewed tap target (#39950) Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt | 5 +++++ .../expo/modules/t3reviewdiff/T3ReviewDiffView.kt | 2 +- .../t3-review-diff/ios/T3ReviewDiffView.swift | 12 ++++++++++-- .../modules/t3reviewdiff/ReviewDiffGeometryTest.kt | 12 ++++++++++++ 4 files changed, 28 insertions(+), 3 deletions(-) diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt index d86861018c77d..3334efd268bc3 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt @@ -70,6 +70,11 @@ internal class ReviewDiffCanvasDrawing(context: Context) { ) } + fun fileHeaderCheckboxHitRect(top: Int, bottom: Int, width: Int, style: DiffStyle): RectF { + val checkbox = fileHeaderCheckboxRect(top, bottom, width, style) + return RectF(checkbox.left - 14f * density, top.toFloat(), width.toFloat(), bottom.toFloat()) + } + fun drawDisclosureChevron( canvas: Canvas, rect: RectF, diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index e2d5a12d76304..2888917a89044 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -766,7 +766,7 @@ private class DiffCanvasView(context: Context) : View(context) { rowHitAt(event.y)?.let { hit -> val target = if ( hit.row.kind == "file" && - drawing.fileHeaderCheckboxRect( + drawing.fileHeaderCheckboxHitRect( hit.top, hit.bottom, width, diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index 0c65ddf19460a..07d9a58a3553c 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -1029,6 +1029,7 @@ private struct ReviewDiffFileHeaderInteractiveRects { let chevron: CGRect let icon: CGRect let checkbox: CGRect + let checkboxHitTarget: CGRect } private struct ReviewDiffStickyFileHeaderIndex { @@ -1643,7 +1644,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let interactiveRects = fileHeaderInteractiveRects(for: row, cardRect: rect) let fileId = resolvedFileId(for: row) - if interactiveRects.checkbox.contains(point) { + if interactiveRects.checkboxHitTarget.contains(point) { onToggleViewedFile?(fileId) return } @@ -2349,10 +2350,17 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let chevronRect = CGRect(x: cardRect.minX + horizontalPadding, y: centerY - 10, width: 20, height: 20) let iconRect = CGRect(x: chevronRect.maxX + 8, y: centerY - 10, width: 20, height: 20) let checkboxRect = CGRect(x: cardRect.maxX - horizontalPadding - 20, y: centerY - 10, width: 20, height: 20) + let checkboxHitMinX = checkboxRect.minX - 14 return ReviewDiffFileHeaderInteractiveRects( chevron: chevronRect, icon: iconRect, - checkbox: checkboxRect + checkbox: checkboxRect, + checkboxHitTarget: CGRect( + x: checkboxHitMinX, + y: cardRect.minY, + width: cardRect.maxX - checkboxHitMinX, + height: cardRect.height + ) ) } diff --git a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt index f2992979bf522..63e1acece9074 100644 --- a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt +++ b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt @@ -149,6 +149,18 @@ class ReviewDiffGeometryTest { } } + @Test + fun viewedCheckboxHitTargetSpansTheHeaderHeightAndTrailingEdge() { + val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) + val style = DiffStyle.defaults(1f) + val glyph = drawing.fileHeaderCheckboxRect(100, 144, 320, style) + val hit = drawing.fileHeaderCheckboxHitRect(100, 144, 320, style) + assertTrue(hit.contains(glyph)) + assertTrue(hit.contains(glyph.left - 13f, 101f)) + assertTrue(hit.contains(319f, 143f)) + assertTrue(!hit.contains(glyph.left - 15f, 122f)) + } + @Test fun asciiWidthCacheDoesNotRetainPerRowMeasurementObjects() { val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) From 05c100fbd893afbc127d29d9ac340d5e1e6412ef Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 18:38:58 -0600 Subject: [PATCH 133/162] fix(server): skip queued checkpoint restores after thread deletion (#41113) Co-authored-by: Julius Marminge --- .../CheckpointRestoreSafety.test.ts | 1 + .../CheckpointRollbackService.test.ts | 24 +++++++++++++++++++ .../CheckpointRollbackService.ts | 1 + .../src/orchestration-v2/Orchestrator.ts | 7 ++++++ .../src/orchestration-v2/runtimeLayer.test.ts | 21 ++++++++++++++++ 5 files changed, 54 insertions(+) diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts index 69f7661b8931c..95dca7c2b1a15 100644 --- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts @@ -80,6 +80,7 @@ it.effect.each([ worktreePath: cwd, activeProviderThreadId: providerThreadId, modelSelection: { instanceId, model: "test" }, + deletedAt: null, }, providerThread, providerSession: undefined, diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index ff368dccb64d9..fd5d9c34b5bcd 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -82,6 +82,7 @@ it.effect.each(["initial", "waiting"])( worktreePath: process.cwd(), activeProviderThreadId: providerThreadId, modelSelection: { instanceId: providerInstanceId, model: "test-model" }, + deletedAt: null, }, providerThread: { id: providerThreadId, providerSessionId, providerInstanceId }, checkpoint: { @@ -217,6 +218,7 @@ it.effect.each([ branch, activeProviderThreadId: providerThreadId, modelSelection: { instanceId: providerInstanceId, model: "test-model" }, + deletedAt: null, }, providerThread, providerSession: undefined, @@ -436,6 +438,7 @@ it.effect.each([ branch: "feature/rollback-reservation", activeProviderThreadId: providerThreadId, modelSelection: { instanceId: providerInstanceId, model: "test-model" }, + deletedAt: null, }, providerThread: { id: providerThreadId, @@ -997,5 +1000,26 @@ it.layer(ProjectionStore.layer.pipe(Layer.provideMerge(SqlitePersistence.layerMe ); }), ); + + it.effect("skips a pending rollback once the thread is deleted", () => + Effect.gen(function* () { + const history = yield* seedRollbackHistory; + const thread = yield* history.store.getThread(history.threadId); + yield* history.store.apply({ + id: EventId.make("rollback-history-deleted"), + type: "thread.deleted", + threadId: history.threadId, + providerInstanceId: thread.providerInstanceId, + occurredAt: history.now, + payload: { ...thread, deletedAt: history.now, updatedAt: history.now }, + }); + + yield* history.rollback(2); + + assert.deepEqual(history.rollbackCounts, []); + assert.deepEqual(history.restored, []); + assert.deepEqual(history.committed, []); + }), + ); }, ); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 8d6fd1c09441d..e85175ef2ee33 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -156,6 +156,7 @@ export const layer: Layer.Layer< readonly requestId?: CommandId; }) { const context = yield* projections.getCheckpointRollbackContext(input.threadId, input); + if (context.thread.deletedAt !== null) return; const { providerThread, checkpoint, scope, targetAttempt, runsToRollback, staleCheckpoints } = context; const restoreFiles = input.restoreFiles !== false; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6920d26d3502f..13fc22a0a051c 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14572,6 +14572,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ["providerThreads", "checkpoints", "checkpointScopes", "runs", "providerTurns", "attempts"], { turnItemTypes: [], messageRoles: ["user"] }, ); + if (projection.thread.deletedAt !== null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} is deleted.`, + }); + } const providerThread = projection.providerThreads.find( (candidate) => candidate.id === projection.thread.activeProviderThreadId, ); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 11525ba32170f..3d640f61fc398 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1865,6 +1865,27 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { conversationOnly.storedEvents.map((stored) => stored.event.type), ["thread.metadata-updated", "checkpoint.rollback-requested"], ); + yield* orchestrator.dispatch({ + type: "thread.delete", + commandId: CommandId.make("runtime-rollback-delete"), + threadId, + }); + const deletedCommandId = CommandId.make("runtime-rollback-deleted"); + const deletedSequence = yield* orchestrator.getThreadEventSequence(threadId); + const deleted = yield* orchestrator + .dispatch({ + type: "checkpoint.rollback", + commandId: deletedCommandId, + threadId, + checkpointId, + scopeId: scope.id, + restoreFiles: false, + }) + .pipe(Effect.flip); + assert.instanceOf(deleted, Orchestrator.OrchestratorDispatchError); + assert.equal(deleted.cause, `Thread ${threadId} is deleted.`); + assert.equal(yield* orchestrator.getThreadEventSequence(threadId), deletedSequence); + assert.deepEqual(yield* outbox.listByCommandId(deletedCommandId), []); } else { const error = yield* rollback.pipe(Effect.flip); assert.instanceOf(error, Orchestrator.OrchestratorDispatchError); From 65b2e6dae66f15caa03abf57ba2fe67da1d769aa Mon Sep 17 00:00:00 2001 From: SSH Date: Sun, 22 Nov 2026 19:39:44 -0500 Subject: [PATCH 134/162] fix(web): stop telemetry refresh spinning after data arrives (#41122) Co-authored-by: Julius Marminge --- .../resourceTelemetryState.browser.test.tsx | 45 +++++++++++++++++++ apps/web/src/lib/resourceTelemetryState.ts | 4 +- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx b/apps/web/src/lib/resourceTelemetryState.browser.test.tsx index 981beeafdfd38..f93c53aff89fd 100644 --- a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx +++ b/apps/web/src/lib/resourceTelemetryState.browser.test.tsx @@ -173,6 +173,7 @@ function setup({ retryFails = false, holdRetry = false } = {}) { const registry = AtomRegistry.make(); return { registry, + snapshot, historyQueries, historyReads, releaseRetry, @@ -265,4 +266,48 @@ describe("resource monitor retry", () => { await expect.element(screen.getByText(startError, { exact: true })).toBeVisible(); await expect.element(screen.getByText(historyError, { exact: true })).toBeVisible(); }); + + it("stops showing refresh as pending after the first live snapshot arrives", async () => { + using fixture = setup(); + const liveTelemetry = Atom.make< + AsyncResult.AsyncResult + >(AsyncResult.initial(true)).pipe(Atom.keepAlive); + monitor.telemetry.mockImplementation(() => liveTelemetry); + + await using screen = await render( + + + , + ); + const refreshButton = screen.getByRole("button", { name: "Refresh resource telemetry" }); + await expect.element(refreshButton).toBeDisabled(); + + await act(() => { + fixture.registry.set( + liveTelemetry, + AsyncResult.waiting(AsyncResult.success(fixture.snapshot)), + ); + }); + await expect.element(refreshButton).toBeEnabled(); + }); + + it("stops showing refresh as pending after a live subscription error", async () => { + using fixture = setup(); + const liveTelemetry = Atom.make< + AsyncResult.AsyncResult + >(AsyncResult.waiting(AsyncResult.fail(new MonitorError({ message: startError })))).pipe( + Atom.keepAlive, + ); + monitor.telemetry.mockImplementation(() => liveTelemetry); + + await using screen = await render( + + + , + ); + await expect.element(screen.getByText(startError, { exact: true })).toBeVisible(); + await expect + .element(screen.getByRole("button", { name: "Refresh resource telemetry" })) + .toBeEnabled(); + }); }); diff --git a/apps/web/src/lib/resourceTelemetryState.ts b/apps/web/src/lib/resourceTelemetryState.ts index 5105195d41e28..1fe63398c95b7 100644 --- a/apps/web/src/lib/resourceTelemetryState.ts +++ b/apps/web/src/lib/resourceTelemetryState.ts @@ -60,7 +60,9 @@ export function useResourceTelemetry( return result.value.snapshot; }; - return { ...query, retry }; + // The live subscription keeps waiting for updates after its first snapshot. + const isPending = query.isPending && query.data === null && query.error === null; + return { ...query, isPending, retry }; } export function useResourceTelemetryHistory( From def64e3a54be24a9840edb229619d401568b3b82 Mon Sep 17 00:00:00 2001 From: Mike Ozornin Date: Mon, 23 Nov 2026 04:01:30 +0300 Subject: [PATCH 135/162] fix(web): clicking the selected file in a Files folder view opens it (#41117) Co-authored-by: Julius Marminge --- .../files/FileBrowserPanel.browser.test.tsx | 4 +++ .../src/components/files/FileBrowserPanel.tsx | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx index 8d069fc766d38..1924cbb941cf9 100644 --- a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx @@ -162,6 +162,10 @@ describe("FileBrowserPanel", () => { row.click(); await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(1)); + + // The selection stays put, so reopening the selected file must not depend on a selection change. + row.click(); + await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(2)); }); it("keeps an expanded folder open when a very large listing rebuilds the tree", async () => { diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index cd44d99220939..8f0bf626ba034 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -649,6 +649,32 @@ export default function FileBrowserPanel({ model={model} aria-label={gt("{projectName} files", { projectName })} className="min-h-0 flex-1 overflow-hidden" + onClickCapture={(event) => { + if ( + event.defaultPrevented || + event.button !== 0 || + event.ctrlKey || + event.metaKey || + event.shiftKey || + event.altKey || + dragMention.isDragInProgress() + ) { + return; + } + // Pierre emits no change for its sole selected row; read before the click to avoid double opens. + const selected = model.getSelectedPaths(); + const path = selected.length === 1 ? selected[0] : undefined; + if (!path || entryKindsRef.current.get(path) !== "file") return; + const clickedSelectedRow = event.nativeEvent + .composedPath() + .some( + (node) => + node instanceof HTMLElement && node.getAttribute("data-item-path") === path, + ); + if (!clickedSelectedRow) return; + treeSelectionPathRef.current = path; + onOpenFile(panelPath(path)); + }} style={pierreTreeStyle(resolvedTheme)} onPointerOver={titleClippedPierreTreeRow} /> From 6b38ec931aab43077760012d0502514e67f7b7ee Mon Sep 17 00:00:00 2001 From: Tyler Bruno Date: Sun, 22 Nov 2026 20:12:29 -0500 Subject: [PATCH 136/162] fix(desktop): remote servers behind origin-checking proxies no longer reject Desktop with 403 (#41092) Co-authored-by: Amp Co-authored-by: Julius Marminge --- apps/desktop/src/electron/ElectronProtocol.ts | 2 +- apps/desktop/src/window/DesktopWindow.test.ts | 6 + apps/desktop/src/window/DesktopWindow.ts | 22 ++- .../src/window/RemoteRequestHeaders.test.ts | 186 ++++++++++++++++++ .../src/window/RemoteRequestHeaders.ts | 129 ++++++++++++ apps/server/src/http.test.ts | 60 ++++++ apps/server/src/http.ts | 55 ++++-- 7 files changed, 446 insertions(+), 14 deletions(-) create mode 100644 apps/desktop/src/window/RemoteRequestHeaders.test.ts create mode 100644 apps/desktop/src/window/RemoteRequestHeaders.ts diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts index 7563898f43efc..43208638f12d8 100644 --- a/apps/desktop/src/electron/ElectronProtocol.ts +++ b/apps/desktop/src/electron/ElectronProtocol.ts @@ -20,7 +20,7 @@ export function getDesktopScheme(isDevelopment: boolean): string { return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME; } -function getDesktopOrigin(isDevelopment: boolean): string { +export function getDesktopOrigin(isDevelopment: boolean): string { return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`; } diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index f2b655b1b69d8..e4e426b1975ae 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -74,6 +74,12 @@ function makeFakeBrowserWindow() { const webContentsListeners = new Map void>(); let zoomLevel = 0; const webContents = { + id: 1, + session: { + webRequest: { + onBeforeSendHeaders: vi.fn(), + }, + }, copyImageAt: vi.fn(), focus: vi.fn(), isDestroyed: vi.fn(() => false), diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 880b9dfef4ab9..c99fbb52c49e2 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -14,12 +14,13 @@ import { msg } from "gt-i18n"; import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; import * as DesktopAssets from "../app/DesktopAssets.ts"; +import * as DesktopClerk from "../app/DesktopClerk.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopPrimaryPaste from "../app/DesktopPrimaryPaste.ts"; import { makeComponentLogger } from "../app/DesktopObservability.ts"; import * as DesktopState from "../app/DesktopState.ts"; import * as ElectronMenu from "../electron/ElectronMenu.ts"; -import { getDesktopUrl } from "../electron/ElectronProtocol.ts"; +import { getDesktopOrigin, getDesktopUrl } from "../electron/ElectronProtocol.ts"; import * as ElectronShell from "../electron/ElectronShell.ts"; import * as ElectronTheme from "../electron/ElectronTheme.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; @@ -44,6 +45,7 @@ import { m } from "../i18n/messages.ts"; import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts"; import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; +import { installMainWindowRemoteRequestHeaderPolicy } from "./RemoteRequestHeaders.ts"; const TITLEBAR_HEIGHT = 40; @@ -408,6 +410,7 @@ export const make = Effect.gen(function* () { Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)), ); let flushMainWindowBounds: Effect.Effect = Effect.void; + let remoteRequestHeaderOwner: Electron.BrowserWindow | null = null; const dismissConnectingSplash = Effect.gen(function* () { const splash = yield* Ref.getAndSet(splashWindowRef, Option.none()); @@ -1036,6 +1039,19 @@ export const make = Effect.gen(function* () { // Desktop IPC only answers the main window, so register it before its renderer can call in. yield* electronWindow.setMain(window); + remoteRequestHeaderOwner = window; + const detachRemoteRequestHeaders = installMainWindowRemoteRequestHeaderPolicy( + window.webContents.session, + { + desktopOrigin: getDesktopOrigin(environment.isDevelopment), + mainWebContentsId: window.webContents.id, + clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname, + devServerOrigin: Option.getOrUndefined( + Option.map(environment.devServerUrl, (url) => url.origin), + ), + isDevelopment: environment.isDevelopment, + }, + ); loadApplication(); if (environment.isDevelopment) { window.webContents.openDevTools({ mode: "detach" }); @@ -1045,6 +1061,10 @@ export const make = Effect.gen(function* () { if (!backendHasStarted) mainClosedDuringStartup = true; clearDevelopmentLoadRetry(); clearBoundsPersist(); + if (remoteRequestHeaderOwner === window) { + remoteRequestHeaderOwner = null; + detachRemoteRequestHeaders(); + } void runPromise(electronWindow.clearMain(Option.some(window))); }); diff --git a/apps/desktop/src/window/RemoteRequestHeaders.test.ts b/apps/desktop/src/window/RemoteRequestHeaders.test.ts new file mode 100644 index 0000000000000..fee9aedb16c63 --- /dev/null +++ b/apps/desktop/src/window/RemoteRequestHeaders.test.ts @@ -0,0 +1,186 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { + stripDesktopOriginHeaders, + type MainWindowRequestHeaderPolicy, +} from "./RemoteRequestHeaders.ts"; + +const packagedPolicy: MainWindowRequestHeaderPolicy = { + desktopOrigin: "t3code://app", + mainWebContentsId: 42, + clerkFrontendApiHostname: "clerk.t3.codes", + isDevelopment: false, +}; + +const devPolicy: MainWindowRequestHeaderPolicy = { + desktopOrigin: "t3code-dev://app", + mainWebContentsId: 42, + clerkFrontendApiHostname: "clerk.t3.codes", + devServerOrigin: "http://devbox.internal:5733", + isDevelopment: true, +}; + +describe("RemoteRequestHeaders", () => { + it.each([ + "https://remote.example.com/.well-known/t3/environment", + "http://127.0.0.1:8080/api/auth/bootstrap", + "ws://127.0.0.1:8080/ws?ticket=abc", + "wss://remote.example.com/ws?ticket=abc", + ])("strips Origin and Sec-Fetch-* on outbound main-window %s requests", (url) => { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Dest": "empty", + "sec-fetch-user": "?1", + Authorization: "Bearer secret", + DPoP: "proof-jwt", + }, + }); + + assert.deepEqual(headers, { + Authorization: "Bearer secret", + DPoP: "proof-jwt", + }); + }); + + it("strips lowercase origin headers and allows null frames (WebSocket upgrades and workers)", () => { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url: "wss://remote.example.com/ws", + webContentsId: 42, + frame: null, + requestHeaders: { + origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + Upgrade: "websocket", + }, + }); + + assert.deepEqual(headers, { + Upgrade: "websocket", + }); + }); + + it("preserves headers for Clerk frontend API requests", () => { + for (const url of ["https://clerk.t3.codes/v1/client", "https://CLERK.T3.CODES./v1/client"]) { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }); + assert.isUndefined(headers); + } + }); + + it("preserves headers for dev loopback and exact devServerOrigin, while stripping other ports and remote hosts", () => { + for (const url of [ + "http://localhost:3773/api/health", + "http://app.localhost:3773/api/health", + "http://127.0.0.1:3773/api/health", + "http://[::1]:3773/api/health", + "ws://127.0.0.1:3773/ws", + "http://devbox.internal:5733/api/health", + "ws://devbox.internal:5733/ws", + ]) { + assert.isUndefined( + stripDesktopOriginHeaders(devPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code-dev://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + } + + for (const url of [ + "http://devbox.internal:8080/api/auth/bootstrap", + "https://remote.example.com/api/auth/bootstrap", + ]) { + assert.deepEqual( + stripDesktopOriginHeaders(devPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code-dev://app", + "Sec-Fetch-Site": "cross-site", + "Content-Type": "application/json", + }, + }), + { "Content-Type": "application/json" }, + ); + } + }); + + it("never touches sandboxed iframes (Origin: null), subframes, or other webContents", () => { + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "null", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: {} }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 99, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: undefined, + frame: null, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + }); +}); diff --git a/apps/desktop/src/window/RemoteRequestHeaders.ts b/apps/desktop/src/window/RemoteRequestHeaders.ts new file mode 100644 index 0000000000000..61df4c3535160 --- /dev/null +++ b/apps/desktop/src/window/RemoteRequestHeaders.ts @@ -0,0 +1,129 @@ +import * as NetAddress from "effect/net/NetAddress"; +import * as Result from "effect/Result"; +import type * as Electron from "electron"; + +// `*://` matches only http and https, so WebSocket schemes are listed separately. +const REMOTE_REQUEST_URL_PATTERNS = ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*"]; + +export interface MainWindowRequestHeaderPolicy { + readonly desktopOrigin: string; + readonly mainWebContentsId: number; + readonly clerkFrontendApiHostname?: string | undefined; + readonly devServerOrigin?: string | undefined; + readonly isDevelopment: boolean; +} + +export interface MainWindowRequestHeaderDetails { + readonly url: string; + readonly webContentsId?: number | undefined; + readonly frame?: { readonly parent: unknown } | null | undefined; + readonly requestHeaders: Record; +} + +function normalizeHostname(hostname: string): string { + return hostname + .toLowerCase() + .replace(/^\[(.*)\]$/, "$1") + .replace(/\.$/, ""); +} + +function isLoopbackHostname(hostname: string): boolean { + return ( + hostname === "localhost" || + hostname.endsWith(".localhost") || + Result.match(NetAddress.ipFromString(hostname), { + onSuccess: NetAddress.isLoopback, + onFailure: () => false, + }) + ); +} + +function toHttpOrigin(url: URL): string { + if (url.protocol === "ws:") { + return `http://${url.host}`; + } + if (url.protocol === "wss:") { + return `https://${url.host}`; + } + return url.origin; +} + +function isSubframe(details: MainWindowRequestHeaderDetails): boolean { + try { + return details.frame != null && details.frame.parent !== null; + } catch { + return true; + } +} + +function hasExactDesktopOriginHeader( + requestHeaders: Record, + desktopOrigin: string, +): boolean { + let matched = false; + for (const [name, value] of Object.entries(requestHeaders)) { + if (name.toLowerCase() !== "origin") continue; + if (value !== desktopOrigin) return false; + matched = true; + } + return matched; +} + +function shouldPreserveOriginHeader(policy: MainWindowRequestHeaderPolicy, url: URL): boolean { + const hostname = normalizeHostname(url.hostname); + if ( + policy.clerkFrontendApiHostname !== undefined && + hostname === normalizeHostname(policy.clerkFrontendApiHostname) + ) { + return true; + } + if (!policy.isDevelopment) return false; + if (policy.devServerOrigin !== undefined && toHttpOrigin(url) === policy.devServerOrigin) { + return true; + } + return isLoopbackHostname(hostname); +} + +/** + * Strips Electron's synthetic `Origin` (`t3code://app`) and `Sec-Fetch-*` headers on outbound + * main-window requests so origin-checking reverse proxies treat Desktop like native T3 clients. + */ +export function stripDesktopOriginHeaders( + policy: MainWindowRequestHeaderPolicy, + details: MainWindowRequestHeaderDetails, +): Record | undefined { + if (details.webContentsId !== policy.mainWebContentsId) return undefined; + if (isSubframe(details)) return undefined; + if (!hasExactDesktopOriginHeader(details.requestHeaders, policy.desktopOrigin)) { + return undefined; + } + + const parsedUrl = URL.parse(details.url); + if (parsedUrl === null || shouldPreserveOriginHeader(policy, parsedUrl)) { + return undefined; + } + + const nextHeaders: Record = {}; + for (const [name, value] of Object.entries(details.requestHeaders)) { + const lowerName = name.toLowerCase(); + if (lowerName === "origin" || lowerName.startsWith("sec-fetch-")) continue; + nextHeaders[name] = value; + } + return nextHeaders; +} + +export function installMainWindowRemoteRequestHeaderPolicy( + session: Pick, + policy: MainWindowRequestHeaderPolicy, +): () => void { + session.webRequest.onBeforeSendHeaders( + { urls: REMOTE_REQUEST_URL_PATTERNS }, + (details, callback) => { + const requestHeaders = stripDesktopOriginHeaders(policy, details); + callback(requestHeaders === undefined ? {} : { requestHeaders }); + }, + ); + return () => { + session.webRequest.onBeforeSendHeaders(null); + }; +} diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts index d0f5b39800319..6e011aef39d26 100644 --- a/apps/server/src/http.test.ts +++ b/apps/server/src/http.test.ts @@ -172,6 +172,66 @@ describe("browser API CORS", () => { await dispose(); } }); + + it("allows originless desktop requests in dev mode while still rejecting disallowed browser origins", async () => { + const layerRoute = Layer.effectDiscard( + Effect.gen(function* () { + const router = yield* HttpRouter.HttpRouter; + yield* router.add( + "GET", + "/api/environment", + HttpServerResponse.empty({ headers: { vary: "Accept-Encoding" } }), + ); + }), + ); + const layerDevConfig = Layer.effect( + ServerConfig.ServerConfig, + Effect.map(ServerConfig.ServerConfig, (config) => ({ + ...config, + devUrl: new URL("http://127.0.0.1:5733"), + })), + ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "http-dev-cors-test-" }))); + const layerApp = Layer.merge(layerRoute, ServerHttp.layerBrowserApiCors).pipe( + Layer.provide(layerDevConfig), + Layer.provide(NodeServices.layer), + ); + const { handler, dispose } = HttpRouter.toWebHandler(layerApp, { disableLogger: true }); + + try { + const originless = await handler( + new Request("https://dev.example/api/environment", { method: "GET" }), + ); + expect(originless.headers.get("access-control-allow-origin")).toBe("*"); + expect(originless.headers.get("access-control-allow-credentials")).toBeNull(); + expect(originless.headers.get("vary")).toBe("Accept-Encoding, Origin"); + + const originlessPreflight = await handler( + new Request("https://dev.example/api/environment", { method: "OPTIONS" }), + ); + expect(originlessPreflight.status).toBe(204); + expect(originlessPreflight.headers.get("access-control-allow-origin")).toBe("*"); + expect(originlessPreflight.headers.get("vary")).toBe("Origin"); + + const allowed = await handler( + new Request("https://dev.example/api/environment", { + method: "GET", + headers: { origin: "http://127.0.0.1:5733" }, + }), + ); + expect(allowed.headers.get("access-control-allow-origin")).toBe("http://127.0.0.1:5733"); + expect(allowed.headers.get("access-control-allow-credentials")).toBe("true"); + + const disallowed = await handler( + new Request("https://dev.example/api/environment", { + method: "GET", + headers: { origin: "https://evil.example" }, + }), + ); + expect(disallowed.headers.get("access-control-allow-origin")).toBeNull(); + } finally { + await dispose(); + } + }); }); describe("untraced requests", () => { diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 47215bef97f7d..acec877a45c55 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -22,6 +22,7 @@ import { cast, pipe } from "effect/Function"; import { HttpClient, HttpClientResponse, + HttpEffect, HttpMiddleware, HttpRouter, HttpServerResponse, @@ -274,28 +275,58 @@ export const layerHttpCompression = HttpRouter.middleware(HttpMiddleware.compres global: true, }); +function withVaryOrigin( + response: HttpServerResponse.HttpServerResponse, +): HttpServerResponse.HttpServerResponse { + const existing = response.headers.vary; + if ( + existing !== undefined && + existing.split(",").some((token) => token.trim().toLowerCase() === "origin") + ) { + return response; + } + return HttpServerResponse.setHeader( + response, + "vary", + existing ? `${existing}, Origin` : "Origin", + ); +} + export const layerBrowserApiCors = Layer.unwrap( Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const devOrigin = config.devUrl?.origin; - // Credentialed dev requests need explicit Vite/Electron origins; packaged desktop uses the default wildcard. - const cors = HttpMiddleware.cors({ - ...(devOrigin - ? { - allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins], - credentials: true, - } - : {}), + // Credentialed dev requests need explicit Vite/Electron origins; originless desktop/native + // requests and packaged servers use the non-credentialed wildcard. + const wildcardCors = HttpMiddleware.cors({ allowedMethods: browserApiCorsAllowedMethods, allowedHeaders: browserApiCorsAllowedHeaders, maxAge: 600, }); + const devCors = devOrigin + ? HttpMiddleware.cors({ + allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins], + credentials: true, + allowedMethods: browserApiCorsAllowedMethods, + allowedHeaders: browserApiCorsAllowedHeaders, + maxAge: 600, + }) + : undefined; return HttpRouter.middleware( (httpEffect) => { - const withCors = cors(httpEffect); - return Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => - request.url.split("?", 1)[0] === MCP_HTTP_PATH ? httpEffect : withCors, - ); + const withWildcardCors = wildcardCors(httpEffect); + const withDevCors = devCors ? devCors(httpEffect) : undefined; + return Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => { + if (request.url.split("?", 1)[0] === MCP_HTTP_PATH) return httpEffect; + if (!withDevCors) return withWildcardCors; + if (request.headers.origin !== undefined) return withDevCors; + if (request.method === "OPTIONS") { + return Effect.map(withWildcardCors, withVaryOrigin); + } + return HttpEffect.appendPreResponseHandler((_request, response) => + Effect.succeed(withVaryOrigin(response)), + ).pipe(Effect.andThen(withWildcardCors)); + }); }, { global: true }, ); From 83119ae8bd0507138faa78be56299d073aab2daa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 17:34:52 -0800 Subject: [PATCH 137/162] fix(server): stopping a delegated child with a queued message no longer ends its task (#41140) --- .../DelegatedChildTerminalRetry.test.ts | 256 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 29 +- .../src/server/subagentProjection.ts | 18 +- 3 files changed, 293 insertions(+), 10 deletions(-) diff --git a/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts index b9c20c02b5afe..7658acaa9f955 100644 --- a/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedChildTerminalRetry.test.ts @@ -31,6 +31,7 @@ const driver = ProviderDriverKind.make("claudeAgent"); const instanceId = ProviderInstanceId.make("claudeAgent"); const modelSelection = { instanceId, model: "claude-test" }; const parentThreadId = ThreadId.make("thread:delegated-terminal-retry-parent"); +const stopRaceParentId = ThreadId.make("thread:delegated-stop-race-parent"); const childError = "Failed to initialize session: No space left on device"; type ParentRead = { @@ -326,3 +327,258 @@ it.effect("a delegated child reaches its parent after its own delivery read fail failChildRunMessage: true, }), ); + +it.effect("stopping a delegated child with a queued message does not report the task ended", () => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("delegated-stop-race"); + const turns: Array<{ + readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput; + readonly events: Queue.Queue; + }> = []; + const terminal = (entry: (typeof turns)[number], status: "completed" | "interrupted") => + Effect.gen(function* () { + const now = yield* DateTime.now; + const providerTurnId = ProviderTurnId.make(`provider-turn:${entry.turn.attemptId}`); + yield* Queue.offer(entry.events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: providerTurnId, + providerThreadId: entry.turn.providerThread.id, + nodeId: entry.turn.rootNodeId, + runAttemptId: entry.turn.attemptId, + nativeTurnRef: null, + ordinal: entry.turn.providerTurnOrdinal, + status, + startedAt: now, + completedAt: now, + }, + }); + yield* Queue.offer(entry.events, { + type: "turn.terminal", + driver, + providerThreadId: entry.turn.providerThread.id, + providerTurnId, + runOrdinal: entry.turn.runOrdinal, + status, + failure: null, + threadDisposition: "reusable", + }); + }); + const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + instanceId, + driver, + getCapabilities: () => Effect.succeed(ClaudeProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), + openSession: (session) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const events = yield* Queue.unbounded(); + return { + instanceId, + driver, + providerSessionId: session.providerSessionId, + providerSession: { + id: session.providerSessionId, + driver, + providerInstanceId: instanceId, + status: "ready", + cwd, + model: modelSelection.model, + capabilities: ClaudeProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + events: Stream.fromQueue(events), + ensureThread: ({ threadId }) => + Effect.succeed({ + id: ProviderThreadId.make(`provider-thread:${threadId}`), + driver, + providerInstanceId: instanceId, + providerSessionId: session.providerSessionId, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: `native:${threadId}`, strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }), + resumeThread: ({ providerThread }) => Effect.succeed(providerThread), + startTurn: (turn) => + Effect.gen(function* () { + turns.push({ turn, events }); + yield* Queue.offer(events, { + type: "provider_turn.updated", + driver, + providerTurn: { + id: ProviderTurnId.make(`provider-turn:${turn.attemptId}`), + providerThreadId: turn.providerThread.id, + nodeId: turn.rootNodeId, + runAttemptId: turn.attemptId, + nativeTurnRef: null, + ordinal: turn.providerTurnOrdinal, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + }), + steerTurn: () => Effect.die("unused"), + interruptTurn: ({ providerTurnId }) => + Effect.gen(function* () { + const entry = turns.find( + (candidate) => + ProviderTurnId.make(`provider-turn:${candidate.turn.attemptId}`) === + providerTurnId, + ); + if (entry !== undefined) yield* terminal(entry, "interrupted"); + }), + respondToRuntimeRequest: () => Effect.die("unused"), + readThreadSnapshot: () => Effect.die("unused"), + rollbackThread: () => Effect.die("unused"), + forkThread: () => Effect.die("unused"), + }; + }), + }; + const layerTest = ProviderReplayHarness.layerWithRegistry( + { name: "delegated-stop-race" }, + ProviderAdapterRegistry.layerSingle(adapter), + { runEffectWorker: false, runContinuationWorker: true }, + ); + + return yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamDomainEvents.pipe( + Stream.filter(predicate), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + const settle = Effect.gen(function* () { + for (let attempt = 0; attempt < 5; attempt++) { + yield* worker.drain(); + yield* TestClock.adjust("1 second"); + } + }); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-parent"), + threadId: stopRaceParentId, + projectId: ProjectId.make("project:delegated-stop-race"), + title: "Parent", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const parentRunning = yield* watch( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-parent"), + threadId: stopRaceParentId, + messageId: MessageId.make("message:start-parent"), + text: "Delegate the work", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(parentRunning); + const parentRun = (yield* orchestrator.getThreadProjection(stopRaceParentId)).runs[0]!; + + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate"), + parentThreadId: stopRaceParentId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Do the work", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + completionWake: "always", + createdBy: "agent", + creationSource: "mcp", + }); + const task = (yield* orchestrator.getThreadProjection(stopRaceParentId)).subagents[0]!; + const childThreadId = task.childThreadId!; + + // The parent's own turn ends, so a completion wake would start it again. + yield* terminal( + turns.find((entry) => entry.turn.threadId === stopRaceParentId)!, + "completed", + ); + yield* settle; + const childRun = (yield* orchestrator.getThreadProjection(childThreadId)).runs[0]!; + assert.equal(childRun.status, "running"); + + // The user types a message in the child pane, then presses Stop there. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("child-follow-up"), + threadId: childThreadId, + messageId: MessageId.make("message:child-follow-up"), + text: "Actually, do it this way", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("child-stop"), + threadId: childThreadId, + runId: childRun.id, + holdQueue: true, + }); + yield* settle; + + const child = yield* orchestrator.getThreadProjection(childThreadId); + assert.deepEqual( + child.runs.map((run) => [run.ordinal, run.status, run.queueHeld ?? false]), + [ + [1, "interrupted", false], + [2, "queued", true], + ], + ); + const parent = yield* orchestrator.getThreadProjection(stopRaceParentId); + const wakes = parent.messages.filter( + (message) => message.delegatedCompletion?.taskIds.includes(task.id) === true, + ); + // The user's message still waits to run in the child's checkout, so the task has not ended. + assert.deepEqual( + wakes.map((message) => message.text), + [], + ); + assert.notInclude( + ["completed", "failed", "cancelled", "interrupted"], + parent.subagents.find((row) => row.id === task.id)?.status, + ); + + // Discarding the held message leaves the stopped run as the task's result. + yield* orchestrator.dispatch({ + type: "queued-run.cancel", + commandId: CommandId.make("child-discard"), + threadId: childThreadId, + runId: child.runs[1]!.id, + }); + yield* settle; + const settled = yield* orchestrator.getThreadProjection(stopRaceParentId); + assert.equal(settled.subagents.find((row) => row.id === task.id)?.status, "interrupted"); + }).pipe(Effect.provide(layerTest)); + }), +); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 13fc22a0a051c..5b1623f8414ec 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -15108,9 +15108,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const readDelegatedChildControls = Effect.fn("Orchestrator.readDelegatedChildControls")( function* (childThreadId: ThreadId, taskIds: ReadonlyArray) { - const controls: DelegatedChildControls = yield* projectionStore.getDelegatedChildControls( - childThreadId, - { taskIds, windowSize: DELEGATED_CHILD_RUN_WINDOW }, + // Progress tells a held wake from a held message the user wrote by the run's message. + const withHeldMessages = Effect.fn("Orchestrator.readHeldRunMessages")(function* < + A extends Omit, + >(read: A) { + const heldRunIds = read.runs.flatMap((run) => + run.status === "queued" && run.queueHeld === true ? [run.id] : [], + ); + if (heldRunIds.length === 0) return read; + const { messages } = yield* projectionStore.getThreadRecords(childThreadId, ["messages"], { + messageRoles: ["user"], + messageRunIds: heldRunIds, + }); + return { ...read, messages: [...read.messages, ...messages] }; + }); + const controls: DelegatedChildControls = yield* withHeldMessages( + yield* projectionStore.getDelegatedChildControls(childThreadId, { + taskIds, + windowSize: DELEGATED_CHILD_RUN_WINDOW, + }), ); const progress = delegatedTaskProgress(controls); // The latest result may have ended before the runs read above; then read them all. @@ -15118,7 +15134,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio controls.runsFloor !== undefined && (progress.resultRun === undefined || !ranSince(progress.resultRun, controls.runsFloor)) ) { - const all = yield* readAllDelegatedChildControls(childThreadId); + const all = yield* withHeldMessages(yield* readAllDelegatedChildControls(childThreadId)); return { controls: all, progress: delegatedTaskProgress(all) }; } return { controls, progress }; @@ -15500,12 +15516,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio childThreadId, openTasks.map((task) => task.id), ); + const cancelAwaitsWork = progress.state === "working" && !progress.onlyAwaitsUserRun; for (const task of openTasks) { // A cancelled task does not wait for the work its cancel is stopping. const cancelled = task.cancelledRunId !== undefined; if ( task.id === forkedFrom.nodeId && - (cancelled ? progress.state === "working" : progress.state !== "result_available") + (cancelled ? cancelAwaitsWork : progress.state !== "result_available") ) continue; yield* finalizeAppOwnedSubagentTask(childControls, { @@ -15524,7 +15541,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio resultTask?.cancelledRunId !== undefined && resultTask.cancelledRunId === resultRun?.id; if ( resultRun === undefined || - (taskCancelled ? progress.state === "working" : progress.state !== "result_available") + (taskCancelled ? cancelAwaitsWork : progress.state !== "result_available") ) return; const status = delegatedTaskTerminalStatus(runOutcome(resultRun)); diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index d1638b8022029..df5ea84c4b440 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -395,7 +395,7 @@ export function subagentHoldsCompletion( export function delegatedTaskProgress(projection: { readonly runs: OrchestrationV2ThreadProjection["runs"]; readonly messages: ReadonlyArray< - Pick + Pick >; readonly subagents: ReadonlyArray< Pick @@ -410,9 +410,17 @@ export function delegatedTaskProgress(projection: { const workRuns = projection.runs.filter( (run) => !monitorRuns.has(run.id) && run.status !== "rolled_back", ); - const active = workRuns.some( - (run) => !terminal(run.status) && !(run.status === "queued" && run.queueHeld === true), + const held = (run: OrchestrationV2Run) => run.status === "queued" && run.queueHeld === true; + const active = workRuns.some((run) => !terminal(run.status) && !held(run)); + // Held wakes wait on nobody, but a held message the user wrote is the child's next work. + const userRunIds = new Set( + projection.messages.flatMap((message) => + message.createdBy === "user" && message.notification === undefined && message.runId !== null + ? [message.runId] + : [], + ), ); + const awaitsUserRun = workRuns.some((run) => held(run) && userRunIds.has(run.id)); const children = projection.subagents.some(subagentHoldsCompletion) || projection.providerThreads.some((thread) => @@ -423,12 +431,14 @@ export function delegatedTaskProgress(projection: { .toSorted((a, b) => (runRanAfter(a, b) ? -1 : runRanAfter(b, a) ? 1 : 0))[0]; return { state: - active || resultRun === undefined + active || awaitsUserRun || resultRun === undefined ? ("working" as const) : children ? ("waiting_for_children" as const) : ("result_available" as const), resultRun, + /** Working only because of a held message the user wrote, which a cancel does not wait for. */ + onlyAwaitsUserRun: awaitsUserRun && !active && resultRun !== undefined, }; } From e414cfd4bee392e95609a4d31fcbbd3228949849 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 17:50:18 -0800 Subject: [PATCH 138/162] feat(server): durable workflows (#38882) Co-authored-by: Claude Fable 5.2 --- apps/server/src/auth/RpcAuthorization.ts | 4 + apps/server/src/binCli.ts | 2 + apps/server/src/cli/thread.ts | 20 +- apps/server/src/cli/workflow.test.ts | 186 ++ apps/server/src/cli/workflow.ts | 408 +++ apps/server/src/config.ts | 3 + apps/server/src/feedback/FeedbackReport.ts | 13 + apps/server/src/mcp/McpHttpServer.ts | 10 +- .../src/mcp/toolkits/project/handlers.ts | 4 + apps/server/src/mcp/toolkits/project/tools.ts | 3 + .../src/mcp/toolkits/workflow/handlers.ts | 98 + .../server/src/mcp/toolkits/workflow/tools.ts | 69 + .../src/milestones/MilestoneEvents.test.ts | 12 +- apps/server/src/milestones/MilestoneEvents.ts | 117 +- .../src/milestones/MilestoneHub.test.ts | 30 +- .../OrchestrationMilestones.test.ts | 43 + .../src/milestones/OrchestrationMilestones.ts | 1 + .../src/observability/RpcInstrumentation.ts | 9 + .../src/orchestration-v2/Orchestrator.ts | 2 + .../src/orchestration-v2/ProjectionStore.ts | 13 +- .../src/orchestration-v2/ThreadForkService.ts | 7 +- .../ThreadLaunchService.test.ts | 17 +- .../orchestration-v2/ThreadLaunchService.ts | 4 + .../ThreadManagementService.test.ts | 115 + .../ThreadManagementService.ts | 47 +- apps/server/src/orchestration-v2/runOutput.ts | 6 + .../src/orchestration-v2/runtimeLayer.test.ts | 146 +- .../src/orchestration-v2/runtimeLayer.ts | 16 + .../testkit/ProviderReplayHarness.ts | 1 + apps/server/src/persistence/Migrations.ts | 2 + .../persistence/Migrations/110_Workflows.ts | 149 + .../reconcileV2PreviewMigration.test.ts | 2 + .../src/provider/AgentContextBudget.test.ts | 2 + .../src/provider/agentContextBudget.json | 2 +- apps/server/src/scheduledTasks/Schedule.ts | 2 +- .../src/scheduledTasks/webhookRoute.test.ts | 36 + .../server/src/scheduledTasks/webhookRoute.ts | 38 + apps/server/src/server.ts | 12 +- .../src/workflows/WorkflowAgentLinks.test.ts | 292 ++ .../src/workflows/WorkflowAgentLinks.ts | 313 +++ .../src/workflows/WorkflowAgentThreads.ts | 335 +++ apps/server/src/workflows/WorkflowAgents.ts | 117 + apps/server/src/workflows/WorkflowEngine.ts | 1056 +++++++ .../src/workflows/WorkflowForge.test.ts | 113 + apps/server/src/workflows/WorkflowForge.ts | 455 ++++ .../src/workflows/WorkflowRuntime.test.ts | 464 ++++ apps/server/src/workflows/WorkflowRuntime.ts | 978 +++++++ .../src/workflows/WorkflowStore.test.ts | 424 +++ apps/server/src/workflows/WorkflowStore.ts | 1142 ++++++++ apps/server/src/workflows/Workflows.test.ts | 2424 +++++++++++++++++ apps/server/src/workflows/Workflows.ts | 221 ++ apps/server/src/workflows/api.ts | 15 + apps/server/src/workflows/forgeApi.ts | 109 + apps/server/src/workflows/options.ts | 28 + apps/server/src/workflows/runReferences.ts | 90 + apps/server/src/workflows/stepServices.ts | 458 ++++ apps/server/src/workflows/triggers.ts | 156 ++ apps/server/src/workflows/workflow.ts | 897 ++++++ apps/server/src/workflows/workflowAgent.ts | 442 +++ apps/server/src/ws.test.ts | 165 ++ apps/server/src/ws.ts | 27 + docs/internals/workflows.md | 178 ++ .../orchestrator-mcp-server.md | 7 + docs/user/managed-policy.md | 1 + docs/user/outside-agents.md | 6 +- evals/README.md | 15 +- evals/package.json | 1 + evals/workflow-authoring/README.md | 36 + evals/workflow-authoring/cases.ts | 270 ++ .../workflow-authoring/fixtures/globals.d.ts | 11 + .../fixtures/replay-keeps-in-a-module.ts | 19 + .../fixtures/replay-keeps-what-it-read.ts | 20 + .../fixtures/replay-reads-outside-a-step.ts | 17 + .../fixtures/scheduled-agent-then-approval.ts | 34 + .../fixtures/webhook-filter-and-dedupe.ts | 22 + evals/workflow-authoring/grade.ts | 159 ++ evals/workflow-authoring/run.test.ts | 37 + evals/workflow-authoring/run.ts | 179 ++ knip.jsonc | 4 + .../contracts/src/clientRpcPermissions.ts | 7 + packages/contracts/src/index.ts | 1 + packages/contracts/src/milestones.ts | 70 +- packages/contracts/src/orchestrationV2.ts | 27 +- packages/contracts/src/rpc.ts | 88 + packages/contracts/src/settings.ts | 3 + packages/contracts/src/workflow.ts | 223 ++ packages/shared/src/nodeSqliteClient.test.ts | 17 + packages/shared/src/nodeSqliteClient.ts | 6 + packages/shared/src/t3McpToolPresentation.ts | 1 + skills/t3-workflows/SKILL.md | 353 +++ 90 files changed, 14092 insertions(+), 92 deletions(-) create mode 100644 apps/server/src/cli/workflow.test.ts create mode 100644 apps/server/src/cli/workflow.ts create mode 100644 apps/server/src/mcp/toolkits/workflow/handlers.ts create mode 100644 apps/server/src/mcp/toolkits/workflow/tools.ts create mode 100644 apps/server/src/persistence/Migrations/110_Workflows.ts create mode 100644 apps/server/src/workflows/WorkflowAgentLinks.test.ts create mode 100644 apps/server/src/workflows/WorkflowAgentLinks.ts create mode 100644 apps/server/src/workflows/WorkflowAgentThreads.ts create mode 100644 apps/server/src/workflows/WorkflowAgents.ts create mode 100644 apps/server/src/workflows/WorkflowEngine.ts create mode 100644 apps/server/src/workflows/WorkflowForge.test.ts create mode 100644 apps/server/src/workflows/WorkflowForge.ts create mode 100644 apps/server/src/workflows/WorkflowRuntime.test.ts create mode 100644 apps/server/src/workflows/WorkflowRuntime.ts create mode 100644 apps/server/src/workflows/WorkflowStore.test.ts create mode 100644 apps/server/src/workflows/WorkflowStore.ts create mode 100644 apps/server/src/workflows/Workflows.test.ts create mode 100644 apps/server/src/workflows/Workflows.ts create mode 100644 apps/server/src/workflows/api.ts create mode 100644 apps/server/src/workflows/forgeApi.ts create mode 100644 apps/server/src/workflows/options.ts create mode 100644 apps/server/src/workflows/runReferences.ts create mode 100644 apps/server/src/workflows/stepServices.ts create mode 100644 apps/server/src/workflows/triggers.ts create mode 100644 apps/server/src/workflows/workflow.ts create mode 100644 apps/server/src/workflows/workflowAgent.ts create mode 100644 docs/internals/workflows.md create mode 100644 evals/workflow-authoring/README.md create mode 100644 evals/workflow-authoring/cases.ts create mode 100644 evals/workflow-authoring/fixtures/globals.d.ts create mode 100644 evals/workflow-authoring/fixtures/replay-keeps-in-a-module.ts create mode 100644 evals/workflow-authoring/fixtures/replay-keeps-what-it-read.ts create mode 100644 evals/workflow-authoring/fixtures/replay-reads-outside-a-step.ts create mode 100644 evals/workflow-authoring/fixtures/scheduled-agent-then-approval.ts create mode 100644 evals/workflow-authoring/fixtures/webhook-filter-and-dedupe.ts create mode 100644 evals/workflow-authoring/grade.ts create mode 100644 evals/workflow-authoring/run.test.ts create mode 100644 evals/workflow-authoring/run.ts create mode 100644 packages/contracts/src/workflow.ts create mode 100644 skills/t3-workflows/SKILL.md diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 2cab3d32f1235..b276fafb2723a 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -129,6 +129,10 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.serverSignalProcess]: AuthEnvironmentMaintainScope, [WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope, [WS_METHODS.scheduledTasksSubscribe]: AuthOrchestrationReadScope, + [WS_METHODS.workflowsSubscribe]: AuthOrchestrationReadScope, + [WS_METHODS.workflowsCounts]: AuthOrchestrationReadScope, + [WS_METHODS.workflowsGet]: AuthOrchestrationReadScope, + [WS_METHODS.workflowsGetDefinition]: AuthFilesystemReadScope, [WS_METHODS.secretsAnswerRequest]: AuthOrchestrationOperateScope, [WS_METHODS.agentFeedbackAnswerRequest]: AuthOrchestrationOperateScope, // Delivery logs hold request bodies, so they need the same scope as the URL. diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts index 677336175d723..2ae78f272cd6b 100644 --- a/apps/server/src/binCli.ts +++ b/apps/server/src/binCli.ts @@ -22,6 +22,7 @@ import { sharedServerCommandFlags } from "./cli/config.ts"; import { projectCommand } from "./cli/project.ts"; import { feedbackCommand } from "./cli/feedback.ts"; import { threadCommand } from "./cli/thread.ts"; +import { workflowCommand } from "./cli/workflow.ts"; import { runDefaultServerCommand, serveCommand, startCommand } from "./cli/server.ts"; import { updateCommand } from "./cli/update.ts"; import { @@ -93,6 +94,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) => projectCommand, threadCommand, feedbackCommand, + workflowCommand, upCommand, statusCommand, serviceCommand, diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index bd40b51c8ce4d..1d81dcc6bd7cb 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -197,6 +197,15 @@ const toolFailureDetail = (result: typeof ToolResult.Type) => { }); }; +/** JSON-RPC's invalid params: the arguments failed the tool's schema. */ +const INVALID_PARAMS = -32602; +const rpcErrorDetail = (error: { readonly code: number; readonly message: string }) => { + const message = error.message.replaceAll(/\s*\n\s*/g, " "); + return error.code === INVALID_PARAMS + ? `The server refused the arguments: ${message}` + : `The server refused the request: ${message}`; +}; + const makeThreadTools = (session: McpToolSession, origin: string) => { const unexpected = (tool: string) => new ThreadToolFailedError({ @@ -214,10 +223,13 @@ const makeThreadTools = (session: McpToolSession, origin: string) => { > { const raw = yield* session.call(tool, args).pipe( Effect.mapError((cause) => - // Effect's MCP server words an unknown or hidden tool exactly this way. - cause.rpcError?.code === -32602 && cause.rpcError.message === `Tool '${tool}' not found` - ? new ThreadToolMissingError({ tool }) - : new ThreadServerUnreachableError({ origin, cause }), + cause.rpcError === undefined + ? new ThreadServerUnreachableError({ origin, cause }) + : // Effect's MCP server words an unknown or hidden tool exactly this way. + cause.rpcError.code === -32602 && + cause.rpcError.message === `Tool '${tool}' not found` + ? new ThreadToolMissingError({ tool }) + : new ThreadToolFailedError({ tool, detail: rpcErrorDetail(cause.rpcError) }), ), ); const result = yield* decodeToolResult(raw).pipe(Effect.mapError(() => unexpected(tool))); diff --git a/apps/server/src/cli/workflow.test.ts b/apps/server/src/cli/workflow.test.ts new file mode 100644 index 0000000000000..0c99ca8ee8d21 --- /dev/null +++ b/apps/server/src/cli/workflow.test.ts @@ -0,0 +1,186 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import { AuthSessionId, type WorkflowRun } from "@t3tools/contracts"; +import * as NetService from "@t3tools/shared/Net"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as TestConsole from "effect/testing/TestConsole"; +import { Command } from "effect/cli"; +import { vi } from "vite-plus/test"; + +import * as McpBridge from "../mcp/AcpMcpStdioBridge.ts"; +import { + makePersistedServerRuntimeState, + persistServerRuntimeState, +} from "../serverRuntimeState.ts"; +import { workflowCommand } from "./workflow.ts"; + +vi.mock("../auth/EnvironmentAuth.ts", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + layerRuntime: Layer.mock(actual.EnvironmentAuth)({ + issueMcpClientSession: () => + Effect.map(DateTime.now, (expiresAt) => ({ + sessionId: AuthSessionId.make("test-session"), + token: "synthetic-token", + expiresAt, + })), + revokeSession: () => Effect.succeed(true), + }), + }; +}); + +const makeRun = (status: WorkflowRun["status"]): WorkflowRun => ({ + runId: "run-1", + workflow: "review", + version: 1, + title: "review pr-1", + status, + detail: null, + result: null, + pauses: 0, + retired: false, + resumesAt: null, + parentRunId: null, + parentStep: null, + startedAt: "2026-11-20T00:00:00.000Z", + updatedAt: "2026-11-20T00:00:00.000Z", + endedAt: ["running", "waiting", "paused"].includes(status) ? null : "2026-11-20T00:00:00.000Z", +}); + +/** Runs `t3 workflow ` against a live-looking server whose t3_workflow is `call`. */ +const runCli = ( + args: ReadonlyArray, + call: McpBridge.McpToolSession["call"] = () => Effect.die("no tool call expected"), +) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-workflow-cli-" }); + yield* persistServerRuntimeState({ + path: path.join(baseDir, "userdata", "server-runtime.json"), + state: yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3_773, + }), + }); + const calls: Array>> = []; + using _session = vi.spyOn(McpBridge, "mcpToolSession").mockReturnValue( + Effect.succeed({ + call: (tool, input) => { + calls.push(input); + return call(tool, input); + }, + }), + ); + const error = yield* Command.runWith(workflowCommand, { version: "0.0.0" })([ + ...args, + "--base-dir", + baseDir, + ]).pipe( + Effect.flip, + Effect.orElseSucceed(() => undefined), + ); + return { error, calls, errors: yield* TestConsole.errorLines }; + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + NetService.layer, + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })), + ), + ), + ); + +/** Answers each action with the run in `status`, as the server does. */ +const serving = + (status: WorkflowRun["status"]): McpBridge.McpToolSession["call"] => + () => + Effect.succeed({ structuredContent: { run: makeRun(status), steps: [] } }); + +it.effect("cancel sends --reason, and steers nothing when the run cannot take it", () => + Effect.gen(function* () { + const cancelled = yield* runCli( + ["cancel", "run-1", "--reason", "superseded"], + serving("running"), + ); + assert.deepStrictEqual(cancelled.calls.at(-1), { + action: "cancel", + runId: "run-1", + reason: "superseded", + }); + + for (const [command, status, said] of [ + ["cancel", "completed", "Run run-1 is completed; nothing to cancel."], + ["resume", "waiting", "Run run-1 is waiting; nothing to resume."], + ["resume", "cancelled", "Run run-1 is cancelled; nothing to resume."], + ] as const) { + const { error, calls, errors } = yield* runCli([command, "run-1"], serving(status)); + assert.isUndefined(error, command); + assert.deepStrictEqual( + calls.map((input) => input.action), + ["read"], + ); + assert.include(errors, said); + } + }), +); + +it.effect("reports what the server refused instead of calling it unreachable", () => + Effect.gen(function* () { + // A blank key is refused here, before the server is asked. + const blank = yield* runCli(["start", "review", "--key", " "], () => + Effect.die("the server is not asked"), + ); + assert.strictEqual(blank.error?.message, "--key cannot be blank."); + + const refused = yield* runCli(["start", "review", "--key", "r1"], () => + Effect.fail( + new McpBridge.AcpMcpBridgeError({ + message: "T3 Code MCP tools/call failed.", + rpcError: { + code: -32602, + message: 'Expected a non-blank string\n at ["idempotencyKey"]', + }, + }), + ), + ); + assert.strictEqual(refused.error?._tag, "ThreadToolFailedError"); + assert.strictEqual( + refused.error?.message, + 'The server refused the arguments: Expected a non-blank string at ["idempotencyKey"]', + ); + + const unreachable = yield* runCli(["start", "review", "--key", "pr-1"], () => + Effect.fail(new McpBridge.AcpMcpBridgeError({ message: "fetch failed" })), + ); + assert.strictEqual(unreachable.error?._tag, "ThreadServerUnreachableError"); + }), +); + +it.effect("signal refuses both addresses at once before reaching the server", () => + Effect.gen(function* () { + const { error, calls } = yield* runCli([ + "signal", + "{}", + "--run", + "run-1", + "--wait", + "approve", + "--workflow", + "review", + "--channel", + "pr-1", + ]); + assert.strictEqual(error?._tag, "ThreadUsageError"); + assert.lengthOf(calls, 0); + }), +); diff --git a/apps/server/src/cli/workflow.ts b/apps/server/src/cli/workflow.ts new file mode 100644 index 0000000000000..95a499043c6c6 --- /dev/null +++ b/apps/server/src/cli/workflow.ts @@ -0,0 +1,408 @@ +import { WorkflowHook, WorkflowRunStatus } from "@t3tools/contracts"; +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { Argument, Command, Flag } from "effect/cli"; + +import * as Workflows from "../workflows/Workflows.ts"; +import { WorkflowRun, WorkflowStep } from "../workflows/WorkflowStore.ts"; +import { projectLocationFlags } from "./config.ts"; +import { + jsonFlag, + printJson, + reportThreadErrors, + type ThreadTools, + ThreadUsageError, + withThreadTools, +} from "./thread.ts"; + +const RunResult = Schema.Struct({ run: WorkflowRun, steps: Schema.Array(WorkflowStep) }); +const RunsResult = Schema.Struct({ runs: Schema.Array(WorkflowRun) }); +const QuestionsResult = Schema.Struct({ questions: Schema.Array(Workflows.WorkflowQuestion) }); +const HooksResult = Schema.Struct({ hooks: Schema.Array(WorkflowHook) }); +const SignalResult = Schema.Struct({ delivery: Schema.Literals(["delivered", "buffered"]) }); + +const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Json)); +const jsonArgument = (text: string, what: string) => + decodeJson(text).pipe( + Effect.mapError(() => new ThreadUsageError({ detail: `${what} is not valid JSON.` })), + ); + +const runLine = (run: WorkflowRun) => + [run.runId, run.status.padEnd(9), run.workflow, run.title, run.detail ?? ""].join(" ").trimEnd(); + +const printRun = Effect.fn("cli.workflow.printRun")(function* ( + result: typeof RunResult.Type, + json: boolean, +) { + if (json) return yield* printJson(result); + yield* Console.log(runLine(result.run)); + for (const step of result.steps) { + yield* Console.log( + ` ${step.status.padEnd(9)} ${step.kind.padEnd(5)} ${step.name}${ + step.attempts > 1 ? ` (${step.attempts} tries)` : "" + }${step.environmentId === null ? "" : ` in ${step.environmentId}`}${ + step.detail === null ? "" : ` ${step.detail}` + }`, + ); + } + if (result.run.result !== null) yield* printJson(result.run.result); +}); + +const runArgument = Argument.String("run").pipe(Argument.withDescription("Run id.")); +const readRun = (tools: ThreadTools, runId: string) => + tools.call("t3_workflow", { action: "read", runId }, RunResult); + +const startCommand = Command.make("start", { + ...projectLocationFlags, + workflow: Argument.String("workflow").pipe(Argument.withDescription("Workflow name.")), + input: Flag.String("input").pipe( + Flag.withDescription("The run's payload, as JSON. Defaults to {}."), + Flag.withDefault("{}"), + ), + key: Flag.String("key").pipe( + Flag.withDescription( + "Required. Names this run: starting again with the same key is the same run, not a second one.", + ), + ), + json: jsonFlag, +}).pipe( + Command.withDescription("Start a workflow run and print it."), + Command.withHandler((flags) => + Effect.gen(function* () { + const input = yield* jsonArgument(flags.input, "--input"); + if (flags.key.trim() === "") { + return yield* new ThreadUsageError({ detail: "--key cannot be blank." }); + } + yield* withThreadTools( + flags, + Effect.fn("cli.workflow.start")(function* (tools) { + const started = yield* tools.call( + "t3_workflow", + { action: "start", workflow: flags.workflow, input, idempotencyKey: flags.key }, + RunResult, + ); + yield* printRun(started, flags.json); + }), + ); + }).pipe(reportThreadErrors), + ), +); + +const listCommand = Command.make("list", { + ...projectLocationFlags, + status: Flag.Literals("status", WorkflowRunStatus.literals).pipe( + Flag.withDescription( + "Only runs in this state. A skipped run is listed only with `skipped`, unless another run invoked it.", + ), + Flag.optional, + ), + json: jsonFlag, +}).pipe( + Command.withDescription("List workflow runs, newest first."), + Command.withHandler((flags) => + withThreadTools( + flags, + Effect.fn("cli.workflow.list")(function* (tools) { + const { runs } = yield* tools.call( + "t3_workflow", + { + action: "list", + ...(Option.isSome(flags.status) ? { status: flags.status.value } : {}), + }, + RunsResult, + ); + // A workflow skips what was never its to do, and that is most of what a trigger brings. + const listed = Option.isSome(flags.status) + ? runs + : runs.filter((run) => run.status !== "skipped" || run.parentRunId !== null); + if (flags.json) return yield* printJson(listed); + for (const run of listed) yield* Console.log(runLine(run)); + }), + ).pipe(reportThreadErrors), + ), +); + +const showCommand = Command.make("show", { + ...projectLocationFlags, + run: runArgument, + json: jsonFlag, +}).pipe( + Command.withDescription("Show a run and its steps."), + Command.withHandler((flags) => + withThreadTools( + flags, + Effect.fn("cli.workflow.show")(function* (tools) { + yield* printRun(yield* readRun(tools, flags.run), flags.json); + }), + ).pipe(reportThreadErrors), + ), +); + +/** Why `action` would leave the run as it is, or undefined when it would act. */ +const noOpReason = (action: "resume" | "cancel", run: WorkflowRun) => { + if (action === "cancel") { + return run.endedAt === null + ? undefined + : `Run ${run.runId} is ${run.status}; nothing to cancel.`; + } + return run.status === "paused" + ? undefined + : `Run ${run.runId} is ${run.status}; nothing to resume.`; +}; + +const steer = Effect.fn("cli.workflow.steer")(function* ( + tools: ThreadTools, + action: "resume" | "cancel", + flags: { readonly run: string; readonly json: boolean; readonly reason: Option.Option }, +) { + const before = yield* readRun(tools, flags.run); + const skipped = noOpReason(action, before.run); + if (skipped !== undefined) { + // Stderr, so --json output stays the run alone. + yield* Console.error(skipped); + return yield* printRun(before, flags.json); + } + const after = yield* tools.call( + "t3_workflow", + { + action, + runId: flags.run, + ...(Option.isSome(flags.reason) ? { reason: flags.reason.value } : {}), + }, + RunResult, + ); + yield* printRun(after, flags.json); +}); + +const resumeCommand = Command.make("resume", { + ...projectLocationFlags, + run: runArgument, + json: jsonFlag, +}).pipe( + Command.withDescription("Run a paused run's failed step again."), + Command.withHandler((flags) => + withThreadTools(flags, (tools) => + steer(tools, "resume", { ...flags, reason: Option.none() }), + ).pipe(reportThreadErrors), + ), +); + +const cancelCommand = Command.make("cancel", { + ...projectLocationFlags, + run: runArgument, + reason: Flag.String("reason").pipe( + Flag.withDescription("Why, kept as the run's detail."), + Flag.optional, + ), + json: jsonFlag, +}).pipe( + Command.withDescription("Cancel a run."), + Command.withHandler((flags) => + withThreadTools(flags, (tools) => steer(tools, "cancel", flags)).pipe(reportThreadErrors), + ), +); + +const signalCommand = Command.make("signal", { + ...projectLocationFlags, + value: Argument.String("value").pipe( + Argument.withDescription('What the wait receives, as JSON. A question takes {"choice": ...}.'), + ), + run: Flag.String("run").pipe( + Flag.withDescription("Run id. Pass with --wait, not with --workflow and --channel."), + Flag.optional, + ), + wait: Flag.String("wait").pipe( + Flag.withDescription("The wait's or question's name in that run."), + Flag.optional, + ), + workflow: Flag.String("workflow").pipe( + Flag.withDescription("Workflow name. Pass with --channel when the run is not known."), + Flag.optional, + ), + channel: Flag.String("channel").pipe( + Flag.withDescription("The channel the wait opened with."), + Flag.optional, + ), + id: Flag.String("id").pipe( + Flag.withDescription( + "Names this signal: sending it again with the same id is the same signal.", + ), + Flag.optional, + ), +}).pipe( + Command.withDescription("Wake a waiting run, or answer its question."), + Command.withHandler((flags) => + Effect.gen(function* () { + const value = yield* jsonArgument(flags.value, "The value"); + const byRun = Option.isSome(flags.run) || Option.isSome(flags.wait); + const byChannel = Option.isSome(flags.workflow) || Option.isSome(flags.channel); + if (byRun && byChannel) { + return yield* new ThreadUsageError({ + detail: + "Address a signal with --run and --wait, or with --workflow and --channel, not both.", + }); + } + yield* withThreadTools( + { ...flags, json: false }, + Effect.fn("cli.workflow.signal")(function* (tools) { + const { delivery } = yield* tools.call( + "t3_workflow", + { + action: "signal", + value, + ...(Option.isSome(flags.run) ? { runId: flags.run.value } : {}), + ...(Option.isSome(flags.wait) ? { wait: flags.wait.value } : {}), + ...(Option.isSome(flags.workflow) ? { workflow: flags.workflow.value } : {}), + ...(Option.isSome(flags.channel) ? { channel: flags.channel.value } : {}), + ...(Option.isSome(flags.id) ? { signalId: flags.id.value } : {}), + }, + SignalResult, + ); + yield* Console.log( + delivery === "delivered" ? "Delivered." : "Kept until a run waits for it.", + ); + }), + ); + }).pipe(reportThreadErrors), + ), +); + +const questionsCommand = Command.make("questions", { + ...projectLocationFlags, + json: jsonFlag, +}).pipe( + Command.withDescription("List the questions runs are waiting on a person to answer."), + Command.withHandler((flags) => + withThreadTools( + flags, + Effect.fn("cli.workflow.questions")(function* (tools) { + const { questions } = yield* tools.call( + "t3_workflow", + { action: "questions" }, + QuestionsResult, + ); + if (flags.json) return yield* printJson(questions); + for (const question of questions) { + yield* Console.log(`${question.runId} ${question.name}`); + yield* printJson(question.request); + } + }), + ).pipe(reportThreadErrors), + ), +); + +const hooksCommand = Command.make("hooks", { + ...projectLocationFlags, + json: jsonFlag, +}).pipe( + Command.withDescription( + "List the URL paths that start runs. Each holds its hook's secret; add the server's origin.", + ), + Command.withHandler((flags) => + withThreadTools( + flags, + Effect.fn("cli.workflow.hooks")(function* (tools) { + const { hooks } = yield* tools.call("t3_workflow", { action: "hooks" }, HooksResult); + if (flags.json) return yield* printJson(hooks); + for (const hook of hooks) { + yield* Console.log(`${hook.workflow} ${hook.name} ${hook.path}`); + } + }), + ).pipe(reportThreadErrors), + ), +); + +const StoreResult = Schema.Struct({ + entries: Schema.Array(Schema.Struct({ key: Schema.String, value: Schema.Json })), +}); +const keyArgument = Argument.String("key").pipe(Argument.withDescription("The key in the store.")); + +const storeListCommand = Command.make("list", { + ...projectLocationFlags, + prefix: Argument.String("prefix").pipe( + Argument.withDescription("Only keys that start with this."), + Argument.withDefault(""), + ), + json: jsonFlag, +}).pipe( + Command.withDescription("List what workflows keep in the store."), + Command.withHandler((flags) => + withThreadTools( + flags, + Effect.fn("cli.workflow.store.list")(function* (tools) { + const { entries } = yield* tools.call( + "t3_workflow", + { action: "store", ...(flags.prefix === "" ? {} : { key: flags.prefix }) }, + StoreResult, + ); + if (flags.json) return yield* printJson(entries); + for (const entry of entries) { + yield* Console.log(entry.key); + yield* printJson(entry.value); + } + }), + ).pipe(reportThreadErrors), + ), +); + +const storeSetCommand = Command.make("set", { + ...projectLocationFlags, + key: keyArgument, + value: Argument.String("value").pipe(Argument.withDescription("The value, as JSON.")), +}).pipe( + Command.withDescription("Set a key of the store, as a person flipping a switch does."), + Command.withHandler((flags) => + Effect.gen(function* () { + const value = yield* jsonArgument(flags.value, "The value"); + yield* withThreadTools( + { ...flags, json: false }, + Effect.fn("cli.workflow.store.set")(function* (tools) { + yield* tools.call( + "t3_workflow", + { action: "store_set", key: flags.key, value }, + StoreResult, + ); + yield* Console.log(`Set ${flags.key}.`); + }), + ); + }).pipe(reportThreadErrors), + ), +); + +const storeDeleteCommand = Command.make("delete", { + ...projectLocationFlags, + key: keyArgument, +}).pipe( + Command.withDescription("Delete a key of the store."), + Command.withHandler((flags) => + withThreadTools( + { ...flags, json: false }, + Effect.fn("cli.workflow.store.delete")(function* (tools) { + yield* tools.call("t3_workflow", { action: "store_delete", key: flags.key }, StoreResult); + yield* Console.log(`Deleted ${flags.key}.`); + }), + ).pipe(reportThreadErrors), + ), +); + +const storeCommand = Command.make("store").pipe( + Command.withDescription("See and change what workflows keep between runs."), + Command.withSubcommands([storeListCommand, storeSetCommand, storeDeleteCommand]), +); + +export const workflowCommand = Command.make("workflow").pipe( + Command.withDescription("Start, inspect and steer durable workflow runs on the running server."), + Command.withSubcommands([ + startCommand, + listCommand, + showCommand, + resumeCommand, + cancelCommand, + signalCommand, + questionsCommand, + hooksCommand, + storeCommand, + ]), +); diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index c707c912d672d..9076aadd47381 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -43,6 +43,8 @@ export interface ServerDerivedPaths { readonly environmentThemesDir: string; readonly providerStatusCacheDir: string; readonly worktreesDir: string; + /** Where workflow definition files live. In the home itself: they are the user's own code. */ + readonly workflowsDir: string; readonly worktreeCheckoutCacheDir: string; readonly attachmentsDir: string; readonly browserArtifactsDir: string; @@ -161,6 +163,7 @@ export const deriveServerPaths = Effect.fn(function* ( environmentThemesDir: join(stateDir, "themes"), providerStatusCacheDir, worktreesDir: join(baseDir, "worktrees"), + workflowsDir: join(baseDir, "workflows"), worktreeCheckoutCacheDir: join(providerStatusCacheDir, "worktree-checkouts"), attachmentsDir, browserArtifactsDir: join(stateDir, "browser-artifacts"), diff --git a/apps/server/src/feedback/FeedbackReport.ts b/apps/server/src/feedback/FeedbackReport.ts index ad1fe305ba6db..f7c026700b0e8 100644 --- a/apps/server/src/feedback/FeedbackReport.ts +++ b/apps/server/src/feedback/FeedbackReport.ts @@ -160,6 +160,19 @@ export const T3_CLI_COMMANDS: ReadonlyArray = [ "t3 thread show", "t3 feedback", "t3 feedback list", + "t3 workflow", + "t3 workflow start", + "t3 workflow list", + "t3 workflow show", + "t3 workflow resume", + "t3 workflow cancel", + "t3 workflow signal", + "t3 workflow questions", + "t3 workflow hooks", + "t3 workflow store", + "t3 workflow store list", + "t3 workflow store set", + "t3 workflow store delete", "t3 up", "t3 status", "t3 service", diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index ff55a2ea5459c..5bf97d42a2461 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -71,6 +71,8 @@ import * as ProjectHandlers from "./toolkits/project/handlers.ts"; import { AttachmentToolkit } from "./toolkits/attachment/tools.ts"; import * as AttachmentHandlers from "./toolkits/attachment/handlers.ts"; import { ThreadToolkit } from "./toolkits/thread/tools.ts"; +import { WorkflowToolkit } from "./toolkits/workflow/tools.ts"; +import * as WorkflowHandlers from "./toolkits/workflow/handlers.ts"; import * as ThreadHandlers from "./toolkits/thread/handlers.ts"; import * as ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts"; import * as McpSessionRegistry from "./McpSessionRegistry.ts"; @@ -1336,6 +1338,7 @@ export const layerOrchestratorToolkit = toolkitRegistration( ).pipe(Layer.provide(OrchestratorMcpService.layer), Layer.provide(ThreadMetadataMcpService.layer)); export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer); +const layerWorkflowToolkit = toolkitRegistration(WorkflowToolkit, WorkflowHandlers.layer); const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); @@ -1432,6 +1435,7 @@ export const layerTools = Layer.mergeAll( layerPreviewToolkit, layerOrchestratorToolkit, layerThreadToolkit, + layerWorkflowToolkit, layerAttachmentToolkit, layerProjectRegistration, layerFeedbackToolkit, @@ -1501,7 +1505,11 @@ export const layerToolSearch = Layer.mergeAll( export const layerMilestoneEvents = Layer.effectDiscard( Effect.gen(function* () { const annotations = Context.make(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromThreads); - for (const options of yield* MilestoneEvents.make) { + const events = yield* MilestoneEvents.make; + for (const options of events.threads) { + yield* McpServer.registerEvent({ ...options, annotations }); + } + for (const options of events.workflows) { yield* McpServer.registerEvent({ ...options, annotations }); } }), diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 76f53b43bdfdc..511dcfe26c3df 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -459,6 +459,10 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { ...(linkOrigin === undefined ? {} : { linkOrigin }), // Kept only alongside linkOrigin: thread.create drops it otherwise. ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }), + // A link's word for it, like `delegatedFrom`: nothing else may name a run. + ...(linkOrigin === undefined || input.workflowRun === undefined + ? {} + : { workflowRun: input.workflowRun }), }).pipe( Effect.mapError((error) => { if (error._tag === "AttachmentClaimError") { diff --git a/apps/server/src/mcp/toolkits/project/tools.ts b/apps/server/src/mcp/toolkits/project/tools.ts index 52e9b77ab3df2..4aff1e4385c8d 100644 --- a/apps/server/src/mcp/toolkits/project/tools.ts +++ b/apps/server/src/mcp/toolkits/project/tools.ts @@ -7,6 +7,7 @@ import { ThreadId, RunId, OrchestrationV2DelegatedFrom, + OrchestrationV2WorkflowOrigin, OrchestrationV2RunStatus, OrchestrationV2ThreadLaunchWorkspaceStrategy, RuntimeMode, @@ -165,6 +166,8 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", { clientRequestId: Schema.optional(OrchestratorMcpClientRequestId), /** Set by a linked environment launching its agent's delegated task here; ignored otherwise. */ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), + /** Set by a linked environment whose workflow run this thread is a step of; ignored otherwise. */ + workflowRun: Schema.optional(OrchestrationV2WorkflowOrigin), }), success: Schema.Struct({ threadId: ThreadId, diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts new file mode 100644 index 0000000000000..fe19b06108480 --- /dev/null +++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts @@ -0,0 +1,98 @@ +import { OrchestratorMcpFailure } from "@t3tools/contracts"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; + +import * as Workflows from "../../../workflows/Workflows.ts"; +import * as McpToolAccess from "../../McpToolAccess.ts"; +import { WORKFLOW_READ_ACTIONS, WorkflowToolkit } from "./tools.ts"; + +const invalid = (message: string) => + new OrchestratorMcpFailure({ code: "invalid_request", message }); +const required = (value: A | undefined, name: string) => + value === undefined + ? Effect.fail(invalid(`This action needs \`${name}\`.`)) + : Effect.succeed(value); +const refused = (error: Workflows.WorkflowError) => invalid(error.message); +const isRead = (action: string): action is (typeof WORKFLOW_READ_ACTIONS)[number] => + (WORKFLOW_READ_ACTIONS as ReadonlyArray).includes(action); + +export const layer = McpToolAccess.toLayer(WorkflowToolkit, { + t3_workflow: McpToolAccess.either( + (input) => isRead(input.action), + McpToolAccess.reads((input) => + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + if (input.action === "questions") { + return { questions: yield* workflows.questions.pipe(Effect.mapError(refused)) }; + } + if (input.action === "store") { + return { + entries: yield* workflows.stored(input.key ?? "").pipe(Effect.mapError(refused)), + }; + } + if (input.action === "list") { + return { + runs: yield* workflows + .list(input.status === undefined ? {} : { status: input.status }) + .pipe(Effect.mapError(refused)), + }; + } + const runId = yield* required(input.runId, "runId"); + return yield* workflows.get(runId).pipe(Effect.mapError(refused)); + }), + ), + McpToolAccess.writes((input) => + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // A hook's path holds its secret, and posting to it starts a run. + if (input.action === "hooks") { + return { hooks: yield* workflows.hooks.pipe(Effect.mapError(refused)) }; + } + if (input.action === "start") { + const name = yield* required(input.workflow, "workflow"); + const idempotencyKey = yield* required(input.idempotencyKey, "idempotencyKey"); + const { runId } = yield* workflows + .start(name, input.input ?? {}, { idempotencyKey }) + .pipe(Effect.mapError(refused)); + return yield* workflows.get(runId).pipe(Effect.mapError(refused)); + } + if (input.action === "signal") { + const value = yield* required(input.value, "value"); + const address = + input.runId !== undefined && input.wait !== undefined + ? { runId: input.runId, wait: input.wait } + : input.workflow !== undefined && input.channel !== undefined + ? { workflow: input.workflow, channel: input.channel } + : undefined; + if (address === undefined) { + return yield* invalid( + "Address a signal with `runId` and `wait`, or `workflow` and `channel`.", + ); + } + const random = yield* SecureRandom.SecureRandom; + const id = input.signalId ?? (yield* random.uuidV4()); + const delivery = yield* workflows + .signal(address, value, { id }) + .pipe(Effect.mapError(refused)); + return { delivery }; + } + if (input.action === "store_set" || input.action === "store_delete") { + const key = yield* required(input.key, "key"); + const value = + input.action === "store_set" ? yield* required(input.value, "value") : undefined; + yield* ( + value === undefined ? workflows.storeDelete(key) : workflows.storeSet(key, value) + ).pipe(Effect.mapError(refused)); + return { entries: yield* workflows.stored(key).pipe(Effect.mapError(refused)) }; + } + const runId = yield* required(input.runId, "runId"); + yield* ( + input.action === "resume" + ? workflows.resume(runId) + : workflows.cancel(runId, input.reason) + ).pipe(Effect.mapError(refused)); + return yield* workflows.get(runId).pipe(Effect.mapError(refused)); + }), + ), + ), +}); diff --git a/apps/server/src/mcp/toolkits/workflow/tools.ts b/apps/server/src/mcp/toolkits/workflow/tools.ts new file mode 100644 index 0000000000000..fa01dfb7c5712 --- /dev/null +++ b/apps/server/src/mcp/toolkits/workflow/tools.ts @@ -0,0 +1,69 @@ +import { OrchestratorMcpFailure, TrimmedNonEmptyString, WorkflowHook } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import { McpSchema, Tool, Toolkit } from "effect/ai"; + +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as Workflows from "../../../workflows/Workflows.ts"; +import { WorkflowRun, WorkflowRunStatus, WorkflowStep } from "../../../workflows/WorkflowStore.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; + +export const WORKFLOW_READ_ACTIONS = ["list", "read", "questions", "store"] as const; + +const WorkflowTool = Tool.make("t3_workflow", { + description: + "Durable workflow runs on this server. start: `workflow`, `input`, `idempotencyKey` (same key, same run). list: runs, by `status`. read: one run and its steps. questions: what runs ask a person. hooks: the URL paths that start runs. store: what workflows keep, under keys starting with `key`; store_set a `key` to `value`; store_delete. signal: wake a wait with `value`, addressed by `runId` and `wait`, or by `workflow` and `channel`; answers a question as `{choice, reason?}`. resume: run a paused run's failed step again. cancel.", + parameters: Schema.Struct({ + action: Schema.Literals([ + ...WORKFLOW_READ_ACTIONS, + "hooks", + "start", + "signal", + "resume", + "cancel", + "store_set", + "store_delete", + ]), + workflow: Schema.optional(TrimmedNonEmptyString), + input: Schema.optional(Schema.Json), + idempotencyKey: Schema.optional(TrimmedNonEmptyString), + runId: Schema.optional(TrimmedNonEmptyString), + status: Schema.optional(WorkflowRunStatus), + wait: Schema.optional(TrimmedNonEmptyString), + key: Schema.optional(TrimmedNonEmptyString), + channel: Schema.optional(TrimmedNonEmptyString), + value: Schema.optional(Schema.Json), + signalId: Schema.optional( + TrimmedNonEmptyString.annotate({ + description: "Reuse it to retry the same signal. A new signal gets a new id.", + }), + ), + reason: Schema.optional(Schema.String), + }), + success: Schema.Struct({ + run: Schema.optional(WorkflowRun), + steps: Schema.optional(Schema.Array(WorkflowStep)), + runs: Schema.optional(Schema.Array(WorkflowRun)), + questions: Schema.optional(Schema.Array(Workflows.WorkflowQuestion)), + hooks: Schema.optional(Schema.Array(WorkflowHook)), + entries: Schema.optional( + Schema.Array(Schema.Struct({ key: Schema.String, value: Schema.Json })), + ), + delivery: Schema.optional(Schema.Literals(["delivered", "buffered"])), + }), + failure: OrchestratorMcpFailure, + failureMode: "return" as const, + dependencies: [ + McpInvocationContext.McpInvocationContext, + Workflows.Workflows, + ThreadManagementService.ThreadManagementService, + SecureRandom.SecureRandom, + ], +}) + .annotate(Tool.Title, "Workflow runs") + .annotate(Tool.Destructive, true) + // Outside clients and the CLI drive workflows. An agent in a thread reaches them through the + // CLI, so the tool costs no thread any context. + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromThreads); + +export const WorkflowToolkit = Toolkit.make(WorkflowTool); diff --git a/apps/server/src/milestones/MilestoneEvents.test.ts b/apps/server/src/milestones/MilestoneEvents.test.ts index bdf102b4dce6f..44896477fa670 100644 --- a/apps/server/src/milestones/MilestoneEvents.test.ts +++ b/apps/server/src/milestones/MilestoneEvents.test.ts @@ -174,7 +174,7 @@ it.effect("advertises the extension and lists each milestone type to outside cli }); const { events } = (yield* call("events/list")).result!; - expect(events).toHaveLength(6); + expect(events).toHaveLength(12); const settledType = events.find( (event: { name: string }) => event.name === "thread.run_settled", ); @@ -182,9 +182,19 @@ it.effect("advertises the extension and lists each milestone type to outside cli expect(Object.keys(settledType.inputSchema.properties)).toEqual([ "projectIds", "threadIds", + "workflowRunIds", "includeSubagentChildren", ]); expect(settledType.payloadSchema.properties.outcome).toBeDefined(); + const workflowType = events.find( + (event: { name: string }) => event.name === "workflow.run_ended", + ); + // A workflow run belongs to no project or thread, so it is picked by workflow and run. + expect(Object.keys(workflowType.inputSchema.properties)).toEqual([ + "workflows", + "workflowRunIds", + "includeSubagentChildren", + ]); expect((yield* call("events/list", {}, { token: threadToken })).result!.events).toEqual([]); }).pipe(Effect.scoped, Effect.provide(layerTest)), ); diff --git a/apps/server/src/milestones/MilestoneEvents.ts b/apps/server/src/milestones/MilestoneEvents.ts index 5b07d64b3aa59..9c0f2edd0ae55 100644 --- a/apps/server/src/milestones/MilestoneEvents.ts +++ b/apps/server/src/milestones/MilestoneEvents.ts @@ -1,8 +1,10 @@ import { type MilestoneEvent as MilestoneEventValue, MilestoneEvent, + type MilestoneFilter, ProjectId, ThreadId, + TrimmedNonEmptyString, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -15,12 +17,30 @@ import * as MilestoneHub from "./MilestoneHub.ts"; const MAX_EVENTS = 1_000; const DEFAULT_EVENTS = 100; +const includeSubagentChildren = Schema.optional( + Schema.Boolean.annotate({ + description: "Also subagent threads and runs another run invoked.", + }), +); +const workflowRunIds = Schema.optional(Schema.Array(TrimmedNonEmptyString)); + const Parameters = Schema.Struct({ projectIds: Schema.optional(Schema.Array(ProjectId)), threadIds: Schema.optional(Schema.Array(ThreadId)), - includeSubagentChildren: Schema.optional( - Schema.Boolean.annotate({ description: "Also subagent threads." }), + workflowRunIds: Schema.optional( + Schema.Array(TrimmedNonEmptyString).annotate({ + description: "Workflow runs, for the threads that are their agent steps.", + }), + ), + includeSubagentChildren, +}); + +const WorkflowParameters = Schema.Struct({ + workflows: Schema.optional( + Schema.Array(TrimmedNonEmptyString).annotate({ description: "Workflow names." }), ), + workflowRunIds, + includeSubagentChildren, }); const DESCRIPTIONS: Record = { @@ -30,6 +50,13 @@ const DESCRIPTIONS: Record = { "thread.guest_request": "A guest on a shared thread asked for something.", "thread.guest_request_resolved": "A guest's request was sent, dismissed, or its link closed.", "pr.watch_wake": "A watched pull request changed and woke its thread.", + "workflow.run_started": "A workflow run started.", + "workflow.needs_input": "A workflow run asks a person a question.", + "workflow.input_resolved": + "A workflow run's question was answered, timed out, or ended with its run.", + "workflow.run_paused": "A workflow run paused: a step failed, or someone paused it.", + "workflow.run_resumed": "A paused workflow run went on again.", + "workflow.run_ended": "A workflow run ended: completed, stopped, skipped or cancelled.", }; const occurrence = ({ event }: MilestoneHub.PositionedMilestone) => ({ @@ -41,42 +68,58 @@ const occurrence = ({ event }: MilestoneHub.PositionedMilestone) => ({ /** * Each milestone type as an MCP event type (SEP-3415), for outside clients to poll or stream. * Cursors are the hub's, so a client that was away catches up on what the hub still keeps. + * Workflow runs have no project or thread, so their types are narrowed by workflow and run. */ export const make = Effect.gen(function* () { const hub = yield* MilestoneHub.MilestoneHub; - return MilestoneEvent.members.map((payload) => { - const type = payload.fields.type.literal; - const filterOf = (args: typeof Parameters.Type) => ({ ...args, types: [type] }); - return { - name: type, - description: DESCRIPTIONS[type], - parameters: Parameters, - payload, - poll: (args, request) => - hub - .read({ - cursor: request.cursor, - maxAgeMs: request.maxAgeMs, - filter: filterOf(args), - limit: Math.min(request.maxEvents ?? DEFAULT_EVENTS, MAX_EVENTS), - }) - .pipe(Effect.map((page) => ({ ...page, events: page.events.map(occurrence) }))), - stream: (args, request) => - hub - .follow({ cursor: request.cursor, maxAgeMs: request.maxAgeMs, filter: filterOf(args) }) - .pipe( - Effect.map(({ cursor, truncated, items }) => ({ - cursor, - truncated, - items: items.pipe( - Stream.map((item): McpServer.EventStreamItem => - item._tag === "Milestone" - ? { _tag: "Event", cursor: item.cursor, ...occurrence(item) } - : item, - ), - ), - })), - ), - } satisfies McpServer.EventOptions; - }); + const isWorkflow = (payload: (typeof MilestoneEvent.members)[number]) => + payload.fields.type.literal.startsWith("workflow."); + return { + threads: MilestoneEvent.members + .filter((payload) => !isWorkflow(payload)) + .map((payload) => eventOf(hub, payload, Parameters)), + workflows: MilestoneEvent.members + .filter(isWorkflow) + .map((payload) => eventOf(hub, payload, WorkflowParameters)), + }; }); + +const eventOf =

    ( + hub: MilestoneHub.MilestoneHub["Service"], + payload: (typeof MilestoneEvent.members)[number], + parameters: P, +) => { + const type = payload.fields.type.literal; + const filterOf = (args: P["Type"]): MilestoneFilter => ({ ...args, types: [type] }); + return { + name: type, + description: DESCRIPTIONS[type], + parameters, + payload, + poll: (args, request) => + hub + .read({ + cursor: request.cursor, + maxAgeMs: request.maxAgeMs, + filter: filterOf(args), + limit: Math.min(request.maxEvents ?? DEFAULT_EVENTS, MAX_EVENTS), + }) + .pipe(Effect.map((page) => ({ ...page, events: page.events.map(occurrence) }))), + stream: (args, request) => + hub + .follow({ cursor: request.cursor, maxAgeMs: request.maxAgeMs, filter: filterOf(args) }) + .pipe( + Effect.map(({ cursor, truncated, items }) => ({ + cursor, + truncated, + items: items.pipe( + Stream.map((item): McpServer.EventStreamItem => + item._tag === "Milestone" + ? { _tag: "Event", cursor: item.cursor, ...occurrence(item) } + : item, + ), + ), + })), + ), + } satisfies McpServer.EventOptions; +}; diff --git a/apps/server/src/milestones/MilestoneHub.test.ts b/apps/server/src/milestones/MilestoneHub.test.ts index 0361c81f4f7e0..40d757a50c3ea 100644 --- a/apps/server/src/milestones/MilestoneHub.test.ts +++ b/apps/server/src/milestones/MilestoneHub.test.ts @@ -21,6 +21,22 @@ const settled = ( runId: RunId.make(`run:${id}`), outcome: "completed", }); +const workflowEnded = (id: string, workflowRunId: string): MilestoneEvent => ({ + id: MilestoneId.make(id), + type: "workflow.run_ended", + occurredAt: "2026-11-20T00:00:00.000Z", + projectId: null, + threadId: null, + parentThreadId: null, + actor: { type: "system" }, + isSubagentChild: false, + workflowRunId, + workflow: "review", + runTitle: "Review", + parentWorkflowRunId: null, + outcome: "completed", + detail: null, +}); const ids = (events: Iterable) => [...events].map((event) => event.id); it.effect("fans out to every subscriber, muting subagent children unless asked for", () => @@ -29,21 +45,31 @@ it.effect("fans out to every subscriber, muting subagent children unless asked f const muted = yield* hub.subscribe(); const everything = yield* hub.subscribe({ includeSubagentChildren: true }); const projectB = yield* hub.subscribe({ projectIds: [ProjectId.make("project:b")] }); + const runR1 = yield* hub.subscribe({ workflowRunIds: ["r1"] }); yield* hub.publish(settled("a")); yield* hub.publish(settled("child", { child: true })); // A repeat of an id is the same milestone. yield* hub.publish(settled("a")); yield* hub.publish(settled("b", { project: "project:b" })); + yield* hub.publish(workflowEnded("w0", "r0")); + yield* hub.publish(workflowEnded("w1", "r1")); - assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(muted, 2))), ["a", "b"]); + assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(muted, 4))), [ + "a", + "b", + "w0", + "w1", + ]); assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(everything, 3))), [ "a", "child", "b", ]); + // A workflow milestone has no project, and a thread milestone no workflow run. assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(projectB, 1))), ["b"]); - assert.deepStrictEqual(ids((yield* hub.recent()).events), ["a", "b"]); + assert.deepStrictEqual(ids(yield* Stream.runCollect(Stream.take(runR1, 1))), ["w1"]); + assert.deepStrictEqual(ids((yield* hub.recent()).events), ["a", "b", "w0", "w1"]); }).pipe(Effect.scoped, Effect.provide(MilestoneHub.layer)), ); diff --git a/apps/server/src/milestones/OrchestrationMilestones.test.ts b/apps/server/src/milestones/OrchestrationMilestones.test.ts index 7930b2ab8097b..bffe7b75fe605 100644 --- a/apps/server/src/milestones/OrchestrationMilestones.test.ts +++ b/apps/server/src/milestones/OrchestrationMilestones.test.ts @@ -1,6 +1,7 @@ import { assert, it } from "@effect/vitest"; import { CommandId, + EnvironmentId, EventId, GuestMessageId, GuestShareId, @@ -106,6 +107,40 @@ it.effect("tells each thread transition once, with its lineage", () => const childThreadId = (yield* projections.getThreadProjection(parentThreadId)).subagents[0]! .childThreadId!; const childRun = (yield* projections.getThreadRecords(childThreadId, ["runs"])).runs[0]!; + // A workflow run's agent step, which a filter on its run picks out. + const stepThreadId = ThreadId.make("thread:milestone-workflow-step"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-milestone-step"), + threadId: stepThreadId, + projectId: ProjectId.make("project:milestones"), + title: "Triage", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "system", + creationSource: "server", + workflowRun: { + environmentId: EnvironmentId.make("environment:milestones"), + runId: "workflow-run:milestones", + workflow: "review", + step: "triage", + }, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-milestone-step"), + threadId: stepThreadId, + messageId: MessageId.make("message:milestone-step"), + text: "Triage the issue", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "system", + creationSource: "server", + }); + const stepRun = (yield* projections.getThreadRecords(stepThreadId, ["runs"])).runs[0]!; const parent = yield* projections.getThread(parentThreadId); const now = yield* DateTime.now; const base = (id: string, threadId: ThreadId) => ({ @@ -213,6 +248,7 @@ it.effect("tells each thread transition once, with its lineage", () => shared("event:guest-closed", null), wake, wake, + ended("event:step-done", stepRun, "completed"), ]) { yield* feeder.handle(event); } @@ -235,8 +271,15 @@ it.effect("tells each thread transition once, with its lineage", () => ["thread.guest_request:guest:two", parentThreadId, null, false], ["thread.guest_request_resolved:guest:two", parentThreadId, null, false], ["pr.watch_wake:message:pr-wake", parentThreadId, null, false], + [`thread.run_settled:${stepRun.id}`, stepThreadId, null, false], ], ); + assert.deepStrictEqual( + (yield* hub.recent({ filter: { workflowRunIds: ["workflow-run:milestones"] } })).events.map( + (event) => event.threadId, + ), + [stepThreadId], + ); const [, child, asked, answered, , sent, , closed, woke] = events; assert.deepInclude(child, { outcome: "failed", projectId: parent.projectId }); assert.deepInclude(asked, { kind: "approval" }); diff --git a/apps/server/src/milestones/OrchestrationMilestones.ts b/apps/server/src/milestones/OrchestrationMilestones.ts index c50c460ec4814..941776771a040 100644 --- a/apps/server/src/milestones/OrchestrationMilestones.ts +++ b/apps/server/src/milestones/OrchestrationMilestones.ts @@ -70,6 +70,7 @@ const make = Effect.gen(function* () { parentThreadId: thread.lineage.parentThreadId, actor, isSubagentChild: thread.lineage.relationshipToParent === "subagent", + ...(thread.workflowRun === undefined ? {} : { workflowRunId: thread.workflowRun.runId }), }); const guestMilestones = ( diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index f8e20da24fbaf..a4a918fe1ddee 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -105,6 +105,15 @@ const RPC_AGGREGATES = { [WS_METHODS.serverRefreshUsageRates]: "server", [WS_METHODS.serverSignalProcess]: "server", [WS_METHODS.serverReportClientActivity]: "server", + [WS_METHODS.workflowsSubscribe]: "workflows", + [WS_METHODS.workflowsCounts]: "workflows", + [WS_METHODS.workflowsGet]: "workflows", + [WS_METHODS.workflowsAnswer]: "workflows", + [WS_METHODS.workflowsResume]: "workflows", + [WS_METHODS.workflowsCancel]: "workflows", + [WS_METHODS.workflowsGetDefinition]: "workflows", + [WS_METHODS.workflowsSaveDefinition]: "workflows", + [WS_METHODS.workflowsDeleteDefinition]: "workflows", [WS_METHODS.scheduledTasksSubscribe]: "scheduledTasks", [WS_METHODS.scheduledTasksUpsert]: "scheduledTasks", [WS_METHODS.scheduledTasksSetEnabled]: "scheduledTasks", diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5b1623f8414ec..8a546270a0515 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -4077,10 +4077,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.linkOrigin === undefined || command.delegatedFrom === undefined ? {} : { delegatedFrom: command.delegatedFrom }), + ...(command.workflowRun === undefined ? {} : { workflowRun: command.workflowRun }), lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: command.threadId, + ...(command.workflowRun === undefined ? {} : { workflowStep: true }), }, forkedFrom: null, createdAt: now, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e10bc5340d646..2278284d7fde7 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1960,6 +1960,9 @@ export function threadShellFromProjection( ...(projection.thread.delegatedFrom === undefined ? {} : { delegatedFrom: projection.thread.delegatedFrom }), + ...(projection.thread.workflowRun === undefined + ? {} + : { workflowRun: projection.thread.workflowRun }), latestRunId: latestRun?.id ?? null, latestRunRequestedAt: latestRun?.requestedAt ?? null, latestRunStartedAt: latestRun?.startedAt ?? null, @@ -2274,6 +2277,9 @@ function shellFromState(input: { ...(input.state.thread.delegatedFrom === undefined ? {} : { delegatedFrom: input.state.thread.delegatedFrom }), + ...(input.state.thread.workflowRun === undefined + ? {} + : { workflowRun: input.state.thread.workflowRun }), latestRunId: input.state.latestRunId, latestRunRequestedAt: input.state.latestRunRequestedAt, latestRunStartedAt: input.state.latestRunStartedAt, @@ -9620,6 +9626,7 @@ export const layer: Layer.Layer = readonly parent_thread_id: string | null; readonly root_thread_id: string; readonly side_chat: number | null; + readonly workflow_step: number | null; readonly delegated_from_environment_id: string | null; readonly delegated_from_thread_id: string | null; readonly delegated_from_title: string | null; @@ -9636,6 +9643,7 @@ export const layer: Layer.Layer = json_extract(t.payload_json, '$.lineage.parentThreadId') AS parent_thread_id, json_extract(t.payload_json, '$.lineage.rootThreadId') AS root_thread_id, json_extract(t.payload_json, '$.lineage.sideChat') AS side_chat, + json_extract(t.payload_json, '$.lineage.workflowStep') AS workflow_step, json_extract(t.payload_json, '$.delegatedFrom.environmentId') AS delegated_from_environment_id, json_extract(t.payload_json, '$.delegatedFrom.threadId') AS delegated_from_thread_id, json_extract(t.payload_json, '$.delegatedFrom.title') AS delegated_from_title, @@ -9650,7 +9658,10 @@ export const layer: Layer.Layer = id: ThreadId.make(row.thread_id), projectId: ProjectId.make(row.project_id), title: row.title, - lineage: shellIndexLineage(row), + lineage: { + ...shellIndexLineage(row), + ...(row.workflow_step === 1 ? { workflowStep: true } : {}), + }, ...(row.delegated_from_environment_id === null || row.delegated_from_thread_id === null ? {} : { diff --git a/apps/server/src/orchestration-v2/ThreadForkService.ts b/apps/server/src/orchestration-v2/ThreadForkService.ts index e3e523e372bd0..2981b4ccfb519 100644 --- a/apps/server/src/orchestration-v2/ThreadForkService.ts +++ b/apps/server/src/orchestration-v2/ThreadForkService.ts @@ -100,7 +100,12 @@ export const layer: Layer.Layer = Layer.succeed( }); } // The remote parent delegated the source thread, not its forks. - const { delegatedFrom: _delegatedFrom, ...inherited } = input.sourceProjection.thread; + // Nor is a fork a step of the run its source was one of. + const { + delegatedFrom: _delegatedFrom, + workflowRun: _workflowRun, + ...inherited + } = input.sourceProjection.thread; const targetThread: OrchestrationV2AppThread = { ...inherited, // PR context follows the conversation; watching remains the source thread's responsibility. diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 73eaabdde2016..2d5d1c5824dde 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -503,7 +503,7 @@ it.effect( }, ); -it.effect("leaves a task delegated from a linked environment out of the top-level list", () => { +it.effect("leaves delegated tasks and workflow agent steps out of the top-level list", () => { const harness = makeHarness(); return Effect.gen(function* () { const launches = yield* ThreadLaunch.ThreadLaunchService; @@ -522,15 +522,26 @@ it.effect("leaves a task delegated from a linked environment out of the top-leve title: "Remote parent", }, }); + const workflowStep = yield* launches.launch({ + ...launchInput({ command: "command:workflow-step", thread: "thread:workflow-step" }), + createdBy: "system", + creationSource: "server", + workflowRun: { + environmentId: EnvironmentId.make("environment:local"), + runId: "run:1", + workflow: "review", + step: "agent", + }, + }); const listed = yield* threads.listProjectThreads({ projectId, includeSubagents: false }); assert.deepEqual( listed.map((thread) => thread.id), [ThreadId.make("thread:top-level")], ); const all = yield* threads.listProjectThreads({ projectId, includeSubagents: true }); - assert.include( + assert.includeMembers( all.map((thread) => thread.id), - delegated.threadId, + [delegated.threadId, workflowStep.threadId], ); }).pipe(Effect.provide(harness.layer)); }); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 0382415179bfc..ce22ad783e0e6 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -10,6 +10,7 @@ import { type OrchestrationV2Actor, type OrchestrationV2CreationSource, type OrchestrationV2DelegatedFrom, + type OrchestrationV2WorkflowOrigin, type OrchestrationV2LinkOrigin, type OrchestrationV2ProviderThreadNativeMetadata, type OrchestrationV2ThreadProjection, @@ -124,6 +125,8 @@ export interface ThreadLaunchInput { readonly linkOrigin?: OrchestrationV2LinkOrigin; /** The parent there, when that environment's agent delegated this as a task. */ readonly delegatedFrom?: OrchestrationV2DelegatedFrom; + /** The workflow run this thread is an agent step of. */ + readonly workflowRun?: OrchestrationV2WorkflowOrigin; } type PreparationInput = Pick< @@ -1473,6 +1476,7 @@ const make = Effect.gen(function* () { ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }), + ...(input.workflowRun === undefined ? {} : { workflowRun: input.workflowRun }), createdBy: input.createdBy, creationSource: input.creationSource, ...(initialMessage === undefined diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index a0b5625af0d2a..eb137e4c50610 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -74,6 +74,13 @@ it("stamps authoritative provenance on commands that create threads or messages" text: "Forged", attachments: [], }, + // Nor a workflow run it is a step of. + workflowRun: { + environmentId: EnvironmentId.make("environment:elsewhere"), + runId: "run-1", + workflow: "fix", + step: "write", + }, }; const stamped = ThreadManagementService.withCreationProvenance(command, { @@ -87,6 +94,7 @@ it("stamps authoritative provenance on commands that create threads or messages" expect(stamped).not.toHaveProperty("linkOrigin"); expect(stamped).not.toHaveProperty("delegatedFrom"); expect(stamped).not.toHaveProperty("initialMessage"); + expect(stamped).not.toHaveProperty("workflowRun"); }); const layerReceiptsTest = CommandReceiptStore.layer.pipe( @@ -465,6 +473,113 @@ it.effect("waitForThread can wait past an ended run for the thread's delegated w }), ); +it.effect( + "a turn that ended without its result is waited past, and a later turn answers for it", + () => + Effect.gen(function* () { + const projectId = ProjectId.make("project:thread-management:owed"); + const threadId = ThreadId.make("thread:thread-management:owed"); + const runId = RunId.make("run:thread-management:owed"); + const wakeRunId = RunId.make("run:thread-management:owed:wake"); + const subscribed = yield* Deferred.make(); + const events = yield* Queue.unbounded(); + const outputSchema = { type: "object", required: ["head"] }; + const run = (id: RunId, ordinal: number, fields: object) => + ({ id, ordinal, ...fields }) as unknown as OrchestrationV2Run; + // The agent ended its turn to wait for something, without the result it was asked for. + let runs = [run(runId, 1, { status: "completed", outputSchema })]; + const submitted: Array = []; + const stored = (sequence: number, event: object) => + ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent; + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadEventSequence: () => Effect.succeed(0), + restartContinuationPending: () => Effect.succeed(false), + streamStoredEventsFrom: (input) => + input?.eventType === "run.output-submitted" + ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe( + Stream.drain, + Stream.concat(Stream.fromQueue(events)), + ) + : Stream.never, + getThreadRecords: () => + Effect.sync( + () => + ({ + thread: { id: threadId, projectId, deletedAt: null }, + runs, + }) as unknown as OrchestrationV2ThreadProjection, + ), + dispatch: (command) => + Effect.sync(() => { + submitted.push(command); + return { sequence: 1 } as never; + }), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerReceiptsTest), + ); + const service = yield* ThreadManagementService.ThreadManagementService.pipe( + Effect.provide(layerTest), + ); + const wait = { projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }; + // Without the option the ended turn is the answer, as before. + expect(yield* service.waitForThread(wait)).toMatchObject({ timedOut: false }); + // A turn asked for nothing owes nothing, so the option does not hold it. + const plainRunId = RunId.make("run:thread-management:owed:plain"); + runs = [run(plainRunId, 0, { status: "completed" }), ...runs]; + expect( + yield* Effect.raceFirst( + service.waitForThread({ ...wait, runId: plainRunId, untilOutput: true }), + Effect.as(Deferred.await(subscribed), "waited for a result"), + ), + ).toMatchObject({ timedOut: false, run: { id: plainRunId } }); + runs = runs.slice(1); + + const fiber = yield* service + .waitForThread({ ...wait, untilOutput: true }) + .pipe(Effect.forkChild); + yield* Effect.raceFirst(Deferred.await(subscribed), Fiber.await(fiber)); + // Something wakes the thread. The turn it starts was asked for nothing, and submits anyway. + // A request queued behind it asks for a result of its own, and is not the one owed. + const queuedRunId = RunId.make("run:thread-management:owed:queued"); + runs = [ + ...runs, + run(wakeRunId, 2, { status: "running" }), + run(queuedRunId, 3, { status: "queued", outputSchema }), + ]; + const accepted = yield* service.submitRunOutput({ + threadId, + commandId: CommandId.make("command:thread-management:owed"), + json: '{"head":"abc"}', + }); + expect(accepted.runId).toBe(runId); + expect(submitted).toMatchObject([ + { type: "run.output.submit", runId, value: { head: "abc" } }, + ]); + const output = { value: { head: "abc" }, submittedAt: "2026-01-01T00:00:00.000Z" }; + runs = [run(runId, 1, { status: "completed", outputSchema, output }), runs[1]!, runs[2]!]; + yield* Queue.offer(events, stored(1, { type: "run.output-submitted", payload: {} })); + expect(yield* Fiber.join(fiber)).toMatchObject({ + timedOut: false, + run: { id: runId, output }, + }); + + // The result is given once: a later plain turn has nothing to submit to. + const again = yield* service + .submitRunOutput({ + threadId, + commandId: CommandId.make("command:thread-management:owed:again"), + json: '{"head":"def"}', + }) + .pipe(Effect.flip); + expect(again.message).toContain("not asked for a result"); + }), +); + it.effect("waitForThread settles delegated work on a thread rolled back past its only run", () => Effect.gen(function* () { const projectId = ProjectId.make("project:thread-management:wait-rolled-back"); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 45b5e9effa8cf..0acb07029f35d 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -70,6 +70,7 @@ import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts"; import { projectTurnItemForDetail } from "./WireProjection.ts"; import { cancelledBeforeStart } from "./RestartBackgroundNote.ts"; +import { contextBoundaryOrdinal } from "./contextBoundary.ts"; import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; import * as ServerSettings from "../serverSettings.ts"; import { ThreadWorktreeRestore } from "../workspace/restoreMissingWorktree.ts"; @@ -93,6 +94,7 @@ export function withCreationProvenance( linkOrigin: _linkOrigin, delegatedFrom: _delegatedFrom, initialMessage: _initialMessage, + workflowRun: _workflowRun, ...rest } = command; return { ...rest, ...provenance }; @@ -1035,18 +1037,44 @@ const make = Effect.gen(function* () { "ThreadManagementService.submitRunOutput", )(function* (input) { const records = yield* orchestrator.getThreadRecords(input.threadId, ["runs"]); + // A retry of a submission already taken answers for the run it went to, which a run asked for + // a result since may have followed. Replaying the receipt ignores the command's run and value. + const receipt = yield* receipts + .getByCommandId(input.commandId) + .pipe(Effect.orElseSucceed(() => Option.none())); + const anyRun = records.runs[0]; + if (Option.isSome(receipt) && receipt.value.status === "accepted" && anyRun !== undefined) { + const replayed = yield* orchestrator.dispatch({ + type: "run.output.submit", + commandId: input.commandId, + threadId: input.threadId, + runId: anyRun.id, + value: null, + }); + const runId = replayed.storedEvents.find(({ event }) => event.type === "run.output-submitted") + ?.event.runId; + if (runId !== undefined) return { runId }; + } const active = latestActiveRun(records); // A turn that ended without its result still owes it: the agent may have ended it to wait - // for something, and answer from the turn that woke it. - // Only an ended turn can owe one; a queued or running turn asked for one answers for itself. - const owed = records.runs + // for something, and answer from the turn that woke it. Only the newest started run asked for + // one can owe it, and only while the agent's conversation still reaches it. + const asked = records.runs .filter( (candidate) => candidate.outputSchema !== undefined && - candidate.output === undefined && - candidate.status === "completed", + candidate.status !== "queued" && + !cancelledBeforeStart(candidate), ) .toSorted((left, right) => right.ordinal - left.ordinal)[0]; + const owing = asked?.status === "completed" && asked.output === undefined ? asked : undefined; + const forgotten = + owing !== undefined && + records.runs.some((later) => later.freshContext === true && later.ordinal > owing.ordinal) && + contextBoundaryOrdinal( + yield* orchestrator.getThreadRecords(input.threadId, ["runs", "turnItems"]), + ) > owing.ordinal; + const owed = forgotten ? undefined : owing; const run = active?.outputSchema !== undefined ? active : owed; if (active === undefined || run?.outputSchema === undefined) { return yield* new ThreadManagementRunOutputRejectedError({ @@ -1364,6 +1392,15 @@ const make = Effect.gen(function* () { }, } as const; } + if (explicitRun?.status === "queued") { + const dispatch = yield* orchestrator.dispatch({ + type: "queued-run.cancel", + commandId: input.commandId, + threadId: input.threadId, + runId: explicitRun.id, + }); + return { type: "interrupt_requested", run: explicitRun, dispatch } as const; + } const interruptibleRun = latestActiveRun(target); if (interruptibleRun === undefined) { if (input.runId === undefined) { diff --git a/apps/server/src/orchestration-v2/runOutput.ts b/apps/server/src/orchestration-v2/runOutput.ts index 26df71c0fa2e8..20d76ecff009d 100644 --- a/apps/server/src/orchestration-v2/runOutput.ts +++ b/apps/server/src/orchestration-v2/runOutput.ts @@ -60,6 +60,12 @@ export interface OutputRejection { readonly cause?: unknown; } +/** The rejection as told to whoever wrote the value: the problem, then what in it did not fit. */ +export const rejectionText = (rejection: OutputRejection): string => + rejection.cause instanceof Error + ? `${rejection.problem}\n${rejection.cause.message.slice(0, 2000)}` + : rejection.problem; + /** * Checks what an agent submitted against the schema its run declared. The value is kept as * submitted. A schema that closes its object turns down keys it does not name; an open one keeps diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 3d640f61fc398..d43bd686d6932 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -11953,6 +11953,70 @@ it.layer(layerSharedApplicationDataPlaneTest)("pending provider interruption", ( assert.isFalse(yield* effectWorker.runOnce()); }), ); + + it.effect("cancels a named queued run and leaves the active one running", () => + Effect.gen(function* () { + const projects = yield* ProjectService.ProjectService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const projectId = ProjectId.make("runtime-layer-queued-interrupt-project"); + const threadId = ThreadId.make("runtime-layer-queued-interrupt-thread"); + + yield* projects.create({ + commandId: CommandId.make("runtime-layer-queued-interrupt-project-create"), + projectId, + title: "Queued interrupt project", + workspaceRoot: "/tmp/runtime-layer-queued-interrupt-project", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-queued-interrupt-create"), + threadId, + projectId, + title: "Queued interrupt", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + for (const [key, dispatchMode] of [ + ["active", { type: "start_immediately" }], + ["queued", { type: "queue_after_active" }], + ] as const) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`runtime-layer-queued-interrupt-${key}`), + threadId, + messageId: MessageId.make(`runtime-layer-queued-interrupt-${key}`), + text: key, + attachments: [], + modelSelection, + dispatchMode, + }); + } + const [active, queued] = (yield* orchestrator.getThreadProjection(threadId)).runs; + assert.equal(queued?.status, "queued"); + + const interrupt = yield* threadManagement.interruptThread({ + projectId, + commandId: CommandId.make("runtime-layer-queued-interrupt-command"), + threadId, + runId: queued!.id, + }); + assert.equal(interrupt.type, "interrupt_requested"); + + const after = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + after.runs.map((run) => run.status), + [active!.status, "cancelled"], + ); + }), + ); }); it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => { @@ -11984,7 +12048,11 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => branch: null, worktreePath: null, }); - const send = (key: string, outputSchema?: { readonly type: "object" }) => + const send = ( + key: string, + outputSchema?: { readonly type: "object" }, + freshContext?: boolean, + ) => orchestrator.dispatch({ type: "message.dispatch", createdBy: "user", @@ -11996,35 +12064,73 @@ it.layer(layerSharedApplicationDataPlaneTest)("run output after a stop", (it) => attachments: [], modelSelection, ...(outputSchema === undefined ? {} : { outputSchema }), + ...(freshContext === undefined ? {} : { freshContext }), dispatchMode: { type: "start_immediately" }, }); - yield* send("asked", { type: "object" }); - const asked = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; - // The agent ended its turn to wait for something, without the result. - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}-asked-completed`), - type: "run.updated", - threadId, - runId: asked.id, - occurredAt: asked.requestedAt, - payload: { ...asked, status: "completed", completedAt: asked.requestedAt }, - }, - ], + const runOf = Effect.fn(function* (key: string) { + const runs = (yield* orchestrator.getThreadProjection(threadId)).runs; + return runs.find( + (run) => run.userMessageId === MessageId.make(`runtime-layer-owed-output-${key}`), + )!; + }); + // The agent ends its turn, to wait for something or because it is done. + const complete = Effect.fn(function* (key: string) { + const run = yield* runOf(key); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-${key}-completed`), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: run.requestedAt, + payload: { ...run, status: "completed", completedAt: run.requestedAt }, + }, + ], + }); + }); + const submit = (key: string, json = '{"head":"abc"}') => + threadManagement.submitRunOutput({ + threadId, + commandId: CommandId.make(`runtime-layer-owed-output-submit-${key}`), + json, + }); + const refused = Effect.fn(function* (key: string) { + const rejected = yield* submit(key).pipe(Effect.flip); + assert.include(rejected.message, "not asked for a result"); }); + yield* send("asked", { type: "object" }); + const asked = yield* runOf("asked"); + yield* complete("asked"); yield* send("woken"); - const accepted = yield* threadManagement.submitRunOutput({ - threadId, - commandId: CommandId.make("runtime-layer-owed-output-submit"), - json: '{"head":"abc"}', - }); + const accepted = yield* submit("asked"); assert.equal(accepted.runId, asked.id); const after = yield* orchestrator.getThreadProjection(threadId); assert.deepEqual(after.runs.find((run) => run.id === asked.id)?.output?.value, { head: "abc", }); + + // Its reply was lost, and the retry comes once the next step's turn asked for a result. + yield* complete("woken"); + yield* send("next", { type: "object" }); + assert.equal((yield* submit("asked")).runId, asked.id); + assert.isUndefined((yield* runOf("next")).output); + + // A correction gave the result `next` owed, so a later plain turn owes nothing. + yield* complete("next"); + yield* send("correction", { type: "object" }); + yield* submit("correction"); + yield* complete("correction"); + yield* send("plain"); + yield* refused("plain"); + + // A turn in a fresh conversation cannot answer for one the agent no longer sees. + yield* complete("plain"); + yield* send("before-fresh", { type: "object" }); + yield* complete("before-fresh"); + yield* send("fresh", undefined, true); + yield* refused("fresh"); }), ); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 1710da5b061d7..c4eed74b274cf 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -56,6 +56,10 @@ import * as ResourceCleanupService from "./ResourceCleanupService.ts"; import * as RuntimePolicy from "./RuntimePolicy.ts"; import * as RuntimeRequestService from "./RuntimeRequestService.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; +import * as PeerLinks from "../peer/PeerLinks.ts"; +import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import * as WorkflowRuntime from "../workflows/WorkflowRuntime.ts"; +import * as ThreadIssueService from "./ThreadIssueService.ts"; import * as ThreadLaunchService from "./ThreadLaunchService.ts"; import * as ThreadForkService from "./ThreadForkService.ts"; import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; @@ -312,6 +316,17 @@ const layerThreadLaunchProvided = ThreadLaunchService.layer.pipe( ).pipe(Layer.provideMerge(layerProjectService)), ), ); +const layerWorkflowsProvided = WorkflowRuntime.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerThreadLaunchProvided, + layerThreadManagementProvided, + ThreadIssueService.layer.pipe(Layer.provide(layerOrchestratorProvided)), + ).pipe(Layer.provideMerge(layerProjectService)), + ), + // Layers memoize by reference, so these are the links Settings and agents use. + Layer.provide(PeerMcpClient.layer.pipe(Layer.provideMerge(PeerLinks.layer))), +); const layerSecretRequestsProvided = SecretRequests.layer.pipe( Layer.provide(layerThreadManagementProvided), ); @@ -423,6 +438,7 @@ export const layerProduction = Layer.mergeAll( layerManagedProjectFoldersProvided, layerThreadLaunchProvided, layerScheduledTaskProvided, + layerWorkflowsProvided, layerScratchThreadPromotionProvided, layerSecretRequestsProvided, layerFeedbackStoreProvided, diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index bf47bc86109bb..bb336d3179f34 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -152,6 +152,7 @@ export function makeReplayServerConfig( providerStatusCacheDir, worktreesDir, worktreeCheckoutCacheDir: path.join(providerStatusCacheDir, "worktree-checkouts"), + workflowsDir: path.join(baseDir, "workflows"), attachmentsDir, browserArtifactsDir: path.join(stateDir, "browser-artifacts"), environmentThemesDir, diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 9b3fc0b4bb472..36762e9059b58 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -117,6 +117,7 @@ import Migration0106 from "./Migrations/106_WorktreePathKeyIndex.ts"; import Migration0107 from "./Migrations/107_DeferredSlashCommandIndex.ts"; import Migration0108 from "./Migrations/108_AgentFeedback.ts"; import Migration0109 from "./Migrations/109_IssueTrackerAccounts.ts"; +import Migration0110 from "./Migrations/110_Workflows.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -229,6 +230,7 @@ const migrationEntries = [ [107, "DeferredSlashCommandIndex", Migration0107], [108, "AgentFeedback", Migration0108], [109, "IssueTrackerAccounts", Migration0109], + [110, "Workflows", Migration0110], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/110_Workflows.ts b/apps/server/src/persistence/Migrations/110_Workflows.ts new file mode 100644 index 0000000000000..39f588a564057 --- /dev/null +++ b/apps/server/src/persistence/Migrations/110_Workflows.ts @@ -0,0 +1,149 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +// What people and clients look at of a workflow run, and how something outside reaches a sleeping +// one. The engine journals each run in tables of its own, which it creates when it first starts. +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql` + CREATE TABLE workflow_runs ( + run_id TEXT PRIMARY KEY, + workflow TEXT NOT NULL, + version INTEGER NOT NULL, + engine_tag TEXT NOT NULL, + idempotency_key TEXT NOT NULL, + title TEXT NOT NULL, + status TEXT NOT NULL, + detail TEXT, + result_json TEXT, + pauses INTEGER NOT NULL DEFAULT 0, + started_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + ended_at TEXT, + -- What a run was started with, for the cleanup of a cancelled run whose body is gone. + input_json TEXT, + -- The run that invoked this one and the wait it sits in, so it hears how this one ended. + parent_run_id TEXT, + parent_wait TEXT, + -- A run its agent gave up on waits for a person: resuming starts the agent's whole job again. + held INTEGER NOT NULL DEFAULT 0, + -- When an ended run's engine journal was deleted; the run's own rows stay. + engine_pruned_at TEXT + ) + `; + yield* sql`CREATE INDEX workflow_runs_status ON workflow_runs (status, updated_at)`; + yield* sql`CREATE INDEX workflow_runs_parent ON workflow_runs (parent_run_id)`; + // A key names one run of a workflow whatever its version: the row that takes it is that run. + yield* sql`CREATE UNIQUE INDEX workflow_runs_key ON workflow_runs (workflow, idempotency_key)`; + yield* sql` + CREATE INDEX workflow_runs_unpruned ON workflow_runs (ended_at) + WHERE ended_at IS NOT NULL AND engine_pruned_at IS NULL + `; + yield* sql` + CREATE TABLE workflow_steps ( + run_id TEXT NOT NULL, + name TEXT NOT NULL, + kind TEXT NOT NULL, + status TEXT NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0, + detail TEXT, + thread_id TEXT, + started_at TEXT NOT NULL, + ended_at TEXT, + -- The linked environment an agent step's thread is in; null for this one. + environment_id TEXT, + -- What a step produced, for a person reading the run. The engine keeps its own copy to replay. + result_json TEXT, + -- An agent that returns data also says something at the end; a person reads that first. + said TEXT, + -- The agent step's own turn, so cancelling its run stops that turn and not the whole thread. + turn_id TEXT, + PRIMARY KEY (run_id, name) + ) + `; + yield* sql` + CREATE TABLE workflow_waits ( + run_id TEXT NOT NULL, + name TEXT NOT NULL, + workflow TEXT NOT NULL, + token TEXT NOT NULL, + key TEXT, + schema_json TEXT NOT NULL, + request_json TEXT, + deadline TEXT, + opened_at TEXT NOT NULL, + signalled_at TEXT, + -- What the engine itself looks at to end this wait, such as a pull request's checks. + watch_json TEXT, + -- What a wait was woken with, kept until the run is past it, so a wake lost to a crash is redone. + woke_json TEXT, + PRIMARY KEY (run_id, name) + ) + `; + yield* sql`CREATE INDEX workflow_waits_key ON workflow_waits (workflow, key)`; + // A signal that arrived before its wait. `address` is `run::` or `key::`. + yield* sql` + CREATE TABLE workflow_mail ( + signal_id TEXT PRIMARY KEY, + address TEXT NOT NULL, + value_json TEXT NOT NULL, + expires_at TEXT NOT NULL + ) + `; + yield* sql`CREATE INDEX workflow_mail_address ON workflow_mail (address)`; + // How often a run reached a point it must not pass twice without a person or a rest. + yield* sql` + CREATE TABLE workflow_marks ( + run_id TEXT NOT NULL, + name TEXT NOT NULL, + count INTEGER NOT NULL, + PRIMARY KEY (run_id, name) + ) + `; + // Ids of signals that woke a wait, so a sender's retry of one is not a second signal. Kept at + // least as long as any kept copy of the signal, which would otherwise wake a second wait. + yield* sql` + CREATE TABLE workflow_signals ( + signal_id TEXT PRIMARY KEY, + kept_until TEXT NOT NULL + ) + `; + // When each schedule trigger is next due. + yield* sql` + CREATE TABLE workflow_triggers ( + trigger_id TEXT PRIMARY KEY, + next_at TEXT NOT NULL + ) + `; + // The secret half of each workflow hook's URL. + yield* sql` + CREATE TABLE workflow_hooks ( + hook_id TEXT PRIMARY KEY, + token TEXT NOT NULL + ) + `; + // What workflows keep between runs: a cursor, a switch, a queue. + yield* sql` + CREATE TABLE workflow_store ( + key TEXT PRIMARY KEY, + value_json TEXT NOT NULL, + updated_at TEXT NOT NULL + ) + `; + // What a run touched, once per thing: a later touch updates the row and adds its step. + yield* sql` + CREATE TABLE workflow_run_references ( + run_id TEXT NOT NULL, + kind TEXT NOT NULL, + key TEXT NOT NULL, + address_json TEXT NOT NULL, + title TEXT NOT NULL, + url TEXT, + state TEXT, + steps_json TEXT NOT NULL, + origin TEXT NOT NULL, + noted_at TEXT NOT NULL, + PRIMARY KEY (run_id, kind, key) + ) + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 1b57a7d5e57c3..1b8cf040b5fbc 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -89,6 +89,7 @@ describe("V2 preview upgrade", () => { [107, "DeferredSlashCommandIndex"], [108, "AgentFeedback"], [109, "IssueTrackerAccounts"], + [110, "Workflows"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -221,6 +222,7 @@ describe("V2 preview upgrade", () => { [107, "DeferredSlashCommandIndex"], [108, "AgentFeedback"], [109, "IssueTrackerAccounts"], + [110, "Workflows"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 1117bf29801f8..ad8593c387528 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -33,6 +33,7 @@ import { PeerLinkRequests } from "../peer/PeerLinkRequests.ts"; import { PeerLinks } from "../peer/PeerLinks.ts"; import { RemoteDelegation } from "../peer/RemoteDelegation.ts"; import { PreviewManager } from "../preview/Manager.ts"; +import { Workflows } from "../workflows/Workflows.ts"; import { PreviewBrowser } from "../preview/PreviewBrowser.ts"; import { ManagedProjectFolders } from "../project/ManagedProjectFolders.ts"; import { ProjectCloneTracker } from "../project/ProjectCloneTracker.ts"; @@ -75,6 +76,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(PreviewAutomationBroker)({}), Layer.mock(PreviewBrowser)({}), Layer.mock(PreviewManager)({}), + Layer.mock(Workflows)({}), Layer.mock(ProjectCloneTracker)({}), Layer.mock(ProjectService)({}), Layer.mock(ProjectSetupScriptRunner)({}), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 3f204d2e68a8d..169fac6ce2a85 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 60374 + "mcpToolListJsonBytes": 61724 } diff --git a/apps/server/src/scheduledTasks/Schedule.ts b/apps/server/src/scheduledTasks/Schedule.ts index f8fb648aaaaa9..ec1f3c2adbd97 100644 --- a/apps/server/src/scheduledTasks/Schedule.ts +++ b/apps/server/src/scheduledTasks/Schedule.ts @@ -4,7 +4,7 @@ import * as Option from "effect/Option"; const MINUTE_MS = 60_000; -function parseTimeOfDay(value: string): { hour: number; minute: number } | null { +export function parseTimeOfDay(value: string): { hour: number; minute: number } | null { const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value.trim()); if (!match) return null; return { hour: Number(match[1]), minute: Number(match[2]) }; diff --git a/apps/server/src/scheduledTasks/webhookRoute.test.ts b/apps/server/src/scheduledTasks/webhookRoute.test.ts index ace3d93b9ac39..7fb2552a56074 100644 --- a/apps/server/src/scheduledTasks/webhookRoute.test.ts +++ b/apps/server/src/scheduledTasks/webhookRoute.test.ts @@ -31,6 +31,8 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as RelayDeliveryProof from "./RelayDeliveryProof.ts"; import { WEBHOOK_MAX_BODY_BYTES } from "./webhookRoute.ts"; import * as WebhookRoute from "./webhookRoute.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as Workflows from "../workflows/Workflows.ts"; class WebhookTestApi extends HttpApi.make("environment").add(EnvironmentHttpApi.groups.webhooks) {} @@ -70,6 +72,15 @@ const relayProof = Effect.fn("relayProof")(function* (claims: { }).pipe(Effect.provide(PlatformNodeCrypto.layerSignature)); }); +const workflowDeliveries: Array[0]> = []; +const hooks = Layer.mock(Workflows.Workflows)({ + deliver: (delivery) => + Effect.sync(() => { + workflowDeliveries.push(delivery); + return delivery.token === "tok" ? Option.some({ runId: "run-1" }) : Option.none(); + }), +}); + const handlerFor = ( trigger: ( request: WebhookTriggerRequest, @@ -81,6 +92,7 @@ const handlerFor = ( Layer.provide(WebhookRoute.layer), Layer.provide(RelayDeliveryProof.layer), Layer.provide(Layer.mock(ScheduledTaskService)({ triggerWebhook: trigger })), + Layer.provide([hooks, ManagedPolicy.layerTest()]), Layer.provide( Layer.mock(ServerSecretStore.ServerSecretStore)({ get: (name) => @@ -114,6 +126,30 @@ const post = ( ) => new Request(`http://env.local${path}`, { method: "POST", body, headers }); describe("webhook route", () => { + it.live("a workflow's hook starts a run and never reaches the scheduled tasks", () => + Effect.gen(function* () { + let tasks = 0; + const { handler, dispose } = handlerFor(() => { + tasks += 1; + return Effect.succeed({ _tag: "not_found" }); + }); + const send = (token: string) => + Effect.promise(() => + handler(post(`/api/hooks/wf-inbound.push/${token}?a=1`, "hello", { "X-Delivery": "d1" })), + ); + const accepted = yield* send("tok"); + expect(accepted.status).toBe(202); + expect(yield* Effect.promise(() => accepted.json())).toEqual({ runId: "run-1" }); + expect((yield* send("wrong")).status).toBe(404); + expect(tasks).toBe(0); + expect(workflowDeliveries[0]).toMatchObject({ + hookId: "wf-inbound.push", + request: { method: "POST", query: "a=1", body: "hello", headers: { "x-delivery": "d1" } }, + }); + yield* Effect.promise(dispose); + }), + ); + it.live("trusts the relay's delivery id and receive time only with its signed proof", () => Effect.gen(function* () { const received: Array = []; diff --git a/apps/server/src/scheduledTasks/webhookRoute.ts b/apps/server/src/scheduledTasks/webhookRoute.ts index a7e0c512cbe41..e1650219eb598 100644 --- a/apps/server/src/scheduledTasks/webhookRoute.ts +++ b/apps/server/src/scheduledTasks/webhookRoute.ts @@ -2,6 +2,7 @@ import { EnvironmentHttpApi } from "@t3tools/contracts"; import * as ByteSize from "effect/ByteSize"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; +import * as Result from "effect/Result"; import * as Tracer from "effect/Tracer"; import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"; import type * as HttpServerRequest from "effect/http/HttpServerRequest"; @@ -11,6 +12,8 @@ import { withRelayClientTracing } from "@t3tools/shared/relayTracing"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as Metrics from "../observability/Metrics.ts"; +import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; +import * as Workflows from "../workflows/Workflows.ts"; import * as RelayDeliveryProof from "./RelayDeliveryProof.ts"; import * as ScheduledTaskService from "./ScheduledTaskService.ts"; @@ -37,6 +40,8 @@ export const layer = HttpApiBuilder.group( Effect.fnUntraced(function* (handlers) { const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService; const relayDeliveryProof = yield* RelayDeliveryProof.RelayDeliveryProof; + const workflows = yield* Workflows.Workflows; + const managedPolicy = yield* ManagedPolicy.ManagedPolicy; /** * The endpoint is raw so the signature is checked over the exact body * bytes; the service checks the token and signature. @@ -95,6 +100,39 @@ export const layer = HttpApiBuilder.group( const relayParent = Option.isSome(relay) ? HttpTraceContext.fromHeaders(request.headers) : Option.none(); + if (params.hookId.startsWith(Workflows.HOOK_PREFIX)) { + if (ManagedPolicy.deniedBy(managedPolicy, "webhookTasks") !== undefined) { + return json(403, { error: "blocked_by_policy" }, "blocked_by_policy"); + } + // Answered only once the run is stored, so a sender that hears nothing may send again. + const started = yield* workflows + .deliver({ + hookId: params.hookId, + token: params.token, + request: { + method: request.method, + headers, + query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1), + body: new TextDecoder().decode(body.value), + }, + ...(relayDeliveryId ? { deliveryId: `relay:${relayDeliveryId}` } : {}), + }) + .pipe(Effect.result); + if (Result.isFailure(started)) { + if (started.failure._tag === "WorkflowInputError") { + return json( + 400, + { error: "invalid_request", problem: started.failure.problem }, + "invalid", + ); + } + yield* Effect.logWarning("Workflow hook delivery failed", { hookId: params.hookId }); + return json(500, { error: "internal_error" }, "error"); + } + return Option.isNone(started.success) + ? json(404, { error: "hook_not_found" }, "not_found") + : json(202, { runId: started.success.value.runId }, "accepted"); + } const result = yield* scheduledTasks .triggerWebhook({ hookId: params.hookId, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 8e0a2ea2f655f..68f32f4ecf0a9 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -227,6 +227,7 @@ import * as UsageService from "./usage/UsageService.ts"; import * as CodexUsageHistory from "./usage/CodexUsageHistory.ts"; import * as RuntimeLayer from "./orchestration-v2/runtimeLayer.ts"; import * as ThreadViewers from "./orchestration-v2/ThreadViewers.ts"; +import * as WorkflowForge from "./workflows/WorkflowForge.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts"; @@ -638,6 +639,13 @@ const layerTaskFolders = TaskFolders.layer.pipe( ); const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe( + Layer.provide( + WorkflowForge.layer.pipe( + Layer.provide(layerIssueService), + Layer.provide(layerPullRequestService), + Layer.provide(RuntimeLayer.layerProjectService), + ), + ), Layer.provide(UsageLimitSources.layerResetFallback), Layer.provide(layerTaskFolders), Layer.provide(layerScheduledTaskWebhookOrigin), @@ -766,9 +774,9 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( ReplayMarkers.layer, Layer.effectDiscard(ProjectSettingsOverrideSweep.sweep), ).pipe( - // One hub, which the feeders above publish to and future consumers read. - Layer.provideMerge(MilestoneHub.layer), Layer.provideMerge(layerOrchestrationApplication), + // One hub, which the feeders above and the workflow store inside the runtime publish to. + Layer.provideMerge(MilestoneHub.layer), Layer.provideMerge(layerTaskFolders), Layer.provideMerge(RuntimeLayer.layerEventInfrastructure), Layer.provideMerge(Layer.merge(ProjectStore.layer, ThreadSearch.layer)), diff --git a/apps/server/src/workflows/WorkflowAgentLinks.test.ts b/apps/server/src/workflows/WorkflowAgentLinks.test.ts new file mode 100644 index 0000000000000..92b7a4f7b2fff --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgentLinks.test.ts @@ -0,0 +1,292 @@ +import { EnvironmentId, OrchestratorMcpFailure } from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; + +import * as PeerLinks from "../peer/PeerLinks.ts"; +import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import * as WorkflowAgentLinks from "./WorkflowAgentLinks.ts"; + +const isFailure = Schema.is(OrchestratorMcpFailure); + +interface Call { + readonly environmentId: string; + readonly tool: string; + readonly arguments: Record; + readonly runtimeMode: string; +} + +/** The other environment, played by the test: each tool answers from a list, in order. */ +const peer = (answers: Record>, enabled = true) => { + const calls: Array = []; + const left = new Map(Object.entries(answers).map(([tool, list]) => [tool, [...list]])); + const layer = Layer.merge( + Layer.succeed( + PeerMcpClient.PeerMcpClient, + PeerMcpClient.PeerMcpClient.of({ + call: (input) => + Effect.suspend(() => { + calls.push({ + environmentId: input.environmentId, + tool: input.tool, + arguments: input.arguments, + runtimeMode: input.limits.runtimeMode, + }); + const answer = left.get(input.tool)?.shift(); + return isFailure(answer) ? Effect.fail(answer) : Effect.succeed(answer as never); + }), + }), + ), + Layer.mock(PeerLinks.PeerLinks)({ enabled: Effect.succeed(enabled) }), + ); + return { calls, layer }; +}; + +const input = { + key: "run-1/write/0", + origin: { runId: "run-1", workflow: "fix", step: "write" }, + title: "fix: write", + prompt: "Write the fix.", + outputSchema: { type: "object" }, + model: undefined, + project: "/work/app", + environment: "env-b", + thread: undefined, +}; +const run = (status: string) => ({ recentRuns: [{ runId: "turn-1", status }], items: [] }); +const waited = { threadId: "thread-1", runId: "turn-1", status: "idle" }; + +it.effect("starts a thread there by the project's folder, with the step's key as the request", () => + Effect.gen(function* () { + const there = peer({ + t3_project_list: [ + { projects: [{ id: "p-other", workspaceRoot: "/work/other" }], nextCursor: 1 }, + { projects: [{ id: "p-app", workspaceRoot: "/work/app" }], nextCursor: null }, + ], + t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], + }); + const options = { + workspace: { type: "worktree", baseRef: "origin/main", startFromOrigin: true }, + runtimeMode: "auto-accept-edits", + } as const; + const [turn, continued] = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + Effect.all([ + links.start( + { ...input, launch: options }, + "env-b", + "workflow:k", + EnvironmentId.make("env-a"), + ), + // A thread keeps how it started. + links + .start( + { ...input, thread: "thread-1", launch: options }, + "env-b", + "workflow:c", + EnvironmentId.make("env-a"), + ) + .pipe(Effect.flip), + ]), + ), + there.layer, + ); + assert.deepStrictEqual(turn, { threadId: "thread-1", turnId: "turn-1", environment: "env-b" }); + assert.include(continued.reason, "A continued `thread` keeps how it started"); + const launch = there.calls.at(-1); + assert.deepStrictEqual(launch?.arguments, { + projectId: "p-app", + title: "fix: write", + runtimeMode: "auto-accept-edits", + workspaceStrategy: { type: "worktree", baseRef: "origin/main", startFromOrigin: true }, + message: "Write the fix.", + outputSchema: { type: "object" }, + clientRequestId: "workflow:k", + workflowRun: { environmentId: "env-a", runId: "run-1", workflow: "fix", step: "write" }, + }); + // The link's own access is the ceiling, not a mode narrower than it. + assert.equal(launch?.runtimeMode, "full-access"); + }), +); + +it.effect("registers a folder that is not a project there yet", () => + Effect.gen(function* () { + const there = peer({ + t3_project_list: [{ projects: [], nextCursor: null }], + t3_project_create: [{ id: "p-new", workspaceRoot: "/work/app" }], + t3_thread_launch: [{ threadId: "thread-1", runId: "turn-1" }], + }); + yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")), + ), + there.layer, + ); + assert.deepStrictEqual( + there.calls.map((call) => [call.tool, call.arguments.projectId ?? call.arguments.title]), + [ + ["t3_project_list", undefined], + ["t3_project_create", "app"], + ["t3_thread_launch", "p-new"], + ], + ); + }), +); + +it.effect("does not start anything while linked environments is off", () => + Effect.gen(function* () { + const there = peer({}, false); + const error = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.start(input, "env-b", "workflow:k", EnvironmentId.make("env-a")), + ), + there.layer, + ).pipe(Effect.flip); + assert.match(error.reason, /Linked environments is off/); + assert.deepStrictEqual(there.calls, []); + }), +); + +it.effect("waits in pieces, rides out a dropped route, and returns the output and reply", () => + Effect.gen(function* () { + const there = peer({ + t3_thread_wait: [ + { ...waited, timedOut: true }, + new OrchestratorMcpFailure({ code: "orchestration_error", message: "unreachable" }), + { ...waited, timedOut: false, output: { branch: "fix/1" } }, + ], + t3_thread_read: [ + run("completed"), + { + recentRuns: [], + hasMore: false, + nextPosition: null, + items: [ + { type: "assistant_message", runId: "turn-0", text: "earlier", textTruncated: false }, + { + type: "assistant_message", + runId: "turn-1", + itemId: "item-9", + text: "Done, ", + textTruncated: true, + nextTextOffset: 6, + }, + ], + }, + { recentRuns: [], items: [{ text: "pushed.", textTruncated: false }] }, + ], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"), + ), + there.layer, + ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + assert.deepStrictEqual(result, { + ending: "completed", + detail: "", + reply: "Done, pushed.", + output: { branch: "fix/1" }, + }); + assert.equal(there.calls.filter((call) => call.tool === "t3_thread_wait").length, 3); + }), +); + +it.effect("a turn someone stopped there is stopped, and a refused link fails at once", () => + Effect.gen(function* () { + const stopped = peer({ + t3_thread_wait: [{ ...waited, timedOut: false }], + t3_thread_read: [run("interrupted")], + t3_thread_interrupt: [{ threadId: "thread-1", runId: "turn-1", status: "interrupted" }], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"), + ), + stopped.layer, + ); + assert.deepStrictEqual(result, { ending: "stopped", detail: "interrupted", reply: "" }); + // Stopping names the step's turn, so a person's turn on that thread keeps going. + yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.interrupt("thread-1", "env-b", "turn-1"), + ), + stopped.layer, + ); + assert.deepInclude(stopped.calls.at(-1)?.arguments, { threadId: "thread-1", runId: "turn-1" }); + + const revoked = peer({ + t3_thread_wait: [ + new OrchestratorMcpFailure({ code: "capability_denied", message: "link revoked" }), + ], + }); + const error = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b"), + ), + revoked.layer, + ).pipe(Effect.flip); + assert.match(error.reason, /link revoked/); + assert.equal(revoked.calls.length, 1); + }), +); + +it.effect("a turn that ended without its result is waited past until a later turn gives it", () => + Effect.gen(function* () { + const there = peer({ + t3_thread_wait: [ + // The turn ended. The agent is waiting to be woken, and has submitted nothing. + { ...waited, timedOut: false }, + // Quiet for five minutes, in pieces. A turn that woke in between is under way... + ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })), + // ...so the wait starts over, and that turn submits. + { ...waited, timedOut: false, output: { head: "abc" } }, + ], + t3_thread_read: [ + run("completed"), + { recentRuns: [{ runId: "turn-2", status: "running" }], items: [] }, + { recentRuns: [], hasMore: false, nextPosition: null, items: [] }, + ], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", { + quiet: Duration.minutes(5), + }), + ), + there.layer, + ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + assert.deepStrictEqual(result.output, { head: "abc" }); + const waits = there.calls.filter((call) => call.tool === "t3_thread_wait"); + assert.isTrue(waits.slice(1).every((call) => call.arguments.untilOutput === true)); + }), +); + +it.effect("a thread that stays quiet gives the turn back without a result", () => + Effect.gen(function* () { + const there = peer({ + t3_thread_wait: [ + { ...waited, timedOut: false }, + ...Array.from({ length: 6 }, () => ({ ...waited, timedOut: true })), + ], + t3_thread_read: [ + run("completed"), + // Nothing has run since the turn the step knows. + run("completed"), + { recentRuns: [], hasMore: false, nextPosition: null, items: [] }, + ], + }); + const result = yield* Effect.provide( + Effect.flatMap(WorkflowAgentLinks.make, (links) => + links.result({ threadId: "thread-1", turnId: "turn-1" }, "env-b", { + quiet: Duration.minutes(5), + }), + ), + there.layer, + ).pipe(Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + assert.deepStrictEqual(result, { ending: "completed", detail: "", reply: "" }); + }), +); diff --git a/apps/server/src/workflows/WorkflowAgentLinks.ts b/apps/server/src/workflows/WorkflowAgentLinks.ts new file mode 100644 index 0000000000000..6a0836fc0162c --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgentLinks.ts @@ -0,0 +1,313 @@ +// Agent steps in a linked environment: the same three operations, as that environment's T3 tools. +import { + type EnvironmentId, + OrchestratorMcpFailure, + OrchestratorMcpThreadInterruptResult, + OrchestratorMcpThreadReadResult, + OrchestratorMcpThreadSendResult, + OrchestratorMcpThreadWaitResult, +} from "@t3tools/contracts"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; +import type * as Schema from "effect/Schema"; + +import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts"; +import * as PeerLinks from "../peer/PeerLinks.ts"; +import * as PeerMcpClient from "../peer/PeerMcpClient.ts"; +import { + type AgentResult, + type AgentTurn, + isProjectPath, + launchOnContinue, + WorkflowAgentError, + type WorkflowAgents, +} from "./WorkflowAgents.ts"; + +// A run acts for whoever owns this environment, not for an agent with modes of its own, so the +// only ceiling on what it starts there is the access the link was paired with. +const LIMITS = { runtimeMode: "full-access", interactionMode: "default" } as const; + +// T3 Connect's edge drops a request that is idle for about 100 s, so a wait goes out in pieces. +const WAIT_PIECE = Duration.seconds(50); + +/** The link is gone or the thread is: asking again cannot help. */ +const isFinal = (error: OrchestratorMcpFailure) => + error.code === "capability_denied" || + error.code === "thread_not_found" || + error.code === "run_not_found" || + error.code === "invalid_request"; + +// The other machine asleep or a dropped route is worth a few more tries before the run pauses. +const retried = { schedule: Schedule.exponential("2 seconds"), times: 5 }; + +type Service = WorkflowAgents["Service"]; + +export const make = Effect.gen(function* () { + const peers = yield* PeerMcpClient.PeerMcpClient; + const links = yield* PeerLinks.PeerLinks; + + const call = >( + environment: string, + tool: string, + success: S, + args: Record, + ) => + peers + .call({ + environmentId: environment as EnvironmentId, + tool, + arguments: args, + limits: LIMITS, + success, + }) + .pipe( + Effect.retry({ ...retried, while: (error) => !isFinal(error) }), + Effect.mapError( + (error) => + new WorkflowAgentError({ + reason: `Environment ${environment} refused ${tool}: ${error.message}`, + }), + ), + ); + + const listed = Effect.fn("WorkflowAgentLinks.listed")(function* ( + environment: string, + path: string, + ) { + let cursor: number | null = 0; + while (cursor !== null) { + const page: Schema.Schema.Type = + yield* call( + environment, + "t3_project_list", + ProjectToolkit.tools.t3_project_list.successSchema, + { cursor, limit: 100 }, + ); + const found = page.projects.find((project) => project.workspaceRoot === path); + if (found !== undefined) return found.id; + cursor = page.nextCursor; + } + return undefined; + }); + + /** + * The project at a folder there. A machine made for one run has the folder and no project yet, + * so a folder that is not one is registered. Two steps may do that at once; the one that is + * refused finds the other's. + */ + const projectAt = Effect.fn("WorkflowAgentLinks.projectAt")(function* ( + environment: string, + path: string, + ) { + const known = yield* listed(environment, path); + if (known !== undefined) return known; + const title = path.split("/").findLast((part) => part.length > 0) ?? path; + const created = yield* call( + environment, + "t3_project_create", + ProjectToolkit.tools.t3_project_create.successSchema, + { title, workspaceRoot: path }, + ).pipe(Effect.result); + if (Result.isSuccess(created)) return created.success.id; + return (yield* listed(environment, path)) ?? (yield* created.failure); + }); + + /** The whole text of the run's last assistant message. */ + const reply = Effect.fn("WorkflowAgentLinks.reply")(function* ( + turn: AgentTurn, + environment: string, + ) { + let last: OrchestratorMcpThreadReadResult["items"][number] | undefined; + let afterPosition: number | undefined; + while (true) { + const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + view: "messages", + limit: 100, + ...(afterPosition === undefined ? {} : { afterPosition }), + }); + last = + read.items.findLast( + (item) => item.type === "assistant_message" && item.runId === turn.turnId, + ) ?? last; + if (!read.hasMore || read.nextPosition === null) break; + afterPosition = read.nextPosition; + } + if (last === undefined) return ""; + let text = last.text ?? ""; + let textOffset = last.textTruncated ? (last.nextTextOffset ?? null) : null; + while (textOffset !== null) { + const rest = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + itemId: last.itemId, + textOffset, + maxCharsPerItem: 50_000, + }); + const part = rest.items[0]; + if (part === undefined) break; + text += part.text ?? ""; + textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null; + } + return text; + }); + + const start = Effect.fn("WorkflowAgentLinks.start")(function* ( + input: Parameters[0], + environment: string, + requestId: string, + here: EnvironmentId, + ) { + if (!(yield* links.enabled)) { + return yield* new WorkflowAgentError({ + reason: + "Linked environments is off on this machine, so an agent step cannot run in another one. Turn it on in Settings → Labs.", + }); + } + const outputSchema = + input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }; + if (input.thread !== undefined) { + if (input.launch !== undefined) return yield* launchOnContinue; + const sent = yield* call(environment, "t3_thread_send", OrchestratorMcpThreadSendResult, { + threadId: input.thread, + message: input.prompt, + mode: "queue", + ...outputSchema, + clientRequestId: requestId, + }); + return { threadId: sent.threadId, turnId: sent.runId, environment }; + } + if (input.project === undefined) { + return yield* new WorkflowAgentError({ + reason: "An agent step needs a `project` to start in, or a `thread` to continue.", + }); + } + const projectId = isProjectPath(input.project) + ? yield* projectAt(environment, input.project) + : input.project; + const launched = yield* call( + environment, + "t3_thread_launch", + ProjectToolkit.tools.t3_thread_launch.successSchema, + { + projectId, + title: input.title, + ...(input.model === undefined ? {} : { modelSelection: input.model }), + ...(input.launch?.runtimeMode === undefined + ? {} + : { runtimeMode: input.launch.runtimeMode }), + ...(input.launch?.interactionMode === undefined + ? {} + : { interactionMode: input.launch.interactionMode }), + ...(input.launch?.workspace === undefined + ? {} + : { workspaceStrategy: input.launch.workspace }), + message: input.prompt, + ...outputSchema, + clientRequestId: requestId, + // The thread there says which run it is a step of, and where that run lives. + workflowRun: { environmentId: here, ...input.origin }, + }, + ); + if (launched.runId === null) { + return yield* new WorkflowAgentError({ + reason: `Thread ${launched.threadId} in ${environment} started without a turn for its first message.`, + }); + } + return { threadId: launched.threadId, turnId: launched.runId, environment }; + }); + + const result = Effect.fn("WorkflowAgentLinks.result")(function* ( + turn: AgentTurn, + environment: string, + options?: { readonly quiet?: Duration.Duration | undefined }, + ): Effect.fn.Return { + const ended = new Set(["completed", "failed", "interrupted", "cancelled", "rolled_back"]); + /** The result a later turn submits, or nothing once the thread has been quiet. */ + const owed = Effect.fn("WorkflowAgentLinks.owed")(function* (quiet: Duration.Duration) { + let left = Duration.toMillis(quiet); + // The newest turn already seen to end without the result, so quiet is not restarted by it. + let counted = turn.turnId; + while (true) { + const piece = Math.min(left, Duration.toMillis(WAIT_PIECE)); + const waited = yield* call(environment, "t3_thread_wait", OrchestratorMcpThreadWaitResult, { + threadId: turn.threadId, + runId: turn.turnId, + untilOutput: true, + timeoutMs: piece, + }); + if (waited.output !== undefined) return Option.some(waited.output); + // An environment that does not know `untilOutput` answers at once: nothing to wait on. + if (!waited.timedOut) return Option.none(); + left -= piece; + if (left > 0) continue; + const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + limit: 1, + runLimit: 1, + }); + const latest = read.recentRuns[0]; + if (latest === undefined || latest.runId === counted) return Option.none(); + // Quiet is counted from the thread's last turn: one under way, or one not yet counted. + if (ended.has(latest.status)) counted = latest.runId; + left = Duration.toMillis(quiet); + } + }); + while (true) { + const waited = yield* call(environment, "t3_thread_wait", OrchestratorMcpThreadWaitResult, { + threadId: turn.threadId, + runId: turn.turnId, + timeoutMs: Duration.toMillis(WAIT_PIECE), + }); + if (waited.timedOut) continue; + const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, { + threadId: turn.threadId, + limit: 1, + runLimit: 50, + }); + const status = read.recentRuns.find((run) => run.runId === turn.turnId)?.status; + if (status === undefined) { + return yield* new WorkflowAgentError({ + reason: `Thread ${turn.threadId} in ${environment} no longer lists turn ${turn.turnId}.`, + }); + } + if (status === "completed") { + const output = + waited.output !== undefined || options?.quiet === undefined + ? Option.fromUndefinedOr(waited.output) + : yield* owed(options.quiet); + return { + ending: "completed", + detail: "", + reply: yield* reply(turn, environment), + ...(Option.isNone(output) ? {} : { output: output.value }), + }; + } + if ( + status === "failed" || + status === "interrupted" || + status === "cancelled" || + status === "rolled_back" + ) { + return { ending: status === "failed" ? "failed" : "stopped", detail: status, reply: "" }; + } + // The wait answered for a turn that has not ended. Asking again at once would spin. + yield* Effect.sleep("5 seconds"); + } + }); + + const interrupt = (threadId: string, environment: string, runId?: string) => + Effect.map( + call(environment, "t3_thread_interrupt", OrchestratorMcpThreadInterruptResult, { + threadId, + ...(runId === undefined ? {} : { runId }), + reason: "Its workflow run was cancelled", + }), + (stopped): "stopped" | "ended" => + stopped.status === "interrupt_requested" ? "stopped" : "ended", + ); + + return { start, result, interrupt }; +}); diff --git a/apps/server/src/workflows/WorkflowAgentThreads.ts b/apps/server/src/workflows/WorkflowAgentThreads.ts new file mode 100644 index 0000000000000..ce4a7510b88c0 --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgentThreads.ts @@ -0,0 +1,335 @@ +// Agent steps as threads: a step's turn is an ordinary thread turn that was asked for a result. +import { + CommandId, + MessageId, + type ModelSelection, + ProjectId, + ProviderInstanceId, + type RunId, + ThreadId, +} from "@t3tools/contracts"; +import { subagentResultForRun } from "@t3tools/provider-core/server/subagentProjection"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; +import * as Digest from "effect/crypto/Digest"; +import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Hex from "effect/encoding/Hex"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as ThreadIssueService from "../orchestration-v2/ThreadIssueService.ts"; +import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as WorkflowAgentLinks from "./WorkflowAgentLinks.ts"; +import { + isProjectPath, + launchOnContinue, + WorkflowAgentError, + WorkflowAgents, +} from "./WorkflowAgents.ts"; +import { noteReference } from "./runReferences.ts"; +import { type IssueAddress, linkedPullRequestReferences, WorkflowForge } from "./WorkflowForge.ts"; + +// A turn can run for hours. Each look is bounded so a wait that lost its event is asked again. +const WAIT_SLICE = Duration.minutes(10); + +const failed = (reason: string) => (cause: unknown) => + new WorkflowAgentError({ + reason: `${reason}: ${cause instanceof Error ? cause.message : String(cause)}`, + }); + +const make = Effect.gen(function* () { + const threads = yield* ThreadManagement.ThreadManagementService; + const launches = yield* ThreadLaunch.ThreadLaunchService; + const projects = yield* ProjectService.ProjectService; + const providers = yield* ProviderRegistry.ProviderRegistry; + const settings = yield* ServerSettings.ServerSettingsService; + const digest = yield* Digest.Digest; + const linked = yield* WorkflowAgentLinks.make; + const forge = yield* WorkflowForge; + const threadIssues = yield* ThreadIssueService.ThreadIssueService; + // A tracker that is down must not cost the step its agent. + const showIssue = (issue: IssueAddress | undefined, threadId: string) => + issue === undefined + ? Effect.void + : forge.issues.read(issue).pipe( + Effect.flatMap((detail) => + threadIssues.link({ + threadId: ThreadId.make(threadId), + ref: { + projectId: detail.projectId, + tracker: detail.tracker, + host: detail.host, + scope: detail.scope, + key: detail.key, + }, + url: detail.url, + displayKey: detail.displayKey, + title: detail.title, + source: "agent", + }), + ), + Effect.catch((error) => + Effect.logWarning("Could not link a workflow agent's thread to its issue", { + threadId, + reason: error.message, + }), + ), + ); + // What the agent opened or linked while it worked is part of what its step touched. + const noteLinked = (threadId: ThreadId, sinceMillis: number | undefined) => + threads.getThreadShell(threadId).pipe( + Effect.flatMap((shell) => + shell === null + ? Effect.void + : Effect.forEach(linkedPullRequestReferences(shell, sinceMillis), noteReference, { + discard: true, + }), + ), + Effect.ignore, + ); + const here = yield* ServerEnvironment.ServerEnvironment.pipe( + Effect.flatMap((environment) => environment.getEnvironmentId), + ); + /** The linked environment a step names, or nothing when it names this one. */ + const elsewhere = (environment: string | undefined) => + environment === here ? undefined : environment; + + // Thread, message and command ids all derive from the step's key, so a start that is asked for + // again after a crash finds the turn it already started. + const idOf = Effect.fn("WorkflowAgentThreads.idOf")(function* (key: string) { + const hash = yield* digest + .digest(Digest.sha256, new TextEncoder().encode(key)) + .pipe(Effect.mapError(failed("Could not derive the turn's id"))); + return `workflow:${Hex.encode(hash)}`; + }); + + const projectDefaults = Effect.fn("WorkflowAgentThreads.projectDefaults")(function* ( + projectId: ProjectId, + ) { + const project = yield* projects + .getById(projectId) + .pipe(Effect.mapError(failed("Could not read the project"))); + if (Option.isNone(project)) { + return yield* new WorkflowAgentError({ reason: `Project ${projectId} was not found.` }); + } + const current = yield* settings.getSettings.pipe( + Effect.mapError(failed("Could not read settings")), + ); + return resolveProjectSettings(current, projectId, project.value).settings; + }); + + const projectIdOf = Effect.fn("WorkflowAgentThreads.projectIdOf")(function* (project: string) { + if (!isProjectPath(project)) return ProjectId.make(project); + const found = yield* projects + .getByWorkspaceRoot(project) + .pipe(Effect.mapError(failed("Could not read the project"))); + if (Option.isNone(found)) { + return yield* new WorkflowAgentError({ + reason: `No project is registered at ${project}.`, + }); + } + return found.value.id; + }); + + return WorkflowAgents.of({ + start: Effect.fn("WorkflowAgentThreads.start")(function* (input) { + const id = yield* idOf(input.key); + const environment = elsewhere(input.environment); + if (environment !== undefined) return yield* linked.start(input, environment, id, here); + const commandId = CommandId.make(id); + const messageId = MessageId.make(id); + const outputSchema = + input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }; + + if (input.thread !== undefined) { + if (input.launch !== undefined) return yield* launchOnContinue; + const threadId = ThreadId.make(input.thread); + const shell = yield* threads + .getThreadShell(threadId) + .pipe(Effect.mapError(failed("Could not read the thread to continue"))); + if (shell === null || shell.deletedAt !== null) { + return yield* new WorkflowAgentError({ + reason: `Thread ${input.thread} no longer exists, so it cannot be continued.`, + }); + } + const sent = yield* threads + .sendToThread({ + projectId: shell.projectId, + commandId, + threadId, + messageId, + text: input.prompt, + attachments: [], + mode: "queue", + ...outputSchema, + createdBy: "system", + creationSource: "server", + }) + .pipe(Effect.mapError(failed("Could not send to the thread"))); + yield* showIssue(input.issue, threadId); + return { threadId, turnId: sent.run.id }; + } + + if (input.project === undefined) { + return yield* new WorkflowAgentError({ + reason: "An agent step needs a `project` to start in, or a `thread` to continue.", + }); + } + const projectId = yield* projectIdOf(input.project); + const defaults = yield* projectDefaults(projectId); + const modelSelection: ModelSelection | undefined = + input.model === undefined + ? (resolveNewThreadModelSelection({ + defaultSelection: defaults.defaultModelSelection, + fallbackSelection: defaults.fallbackModelSelection, + providers: yield* providers.getProviders, + settings: defaults, + projectId, + now: DateTime.toEpochMillis(yield* DateTime.now), + }).selection ?? undefined) + : { + instanceId: ProviderInstanceId.make(input.model.instanceId), + model: input.model.model, + ...(input.model.options === undefined ? {} : { options: input.model.options }), + }; + if (modelSelection === undefined) { + return yield* new WorkflowAgentError({ + reason: `Project ${input.project} has no default model. Give the agent step a \`model\`.`, + }); + } + const launched = yield* launches + .launch({ + commandId, + threadId: ThreadId.make(id), + projectId, + title: input.title, + modelSelection, + runtimeMode: input.launch?.runtimeMode ?? defaults.defaultRuntimeMode, + interactionMode: input.launch?.interactionMode ?? "default", + workspaceStrategy: input.launch?.workspace ?? { type: "root" }, + initialMessage: { messageId, text: input.prompt, attachments: [], ...outputSchema }, + createdBy: "system", + creationSource: "server", + workflowRun: { environmentId: here, ...input.origin }, + }) + .pipe(Effect.mapError(failed("Could not start the thread"))); + const run = launched.projection.runs.find( + (candidate) => candidate.userMessageId === messageId, + ); + if (run === undefined) { + return yield* new WorkflowAgentError({ + reason: `Thread ${launched.threadId} started without a turn for its first message.`, + }); + } + yield* showIssue(input.issue, launched.threadId); + return { threadId: launched.threadId, turnId: run.id }; + }), + result: Effect.fn("WorkflowAgentThreads.result")(function* (turn, options) { + const environment = elsewhere(turn.environment); + if (environment !== undefined) return yield* linked.result(turn, environment, options); + const threadId = ThreadId.make(turn.threadId); + const shell = yield* threads + .getThreadShell(threadId) + .pipe(Effect.mapError(failed("Could not read the thread"))); + if (shell === null) { + return yield* new WorkflowAgentError({ + reason: `Thread ${turn.threadId} no longer exists.`, + }); + } + // The newest turn already seen to end without the result, so quiet is not restarted by it. + let quietSince = -1; + while (true) { + const waited = yield* threads + .waitForThread({ + projectId: shell.projectId, + threadId, + runId: turn.turnId as RunId, + timeoutMs: Duration.toMillis(WAIT_SLICE), + }) + .pipe(Effect.mapError(failed("Could not wait for the turn"))); + let run = waited.run; + if (waited.timedOut || run === null) continue; + // The agent may have ended its turn to wait for something that will wake it. + const quiet = options?.quiet; + const owes = (candidate: NonNullable) => + candidate.status === "completed" && + candidate.outputSchema !== undefined && + candidate.output === undefined; + while (owes(run)) { + if (quiet === undefined) break; + const owed: ThreadManagement.ThreadManagementWaitResult = yield* threads + .waitForThread({ + projectId: shell.projectId, + threadId, + runId: run.id, + untilOutput: true, + timeoutMs: Duration.toMillis(quiet), + }) + .pipe(Effect.mapError(failed("Could not wait for the turn's result"))); + if (owed.run === null) break; + run = owed.run; + if (!owed.timedOut) continue; + // Quiet is counted from the thread's last turn, so one under way is waited out first. + const latest = yield* threads + .waitForThread({ + projectId: shell.projectId, + threadId, + timeoutMs: Duration.toMillis(WAIT_SLICE), + }) + .pipe(Effect.mapError(failed("Could not wait for the thread"))); + if (latest.run === null || latest.run.id === run.id) break; + if (!latest.timedOut && latest.run.ordinal <= quietSince) break; + quietSince = latest.timedOut ? quietSince : latest.run.ordinal; + } + yield* noteLinked(threadId, turn.startedAt); + if (run.status !== "completed") { + // Interrupted or cancelled is someone stopping it; the rest is the turn dying. + const ending = run.status === "failed" ? ("failed" as const) : ("stopped" as const); + return { ending, detail: run.status, reply: "" }; + } + const records = yield* threads + .getThreadRecords(threadId, ["messages", "turnItems", "providerTurns"]) + .pipe(Effect.mapError(failed("Could not read the turn's reply"))); + return { + ending: "completed" as const, + detail: "", + reply: subagentResultForRun(records, run).text, + ...(run.output === undefined ? {} : { output: run.output.value }), + }; + } + }), + interrupt: Effect.fn("WorkflowAgentThreads.interrupt")(function* (target) { + const environment = elsewhere(target.environment); + if (environment !== undefined) + return yield* linked.interrupt(target.threadId, environment, target.turnId); + const thread = target.threadId; + const threadId = ThreadId.make(thread); + const shell = yield* threads + .getThreadShell(threadId) + .pipe(Effect.mapError(failed("Could not read the thread"))); + if (shell === null) return "ended" as const; + const stopped = yield* threads + .interruptThread({ + projectId: shell.projectId, + threadId, + commandId: CommandId.make( + `workflow:interrupt:${thread}:${target.turnId ?? ""}:${yield* Clock.currentTimeMillis}`, + ), + reason: "Its workflow run was cancelled", + ...(target.turnId === undefined ? {} : { runId: target.turnId as RunId }), + }) + .pipe(Effect.mapError(failed("Could not stop the thread"))); + return stopped.type === "interrupt_requested" ? ("stopped" as const) : ("ended" as const); + }), + }); +}); + +export const layer = Layer.effect(WorkflowAgents, make); diff --git a/apps/server/src/workflows/WorkflowAgents.ts b/apps/server/src/workflows/WorkflowAgents.ts new file mode 100644 index 0000000000000..674b72c69aa3d --- /dev/null +++ b/apps/server/src/workflows/WorkflowAgents.ts @@ -0,0 +1,117 @@ +import type { + ModelSelection, + OrchestrationV2ThreadLaunchWorkspaceStrategy, + ProviderInteractionMode, + RuntimeMode, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import type * as Duration from "effect/Duration"; +import type * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import type { IssueAddress } from "./WorkflowForge.ts"; + +export class WorkflowAgentError extends Schema.TaggedError()( + "WorkflowAgentError", + { reason: Schema.String }, +) { + override get message(): string { + return this.reason; + } +} + +export interface AgentModel { + readonly instanceId: string; + readonly model: string; + /** The model's own options, such as reasoning effort, as `{ id, value }` pairs. */ + readonly options?: ModelSelection["options"]; +} + +/** How a new thread starts, as `t3_thread_launch` takes it. Unset fields follow the project. */ +export interface AgentLaunch { + /** Where its files are: the project's checkout by default, or a worktree of its own. */ + readonly workspace?: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined; + readonly runtimeMode?: RuntimeMode | undefined; + readonly interactionMode?: ProviderInteractionMode | undefined; +} + +export const AgentTurn = Schema.Struct({ + threadId: Schema.String, + turnId: Schema.String, + /** The linked environment the thread is in. Absent for this one. */ + environment: Schema.optional(Schema.String), + /** When the step's first turn started, which its time limit counts from. */ + startedAt: Schema.optional(Schema.Number), + /** Why no turn was started, for a step that takes that as an answer. The ids are then empty. */ + failed: Schema.optional(Schema.String), +}); +export type AgentTurn = typeof AgentTurn.Type; + +export const AgentResult = Schema.Struct({ + /** + * How the turn ended. `stopped` is someone ending it on purpose, which is not a reason to try + * again; `failed` is the turn dying underneath the agent. + */ + ending: Schema.Literals(["completed", "failed", "stopped"]), + detail: Schema.String, + reply: Schema.String, + /** What the agent submitted against the output schema, when it did. */ + output: Schema.optional(Schema.Json), +}); +export type AgentResult = typeof AgentResult.Type; + +/** What a continued thread says to options that only shape a new one. */ +export const launchOnContinue = new WorkflowAgentError({ + reason: + "`workspace`, `runtimeMode` and `interactionMode` shape a new thread. A continued `thread` keeps how it started.", +}); + +/** A project named by its folder instead of its id. */ +export const isProjectPath = (project: string) => project.startsWith("/"); + +/** Where agent steps run. The server implements it with threads; tests stand in for it. */ +export class WorkflowAgents extends Context.Service< + WorkflowAgents, + { + /** Start a turn. The same `key` is the same turn, however often it is asked for. */ + readonly start: (input: { + readonly key: string; + /** The run and step this turn is for, which a new thread is marked with. */ + readonly origin: { readonly runId: string; readonly workflow: string; readonly step: string }; + readonly title: string; + readonly prompt: string; + readonly outputSchema: Readonly> | undefined; + readonly model: AgentModel | undefined; + /** The project a new thread is made in: its id, or its folder. Not needed to continue `thread`. */ + readonly project: string | undefined; + /** The linked environment to run in. Absent for this one. */ + readonly environment: string | undefined; + /** Continue this thread instead of starting one. */ + readonly thread: string | undefined; + /** An issue the thread is about, which it is linked to. */ + readonly issue?: IssueAddress | undefined; + /** How a new thread starts. Refused with `thread`, which keeps how it started. */ + readonly launch?: AgentLaunch | undefined; + }) => Effect.Effect; + /** + * Wait for the turn to end and return what it produced. With `quiet`, a turn that ended + * without the output it owes is waited past: its agent may be waiting to be woken, and + * submits from a later turn. Only once the thread has done nothing for `quiet` is the turn + * returned without output. + */ + readonly result: ( + turn: AgentTurn, + options?: { readonly quiet?: Duration.Duration | undefined }, + ) => Effect.Effect; + /** + * Stop whatever the thread is doing, when its run is cancelled. `ended` when there was nothing + * to stop: the turn had already ended. + */ + readonly interrupt: (thread: { + readonly threadId: string; + readonly environment?: string | undefined; + /** The step's own turn. With it, a turn of someone else's on the same thread is left alone. */ + readonly turnId?: string | undefined; + }) => Effect.Effect<"stopped" | "ended", WorkflowAgentError>; + } +>()("t3/workflows/WorkflowAgents") {} diff --git a/apps/server/src/workflows/WorkflowEngine.ts b/apps/server/src/workflows/WorkflowEngine.ts new file mode 100644 index 0000000000000..77ff4cf0ada2e --- /dev/null +++ b/apps/server/src/workflows/WorkflowEngine.ts @@ -0,0 +1,1056 @@ +// The workflow service on Effect's workflow engine. Loaded only when workflows are enabled: the +// engine's modules are not worth their load time on a server that registers none. +import * as Cause from "effect/Cause"; +import { + ClusterWorkflowEngine, + EntityAddress, + EntityId, + EntityType, + MessageStorage, + Sharding, + SingleRunner, +} from "effect/cluster"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as PubSub from "effect/PubSub"; +import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; +import { DurableDeferred, WorkflowEngine } from "effect/workflow"; + +import { checkOutput, rejectionText } from "../orchestration-v2/runOutput.ts"; +import { isMissedFixedTimeRun, nextScheduledRunAt } from "../scheduledTasks/Schedule.ts"; +import { constantTimeEquals } from "../scheduledTasks/webhookVerification.ts"; +import { + END_STEP, + type EngineWorkflow, + engineTag, + engineWorkflow, + layerDefinition, + text, + wakeOf, + type Woke, + type WorkflowDefinition, +} from "./workflow.ts"; +import { issueReference, noteFor, stepReferences } from "./runReferences.ts"; +import { forStep, KeyValues, layerKeyValues, EngineLink, layerEngineLink } from "./stepServices.ts"; +import { WorkflowAgents } from "./WorkflowAgents.ts"; +import { + type Issue, + isSettled, + type PullRequest, + type PullRequestAddress, + type PullRequestWatch, + pullRequestReferenceOf, + standingOf, + unavailable, + WorkflowForge, +} from "./WorkflowForge.ts"; +import { + hookId as hookIdOf, + WorkflowInputError, + WorkflowNotRegisteredError, + WorkflowRunNotFoundError, + Workflows, +} from "./Workflows.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; + +const SWEEP_EVERY = Duration.seconds(15); +const LOOK_EVERY = Duration.minutes(1); +const LOOK_AT_MOST = 100; +const DEFAULT_SIGNAL_TTL = Duration.days(7); +const RESUME_LOOK_EVERY = Duration.millis(25); +const RESUME_LOOKS = 80; +const WATCH_SETTLE = Duration.millis(100); +const END_TRIES = 5; +// How long a cancelled run's cleanup rests after each failed try before the sweep tries again. +const END_AFTER = ["5 minutes", "20 minutes", "80 minutes", "5 hours"] as const; +// An ended run's engine journal only answers replays that will not come; the run's own rows stay. +const PRUNE_AFTER = Duration.hours(1); +const PRUNE_BATCH = 100; +// Delivery ids that common senders put on a request and keep when they send it again. +const DELIVERY_HEADERS = [ + "x-github-delivery", + "x-gitea-delivery", + "x-gitlab-event-uuid", + "linear-delivery", + "webhook-id", + "idempotency-key", +]; +const CANCEL_WAITS = Duration.seconds(30); +// Times of day are the server's own, as they are for scheduled tasks. +const localNow = DateTime.withCurrentZoneLocal(DateTime.nowInCurrentZone); + +const make = Effect.fn("WorkflowEngine.make")(function* ( + registered: ReadonlyArray, +) { + const store = yield* WorkflowStore.WorkflowStore; + const keyValues = yield* KeyValues; + const link = yield* EngineLink; + const trackers = Option.getOrElse(yield* Effect.serviceOption(WorkflowForge), () => unavailable); + const messages = yield* Effect.serviceOption(MessageStorage.MessageStorage); + const sharding = yield* Effect.serviceOption(Sharding.Sharding); + // The engine reads its own tables as BigInts. The rest of the server's queries must not. + const plain = + , A, E>(call: (...args: Args) => Effect.Effect) => + (...args: Args) => + call(...args).pipe(Effect.provideService(SqlClient.SafeIntegers, false)); + const forge = WorkflowForge.of({ + issues: { + list: plain(trackers.issues.list), + read: plain(trackers.issues.read), + comment: plain(trackers.issues.comment), + setState: plain(trackers.issues.setState), + create: plain(trackers.issues.create), + }, + pullRequests: { + list: plain(trackers.pullRequests.list), + read: plain(trackers.pullRequests.read), + comment: plain(trackers.pullRequests.comment), + act: plain(trackers.pullRequests.act), + }, + }); + const scope = yield* Scope.Scope; + const agents = yield* WorkflowAgents; + const stopTurn = plain(agents.interrupt); + const random = yield* SecureRandom.SecureRandom; + const digest = yield* Digest.Digest; + const context = yield* Effect.context(); + // The engine keeps 64-bit ids, which this SQLite client only reads when asked for BigInts. + const withEngine = (effect: Effect.Effect) => + effect.pipe( + Effect.provideContext(context), + Effect.provideService(SqlClient.SafeIntegers, true), + ); + const byTag = new Map(registered.map(([, engine]) => [engine._tag, engine] as const)); + const definitionByTag = new Map( + registered.map(([definition]) => [engineTag(definition), definition] as const), + ); + const latest = (name: string) => + registered + .filter(([definition]) => definition.name === name) + .toSorted(([left], [right]) => right.version - left.version)[0]; + + /** When the sweep resumes a paused run; undefined once it has used up its tries. */ + const resumesAt = (row: WorkflowStore.RunRow) => { + if (row.status !== "paused" || Number(row.held) === 1) return undefined; + const rest = definitionByTag.get(row.engine_tag)?.resumeAfter[Number(row.pauses) - 1]; + return rest === undefined + ? undefined + : DateTime.addDuration(DateTime.makeUnsafe(row.updated_at), Duration.fromInputUnsafe(rest)); + }; + const toRun = (row: WorkflowStore.RunRow): WorkflowStore.WorkflowRun => { + const resumes = resumesAt(row); + return toRunAt(row, resumes === undefined ? null : DateTime.formatIso(resumes)); + }; + const toRunAt = ( + row: WorkflowStore.RunRow, + resumes: string | null, + ): WorkflowStore.WorkflowRun => ({ + runId: row.run_id, + workflow: row.workflow, + version: Number(row.version), + title: row.title, + status: row.status, + detail: row.detail, + result: row.result_json === null ? null : WorkflowStore.jsonValue(row.result_json), + pauses: Number(row.pauses), + retired: row.ended_at === null && !byTag.has(row.engine_tag), + resumesAt: resumes, + parentRunId: row.parent_run_id, + parentStep: row.parent_wait, + startedAt: row.started_at, + updatedAt: row.updated_at, + endedAt: row.ended_at, + }); + const requireRun = Effect.fn("WorkflowEngine.requireRun")(function* (runId: string) { + const row = yield* store.run(runId); + if (row === undefined) return yield* new WorkflowRunNotFoundError({ runId }); + return row; + }); + const send = (wait: WorkflowStore.WaitRow, value: typeof Woke.Type) => + withEngine( + DurableDeferred.succeed(wakeOf(wait.name), { + token: wait.token as DurableDeferred.Token, + value, + }), + ); + // Runs being resumed now: until the engine has them, the sweep must not take them for paused. + const resuming = new Set(); + // The engine would replay a paused run for the wake and run its failed step again unasked. The + // claim keeps the value, and the resume sends it. + const wake = Effect.fnUntraced(function* (wait: WorkflowStore.WaitRow, value: typeof Woke.Type) { + if (resuming.has(wait.run_id) || (yield* store.run(wait.run_id))?.status === "paused") return; + yield* send(wait, value); + }); + + const start: Workflows["Service"]["start"] = Effect.fn("Workflows.start")( + function* (name, input, options) { + // A parent written against one version of a child must not get another one's payload. + const found = + options.version === undefined + ? latest(name) + : registered.find( + ([candidate]) => candidate.name === name && candidate.version === options.version, + ); + if (found === undefined) { + return yield* new WorkflowNotRegisteredError({ + workflow: name, + ...(options.version === undefined ? {} : { version: options.version }), + }); + } + const [definition, engine] = found; + // A key is one run of the workflow: the engine's own id also counts the version, so a + // start after a new version would otherwise begin the same work again. + const other = Effect.fnUntraced(function* (earlier: WorkflowStore.RunRow) { + if ( + options.parent !== undefined && + (earlier.parent_run_id !== options.parent.runId || + earlier.parent_wait !== options.parent.wait) + ) { + return yield* new WorkflowInputError({ + problem: `Run ${earlier.run_id} of ${name} was started by something else under this key, so it cannot be invoked. Give the invoke a key of its own.`, + }); + } + // A start cut off between its row and the engine left a run nothing executes. Executing + // one the engine has is a no-op. + const its = byTag.get(earlier.engine_tag); + if (earlier.ended_at === null && its !== undefined && earlier.input_json !== null) { + yield* withEngine( + its.execute( + { + idempotencyKey: earlier.idempotency_key, + input: WorkflowStore.jsonValue(earlier.input_json), + }, + { discard: true }, + ), + ); + } + return { runId: earlier.run_id }; + }); + const earlier = yield* store.runByKey(name, options.idempotencyKey); + // An ended run's journal may be pruned, so executing it again would start the work over. + if ( + earlier !== undefined && + (earlier.engine_tag !== engineTag(definition) || earlier.ended_at !== null) + ) { + return yield* other(earlier); + } + const payloadCodec = Schema.toCodecJson(definition.payload); + const encode = Schema.encodeUnknownEffect(payloadCodec); + const encoded = yield* encode(input).pipe( + Effect.mapError( + (error) => + new WorkflowInputError({ + problem: `The payload does not fit workflow ${name}: ${text(error)}`, + }), + ), + ); + const payload = { idempotencyKey: options.idempotencyKey, input: encoded as Schema.Json }; + // The row is written first, with who waits for it: the run's own first step writes the same + // row without that, and whichever write lands first is the one that stays. + const runId = yield* engine.executionId(payload); + yield* store.runStarted({ + runId, + workflow: definition.name, + version: definition.version, + engineTag: engineTag(definition), + idempotencyKey: options.idempotencyKey, + input: payload.input, + parent: options.parent, + }); + // The key is unique, so the row holding it is the run, even one another version started. + const holder = yield* store.runByKey(name, options.idempotencyKey); + if (holder !== undefined && holder.run_id !== runId) return yield* other(holder); + yield* withEngine(engine.execute(payload, { discard: true })); + if (options.parent !== undefined) { + // The key named a run that someone else started: it would never tell this parent. + const row = yield* store.run(runId); + if ( + row?.parent_run_id !== options.parent.runId || + row.parent_wait !== options.parent.wait + ) { + return yield* new WorkflowInputError({ + problem: `Run ${runId} of ${name} was started by something else under this key, so it cannot be invoked. Give the invoke a key of its own.`, + }); + } + } + return { runId }; + }, + ); + + const latestDefinitions = [...new Set(registered.map(([definition]) => definition.name))].map( + (name) => latest(name)![0], + ); + // A schedule taken out and put back is new again: its first run is one interval away. + yield* store.triggersKeep( + latestDefinitions.flatMap((definition) => + definition.triggers.flatMap((trigger) => + trigger.kind === "webhook" ? [] : [`${definition.name}/${trigger.id}`], + ), + ), + ); + /** Start what each schedule is due for, once, however long ago that was. */ + const fireSchedules = Effect.gen(function* () { + const now = yield* localNow; + for (const definition of latestDefinitions) { + for (const trigger of definition.triggers) { + if (trigger.kind !== "schedule") continue; + const id = `${definition.name}/${trigger.id}`; + const due = yield* store.triggerNext(id); + if (due !== undefined) { + const dueAt = DateTime.makeUnsafe(due); + if (DateTime.isLessThan(now, dueAt)) continue; + if (!isMissedFixedTimeRun(trigger.schedule, dueAt, now)) { + // The key is the time it was due, so a crash before the next line starts no second run. + const started = yield* start( + definition.name, + { scheduledAt: due }, + { idempotencyKey: `trigger:${id}:${due}` }, + ).pipe( + Effect.as(true), + Effect.catch((error) => + Effect.as( + Effect.logWarning("A scheduled workflow run did not start", { + trigger: id, + error, + }), + false, + ), + ), + ); + // Not moved past a time it has not started: the next sweep tries that one again. + if (!started) continue; + } + } + const next = nextScheduledRunAt(trigger.schedule, now); + if (next !== null) { + yield* store.triggerSet(id, DateTime.formatIso(DateTime.toUtc(next))); + } + } + } + }).pipe(Effect.withSpan("Workflows.fireSchedules")); + + // Trackers and hosts count requests, and nothing here is in that much of a hurry. + const lookedAt = new Map(); + // Said once per engine: the same item is in every look until newer ones push it out. + const turnedDown = new Set(); + const millisOf = (at: string) => + Option.match(DateTime.make(at), { onNone: () => undefined, onSome: DateTime.toEpochMillis }); + /** + * Start a run for each issue or pull request opened since the trigger last looked. The first + * look only notes the time, so a workflow never starts on everything that was already there. + */ + const fireOpened = Effect.gen(function* () { + const now = yield* DateTime.now; + for (const definition of latestDefinitions) { + for (const trigger of definition.triggers) { + if (trigger.kind !== "issues" && trigger.kind !== "pullRequests") continue; + const id = `${definition.name}/${trigger.id}`; + const since = yield* store.triggerNext(id); + if (since === undefined) { + yield* store.triggerSet(id, DateTime.formatIso(now)); + continue; + } + const last = lookedAt.get(id); + const at = DateTime.toEpochMillis(now); + if (last !== undefined && at - last < Duration.toMillis(LOOK_EVERY)) continue; + lookedAt.set(id, at); + const found = + trigger.kind === "issues" + ? forge.issues.list({ + project: trigger.project, + // Closed ones too: an item can open and close between two looks. + state: "all", + sort: "created", + limit: LOOK_AT_MOST, + labels: trigger.labels, + query: trigger.query, + }) + : forge.pullRequests.list({ + project: trigger.project, + state: "all", + limit: LOOK_AT_MOST, + query: trigger.query, + }); + const sinceMillis = millisOf(since) ?? at; + yield* found.pipe( + Effect.flatMap( + Effect.fnUntraced(function* (entries: ReadonlyArray) { + // From the mark on, not after it: two items can share a moment. As times, since a + // host writes them in its own format and the mark is ours. + const fresh = entries + .flatMap((entry) => { + const created = millisOf(entry.createdAt); + return created === undefined || created < sinceMillis ? [] : [{ entry, created }]; + }) + .toSorted((a, b) => a.created - b.created); + if (entries.length >= LOOK_AT_MOST && fresh.length === entries.length) { + yield* Effect.logWarning( + "More new items than one look reads; older ones among them start no run", + { trigger: id, read: entries.length }, + ); + } + for (const { entry, created } of fresh) { + // The key is the address, so an issue seen twice is still one run. One the + // workflow turns down is passed over, so it does not hold back the ones after it. + const key = `trigger:${id}:${entry.url}`; + if ( + !turnedDown.has(key) && + (yield* store.runByKey(definition.name, key)) === undefined + ) { + yield* start(definition.name, entry, { idempotencyKey: key }).pipe( + // What started the run is the first thing it touched. + Effect.flatMap(({ runId }) => + noteFor( + store, + runId, + null, + "tracker" in entry + ? issueReference(entry, entry) + : pullRequestReferenceOf(entry, entry), + ), + ), + Effect.catchTags({ + WorkflowInputError: (error) => + Effect.andThen( + Effect.sync(() => turnedDown.add(key)), + Effect.logWarning("A workflow turned down an item it was started on", { + trigger: id, + item: entry.url, + error, + }), + ), + }), + ); + } + yield* store.triggerSet(id, DateTime.formatIso(DateTime.makeUnsafe(created))); + } + }), + ), + Effect.catch((error) => + Effect.logWarning("A workflow could not look for new work", { trigger: id, error }), + ), + ); + } + } + }).pipe(Effect.withSpan("Workflows.fireOpened")); + + const noChecksSince = new Map(); + /** End each wait on a pull request that has got where the wait wanted it. */ + const fireWatches = Effect.gen(function* () { + const now = DateTime.toEpochMillis(yield* DateTime.now); + for (const wait of yield* store.watches) { + const id = `watch:${wait.run_id}/${wait.name}`; + const last = lookedAt.get(id); + if (last !== undefined && now - last < Duration.toMillis(LOOK_EVERY)) continue; + lookedAt.set(id, now); + const watch = WorkflowStore.jsonValue( + wait.watch_json ?? "null", + ) as unknown as PullRequestWatch; + yield* forge.pullRequests.read(watch.pullRequest as PullRequestAddress).pipe( + // Each look keeps where the pull request stands on the wait's own step. + Effect.provideContext(stepReferences(store, wait.run_id, wait.name)), + Effect.flatMap( + Effect.fnUntraced(function* (detail) { + const standing = standingOf(detail); + // How long the host has listed no checks, not how long the wait is open: a push can + // clear the list for a moment in the middle of a long wait. + if (standing.checks !== "none") noChecksSince.delete(id); + else if (!noChecksSince.has(id)) noChecksSince.set(id, now); + const without = now - (noChecksSince.get(id) ?? now); + if (!isSettled(watch.until, standing, without)) return; + const woke = { expired: false, value: standing }; + if (!(yield* store.waitSignalled(wait.run_id, wait.name, woke))) return; + lookedAt.delete(id); + noChecksSince.delete(id); + yield* wake(wait, woke); + }), + ), + // The wait's own timeout is what ends a wait on something that cannot be read. + Effect.catch((error) => + Effect.logWarning("A workflow could not look at a pull request", { wait: id, error }), + ), + ); + } + }).pipe(Effect.withSpan("Workflows.fireWatches")); + + const hooks = yield* Effect.forEach( + latestDefinitions.flatMap((definition) => + definition.triggers.flatMap((trigger) => + trigger.kind === "webhook" ? [{ definition, trigger }] : [], + ), + ), + Effect.fnUntraced(function* ({ definition, trigger }) { + const hookId = hookIdOf(definition.name, trigger.name); + const token = yield* store.hookToken(hookId, yield* random.uuidV4()); + return { + hookId, + token, + trigger, + workflow: definition.name, + name: trigger.name, + path: `/api/hooks/${encodeURIComponent(hookId)}/${token}`, + }; + }), + ); + const deliver: Workflows["Service"]["deliver"] = Effect.fn("Workflows.deliver")( + function* (delivery) { + const hook = hooks.find((candidate) => candidate.hookId === delivery.hookId); + // A wrong token reads the same as an unknown hook, so the URL does not say which exist. + const known = + hook !== undefined && + (yield* constantTimeEquals(delivery.token, hook.token).pipe( + Effect.provideService(Digest.Digest, digest), + Effect.orElseSucceed(() => false), + )); + if (!known) return Option.none(); + const authored = yield* Effect.try({ + try: () => hook.trigger.key?.(delivery.request), + catch: (error) => + new WorkflowInputError({ + problem: `The key of hook ${hook.name} could not be read from the request: ${text(error)}`, + }), + }); + // A sender's own delivery id is kept on its retry, so the retry is the same run. + const sent = DELIVERY_HEADERS.find((header) => delivery.request.headers[header]); + const key = + authored ?? + (sent === undefined ? undefined : `${sent}:${delivery.request.headers[sent]}`) ?? + delivery.deliveryId ?? + (yield* random.uuidV4()); + return Option.some( + yield* start(hook.workflow, delivery.request, { + idempotencyKey: `hook:${hook.hookId}:${key}`, + }), + ); + }, + ); + + /** With `pause`, the sweep's own resume, which only resumes that pause and not a later one. */ + const resumeRun = Effect.fn("WorkflowEngine.resumeRun")(function* ( + runId: string, + pause?: WorkflowStore.RunRow, + ) { + const row = yield* requireRun(runId); + const engine = byTag.get(row.engine_tag); + if (engine === undefined) { + return yield* new WorkflowNotRegisteredError({ workflow: row.engine_tag }); + } + if (row.ended_at !== null) return; + resuming.add(runId); + const resumed = yield* Effect.gen(function* () { + // Marked first: once the engine is resumed, the step may fail again and pause the run, and + // that must be the last word. A crash in between leaves `running`, which the sweep corrects. + if (row.status === "paused") { + const unpaused = yield* store.runUnpaused( + runId, + pause === undefined + ? undefined + : { pauses: Number(pause.pauses), updatedAt: pause.updated_at }, + ); + if (!unpaused && pause !== undefined) return false; + } + // The step marks its run paused from inside the engine, a moment before the engine records + // the failure. Resuming in that moment would do nothing, so the record is waited for. + yield* withEngine(engine.poll(runId)).pipe( + Effect.repeat({ + until: (result) => Option.isSome(result) && result.value._tag === "Suspended", + schedule: Schedule.spaced(RESUME_LOOK_EVERY), + times: RESUME_LOOKS, + }), + ); + yield* withEngine(engine.resume(runId)); + yield* store.runUnheld(runId); + return true; + }).pipe(Effect.ensuring(Effect.sync(() => resuming.delete(runId)))); + // Read once `resuming` is clear, so a wake held back meanwhile is among them. + if (!resumed) return; + for (const wait of yield* store.waitsClaimed(runId)) { + yield* send(wait, WorkflowStore.jsonValue(wait.woke_json ?? "null") as typeof Woke.Type); + } + }); + const resume: Workflows["Service"]["resume"] = (runId) => resumeRun(runId); + + /** A run the engine holds as failed while its row says it goes on: paused, after all. */ + const reconcile = Effect.fn("WorkflowEngine.reconcile")(function* (row: WorkflowStore.RunRow) { + if (resuming.has(row.run_id)) return; + const engine = byTag.get(row.engine_tag); + if (engine === undefined) return; + const result = yield* withEngine(engine.poll(row.run_id)); + if (Option.isNone(result) || result.value._tag !== "Suspended") return; + if (result.value.failed !== true) return; + const cause = result.value.cause; + // Held as it was: a run that waited for a person still does. + yield* store.runPaused( + row.run_id, + cause === undefined ? "A step failed." : text(Cause.squash(cause)), + ); + }); + + // A cancelled run's body is gone, so its `onEnd` runs here, outside the engine. The sweep asks + // again after a failure or a restart, and `ending` keeps the two from running it at once. + const ending = new Set(); + const endCancelled = Effect.fn("WorkflowEngine.endCancelled")(function* ( + row: WorkflowStore.RunRow, + ) { + const definition = definitionByTag.get(row.engine_tag); + if (definition?.onEnd === undefined || ending.has(row.run_id)) return; + const onEnd = definition.onEnd; + ending.add(row.run_id); + // A step still running would race the cleanup: a machine deleted before it is made. + yield* link.inFlight.settled(row.run_id); + // The body may have run its own `onEnd` just as the run was cancelled: once is enough. + const steps = yield* store.steps(row.run_id); + if (steps.some((step) => step.name === END_STEP && step.status === "completed")) { + ending.delete(row.run_id); + return; + } + yield* store.stepStarted(row.run_id, END_STEP, "step"); + const payloadCodec = Schema.toCodecJson(definition.payload); + const decode = Schema.decodeEffect(payloadCodec); + yield* decode(row.input_json === null ? null : WorkflowStore.jsonValue(row.input_json)).pipe( + Effect.flatMap((input) => + onEnd(input as never, { + id: row.run_id, + outcome: "cancelled", + reason: row.detail ?? undefined, + }), + ), + Effect.provideContext(forStep(store, keyValues, link, forge, row.run_id, END_STEP)), + // The sweep that runs it reads the engine's BigInts; the cleanup's own code must not. + Effect.provideService(SqlClient.SafeIntegers, false), + Effect.matchCauseEffect({ + onSuccess: () => store.stepEnded(row.run_id, END_STEP, "completed", null), + onFailure: (cause) => + store.stepEnded(row.run_id, END_STEP, "failed", text(Cause.squash(cause))), + }), + Effect.ensuring(Effect.sync(() => ending.delete(row.run_id))), + ); + }); + + const prune = Effect.fn("WorkflowEngine.prune")(function* (at: DateTime.Utc) { + if (Option.isNone(messages) || Option.isNone(sharding)) return; + const before = DateTime.formatIso(DateTime.subtractDuration(at, PRUNE_AFTER)); + for (const row of yield* store.prunable(before, PRUNE_BATCH)) { + const entityId = EntityId.make(row.run_id); + const shardId = sharding.value.getShardId(entityId, "default"); + // Its sleeps are entities of their own under the same id. + yield* Effect.forEach( + [`Workflow/${row.engine_tag}`, "Workflow/-/DurableClock"], + (type) => + messages.value.clearAddress( + EntityAddress.make({ shardId, entityType: EntityType.make(type), entityId }), + ), + { discard: true }, + ).pipe( + Effect.andThen(store.enginePruned(row.run_id)), + // Left unmarked, so the next sweep tries it again. + Effect.catchCause((cause) => + Effect.logWarning("Could not prune a workflow run's engine journal", cause), + ), + ); + } + }); + + const sweep: Workflows["Service"]["sweep"] = Effect.gen(function* () { + for (const wait of yield* store.waitsPastDeadline) { + const woke = { expired: true, value: null }; + if (yield* store.waitSignalled(wait.run_id, wait.name, woke)) yield* wake(wait, woke); + } + // A claim whose wake a crash swallowed: the wake is made again. Waking twice is harmless. + for (const wait of yield* store.waitsToWake) { + if (wait.woke_json === null) continue; + yield* wake(wait, WorkflowStore.jsonValue(wait.woke_json) as typeof Woke.Type); + } + // A cancel that was cut short before it reached what the run had invoked. + for (const child of yield* store.orphans) { + yield* Effect.ignore(cancel(child.run_id, "the run that invoked it was cancelled")); + } + // A cancel cut short after the run was ended: what it had not stopped yet is stopped here. + for (const row of yield* store.cancelsCutShort(END_STEP)) { + if (cancelling.has(row.run_id) || ending.has(row.run_id)) continue; + const engine = byTag.get(row.engine_tag); + if (engine !== undefined) yield* withEngine(engine.interrupt(row.run_id)); + yield* stopSteps(row.run_id, yield* store.runningThreads(row.run_id)); + } + // A run that ended without its parent hearing of it. Telling twice is harmless. + for (const child of yield* store.untold) yield* ended(child.run_id); + yield* store.mailExpire; + yield* fireSchedules; + yield* fireOpened; + yield* fireWatches; + const at = yield* DateTime.now; + // A run with a step still going is ended by its cancel, which waits for that step. + for (const row of yield* store.runsToEnd(END_STEP, END_TRIES)) { + const rest = END_AFTER[Number(row.end_attempts ?? 0) - 1]; + if (row.end_ended_at !== null && rest !== undefined) { + const due = DateTime.addDuration( + DateTime.makeUnsafe(row.end_ended_at), + Duration.fromInputUnsafe(rest), + ); + if (DateTime.isLessThan(at, due)) continue; + } + if (!link.inFlight.busy(row.run_id)) yield* endCancelled(row); + } + for (const row of yield* store.everyRun("running")) yield* reconcile(row); + for (const row of yield* store.everyRun("waiting")) yield* reconcile(row); + for (const row of yield* store.everyRun("paused")) { + const due = resumesAt(row); + if (due === undefined || DateTime.isLessThan(at, due)) continue; + yield* Effect.ignore(resumeRun(row.run_id, row)); + } + yield* prune(at); + }).pipe(Effect.withSpan("Workflows.sweep")); + + // With nothing registered there is nothing to resume, end or start: only history to read. + if (registered.length > 0) { + yield* sweep.pipe( + Effect.catchCause((cause) => Effect.logWarning("Workflow sweep failed", cause)), + Effect.andThen(Effect.sleep(SWEEP_EVERY)), + Effect.forever, + Effect.forkScoped, + ); + } + + const questions = Effect.flatMap(store.requests, (waits) => + Effect.forEach( + waits.filter((wait) => wait.request_json !== null), + (wait) => + Effect.map(store.latestThread(wait.run_id), (thread) => ({ + runId: wait.run_id, + name: wait.name, + request: WorkflowStore.jsonValue(wait.request_json ?? "null"), + askedAt: wait.opened_at, + thread, + })), + ), + ); + const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + const triggerText = (trigger: WorkflowDefinition["triggers"][number]) => { + if (trigger.kind === "webhook") return `webhook ${trigger.name}`; + if (trigger.kind !== "schedule") { + return `new ${trigger.kind === "issues" ? "issues" : "pull requests"} in ${trigger.project}`; + } + if (trigger.schedule.type === "interval") { + return `every ${Duration.format(Duration.millis(trigger.schedule.everyMs))}`; + } + const days = trigger.schedule.weekdays; + return `daily at ${trigger.schedule.timeOfDay}${ + days === undefined ? "" : ` on ${days.map((day) => WEEKDAYS[day] ?? day).join(", ")}` + }`; + }; + const summaries = [...new Set(registered.map(([definition]) => definition.name))].flatMap( + (name) => { + const found = latest(name); + return found === undefined + ? [] + : [{ name, version: found[0].version, triggers: found[0].triggers.map(triggerText) }]; + }, + ); + const snapshot = Effect.all({ + workflows: Effect.succeed(summaries), + runs: Effect.map(store.runs(undefined), (rows) => rows.map(toRun)), + questions, + }); + const watch: Workflows["Service"]["watch"] = Stream.unwrap( + Effect.gen(function* () { + // Subscribed before the first look, so a change in between is not missed. + const changes = yield* PubSub.subscribe(store.changes); + return Stream.concat( + Stream.fromEffect(snapshot), + // A run writes several rows per step; one list answers a burst of them. + Stream.fromSubscription(changes).pipe( + Stream.debounce(WATCH_SETTLE), + Stream.mapEffect(() => snapshot), + ), + ); + }), + ); + + const counts: Workflows["Service"]["counts"] = Stream.unwrap( + Effect.gen(function* () { + const changes = yield* PubSub.subscribe(store.changes); + return Stream.concat( + Stream.fromEffect(store.counts), + Stream.fromSubscription(changes).pipe( + Stream.debounce(WATCH_SETTLE), + Stream.mapEffect(() => store.counts), + ), + // Most changes move no count, and a badge has no use for hearing of those. + ).pipe(Stream.changesWith((left, right) => JSON.stringify(left) === JSON.stringify(right))); + }), + ); + + const signal: Workflows["Service"]["signal"] = Effect.fn("Workflows.signal")( + function* (address, value, options) { + // A sender's retry of a signal that already woke a wait is not a second signal. + if (yield* store.signalSeen(options.id)) return "delivered" as const; + const valueJson = WorkflowStore.jsonText(value); + const woke = { expired: false, value }; + // One signal per wait: a wait another signal took first sends this one to the next. + while (true) { + const wait = yield* store.waitAt(address); + if (wait === undefined) break; + const schema = WorkflowStore.jsonValue(wait.schema_json) as Record; + const checked = yield* checkOutput(schema, valueJson); + if (Result.isFailure(checked)) { + return yield* new WorkflowInputError({ + problem: `The value does not fit what ${wait.name} waits for. ${rejectionText(checked.failure)}`, + }); + } + if (yield* store.waitSignalled(wait.run_id, wait.name, woke, options.id)) { + yield* wake(wait, woke); + return "delivered" as const; + } + // Refused for its id: the same signal, sent again at once, woke a wait. + if (yield* store.signalSeen(options.id)) return "delivered" as const; + } + const expiresAt = DateTime.formatIso( + DateTime.addDuration( + yield* DateTime.now, + Duration.fromInputUnsafe(options.ttl ?? DEFAULT_SIGNAL_TTL), + ), + ); + if (yield* store.signalSeen(options.id)) return "delivered" as const; + yield* store.mailPut({ signalId: options.id, address, valueJson, expiresAt }); + // The wait may have opened and looked for mail between the look above and this write. + while (true) { + const late = yield* store.waitAt(address); + if (late === undefined) return "buffered" as const; + const schema = WorkflowStore.jsonValue(late.schema_json) as Record; + // Kept for a wait it fits; this one, the oldest on the channel, is not it. + if (Result.isFailure(yield* checkOutput(schema, valueJson))) return "buffered" as const; + const outcome = yield* store.mailDeliver(options.id, late.run_id, late.name, woke); + if (outcome === "delivered") { + yield* wake(late, woke); + return "delivered" as const; + } + // The kept copy went to a wait that opened, or was dropped as already delivered. + if (outcome === "gone") return "delivered" as const; + } + }, + ); + const answer: Workflows["Service"]["answer"] = Effect.fn("Workflows.answer")( + function* (runId, name, value) { + const wait = yield* store.waitAt({ runId, wait: name }); + // Answered already, or never asked: kept, it would answer whatever asks there next. + if (wait === undefined || wait.request_json === null) return; + // Named by this asking of the question, so every answer to it is one signal. + yield* signal({ runId, wait: name }, value, { id: `answer:${wait.token}` }); + }, + ); + const signalAll = Effect.fn("WorkflowEngine.signalAll")(function* ( + address: { readonly channel: string; readonly workflow?: string | undefined }, + value: Schema.Json, + ) { + const valueJson = WorkflowStore.jsonText(value); + let woken = 0; + for (const wait of yield* store.waitsOn(address.channel, address.workflow)) { + const schema = WorkflowStore.jsonValue(wait.schema_json) as Record; + // A wait this value does not fit was not waiting for it; the others are still woken. + if (Result.isFailure(yield* checkOutput(schema, valueJson))) continue; + const woke = { expired: false, value }; + if (!(yield* store.waitSignalled(wait.run_id, wait.name, woke))) continue; + yield* wake(wait, woke); + woken++; + } + return woken; + }); + /** Tell the run that invoked this one, if one did, how it ended. */ + const ended = Effect.fn("WorkflowEngine.ended")(function* (runId: string) { + const row = yield* store.run(runId); + if (row === undefined || row.parent_run_id === null || row.parent_wait === null) return; + if (row.ended_at === null) return; + yield* signal( + { runId: row.parent_run_id, wait: row.parent_wait }, + { + outcome: row.status, + value: row.result_json === null ? null : WorkflowStore.jsonValue(row.result_json), + ...(row.detail === null ? {} : { reason: row.detail }), + }, + { id: `${runId}/ended` }, + ).pipe(Effect.ignore); + }); + + /** A step in flight cannot be interrupted, so the agent it waits on is stopped instead. */ + const stopSteps = Effect.fn("WorkflowEngine.stopSteps")(function* ( + runId: string, + threads: ReadonlyArray[0]>, + ) { + yield* Effect.forEach(threads, (thread) => Effect.ignore(stopTurn(thread)), { + discard: true, + }); + yield* store.stepsCancelled(runId, END_STEP); + }); + + // Cancels under way, whose slow part the sweep must not take for one cut short. + const cancelling = new Set(); + const cancel: Workflows["Service"]["cancel"] = Effect.fn("Workflows.cancel")( + function* (runId, reason) { + const row = yield* requireRun(runId); + if (row.ended_at !== null) return; + const threads = yield* store.runningThreads(runId); + const engine = byTag.get(row.engine_tag); + cancelling.add(runId); + yield* Effect.gen(function* () { + // Ended first, so nothing the run still does can be recorded as its outcome. A run that + // finished in the meantime keeps its own ending, and its cleanup is its own. Not cut off + // midway: the engine would go on with a cancelled run, or its parent wait forever. + const cancelled = yield* Effect.uninterruptible( + Effect.gen(function* () { + if (!(yield* store.runEnded(runId, "cancelled", reason ?? null, null))) return false; + if (engine !== undefined) yield* withEngine(engine.interrupt(runId)); + yield* ended(runId); + return true; + }), + ); + if (!cancelled) return; + yield* stopSteps(runId, threads); + // What this run invoked was part of it. + yield* Effect.forEach( + yield* store.children(runId), + (child) => Effect.ignore(cancel(child.run_id, reason)), + { discard: true }, + ); + // Waited for briefly, so the caller usually hears of a run that is cleaned up. A cleanup + // can take minutes; it goes on by itself, and the sweep finishes one that is cut short. + const cleanup = yield* Effect.forkIn( + endCancelled({ ...row, detail: reason ?? null }), + scope, + ); + yield* Fiber.join(cleanup).pipe(Effect.timeoutOption(CANCEL_WAITS)); + }).pipe(Effect.ensuring(Effect.sync(() => cancelling.delete(runId)))); + }, + ); + + // Steps were registered before this engine existed; now they can reach it. + link.current = { + signal, + signalAll, + start, + ended, + cancel: (runId, reason) => cancel(runId, reason), + list: Effect.fn("WorkflowEngine.list")(function* (filter) { + return (yield* store.runsWhere(filter)).map((row) => ({ + id: row.run_id, + workflow: row.workflow, + key: row.idempotency_key, + title: row.title, + status: row.status, + detail: row.detail, + startedAt: row.started_at, + endedAt: row.ended_at, + })); + }), + }; + + return Workflows.of({ + start, + hooks: Effect.succeed(hooks.map(({ workflow, name, path }) => ({ workflow, name, path }))), + // A cancelled run whose cleanup has not worked yet still needs its version to run it. + unfinished: Effect.map( + Effect.all([store.unfinished, store.runsToEnd(END_STEP, END_TRIES)]), + ([open, ending]) => [ + ...open, + ...ending + .filter((row) => definitionByTag.get(row.engine_tag)?.onEnd !== undefined) + .map((row) => ({ workflow: row.workflow, version: Number(row.version) })), + ], + ), + deliver, + signal, + answer, + resume, + cancel, + get: Effect.fn("Workflows.get")(function* (runId) { + const row = yield* requireRun(runId); + const steps = yield* store.steps(runId); + return { + run: toRun(row), + references: yield* store.references(runId), + steps: steps.map((step) => ({ + name: step.name, + kind: step.kind, + status: step.status, + attempts: Number(step.attempts), + detail: step.detail, + threadId: step.thread_id, + environmentId: step.environment_id, + result: step.result_json === null ? null : WorkflowStore.jsonValue(step.result_json), + said: step.said, + startedAt: step.started_at, + endedAt: step.ended_at, + })), + }; + }), + list: Effect.fn("Workflows.list")(function* (filter) { + return (yield* store.runs(filter?.status)).map(toRun); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* (runId, done) { + // Subscribed before the first look, so a change in between is not missed. + const changes = yield* PubSub.subscribe(store.changes); + while (true) { + const row = yield* store.run(runId); + if (row !== undefined && done(toRun(row))) return toRun(row); + yield* Effect.repeat(PubSub.take(changes), { until: (changed) => changed === runId }); + } + }, Effect.scoped), + questions, + counts, + stored: Effect.fn("Workflows.stored")(function* (prefix) { + return (yield* keyValues.list(prefix)).map((row) => ({ + key: row.key, + value: WorkflowStore.jsonValue(row.valueJson), + })); + }), + storeSet: Effect.fn("Workflows.storeSet")(function* (key, value) { + yield* keyValues.set(key, WorkflowStore.jsonText(value)); + }), + storeDelete: Effect.fn("Workflows.storeDelete")(function* (key) { + yield* keyValues.delete(key); + }), + watch, + sweep, + }); +}); + +/** + * The workflow service with these definitions registered, on the SQLite database provided to it. + * Only one process may run this layer against a database. + */ +export const layer = ( + definitions: ReadonlyArray, + store: typeof WorkflowStore.layer = WorkflowStore.layer, +) => { + const registered = definitions.map( + (definition) => [definition, engineWorkflow(definition)] as const, + ); + const layerDefinitions = Layer.mergeAll( + Layer.empty, + ...registered.map(([definition, engine]) => layerDefinition(definition, engine)), + ); + return Layer.effect(Workflows, make(registered)).pipe( + Layer.provide(layerDefinitions), + Layer.provide(store), + Layer.provide(Layer.merge(layerKeyValues, layerEngineLink)), + Layer.provide( + registered.length === 0 + ? WorkflowEngine.layerMemory + : ClusterWorkflowEngine.layer.pipe( + // Merged so the sweep can prune ended runs' journals from the same storage. + Layer.provideMerge(SingleRunner.layer({ runnerStorage: "sql" })), + ), + ), + Layer.provide(Layer.succeed(SqlClient.SafeIntegers, true)), + ); +}; diff --git a/apps/server/src/workflows/WorkflowForge.test.ts b/apps/server/src/workflows/WorkflowForge.test.ts new file mode 100644 index 0000000000000..58f9626423510 --- /dev/null +++ b/apps/server/src/workflows/WorkflowForge.test.ts @@ -0,0 +1,113 @@ +import { assert, it } from "@effect/vitest"; +import { IssueTrackerKind, ProjectId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as IssueService from "../issue/IssueService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as PullRequestService from "../pullRequest/PullRequestService.ts"; +import { StepReferences } from "./runReferences.ts"; +import * as WorkflowForge from "./WorkflowForge.ts"; +import type { ReferenceInput } from "./WorkflowStore.ts"; + +const projectId = ProjectId.make("project-1"); +const forge = WorkflowForge.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(IssueService.IssueService)({ comment: () => Effect.void }), + Layer.mock(PullRequestService.PullRequestService)({ + runAction: () => Effect.void as never, + detail: () => + Effect.succeed({ + projectId, + repository: "Me/App", + number: 7, + title: "Minutes wrap at the hour", + url: "https://github.com/Me/App/pull/7", + state: "merged", + } as never), + }), + Layer.mock(ProjectService.ProjectService)({ + getByWorkspaceRoot: () => Effect.succeedSome({ id: projectId } as never), + }), + ), + ), +); + +it.effect("what a step does through the forge is kept against it, one key per thing", () => + Effect.gen(function* () { + const { issues, pullRequests } = yield* WorkflowForge.WorkflowForge; + const noted: Array = []; + const inStep = Context.make(StepReferences, { + note: (reference) => Effect.sync(() => void noted.push(reference)), + }); + const issue = { + projectId, + tracker: IssueTrackerKind.make("github"), + host: "github.com", + scope: "me/app", + key: "3", + }; + yield* Effect.provideContext( + Effect.all([ + // By its address, then as a listing names it: the same pull request either way. + pullRequests.act( + { project: "/home/me/app", url: "https://github.com/Me/App/pull/7" }, + "merge", + ), + pullRequests.read({ projectId, host: "github.com", repository: "me/app", number: 7 }), + issues.comment(issue, "Looking at it."), + ]), + inStep, + ); + // Outside a step nothing is kept. + yield* issues.comment(issue, "Again."); + assert.deepStrictEqual( + noted.map(({ kind, key, title, state }) => ({ kind, key, title, state })), + [ + { kind: "pullRequest", key: noted[1]!.key, title: "", state: undefined }, + { + kind: "pullRequest", + key: '["github.com","me/app",7]', + title: "Minutes wrap at the hour", + state: "merged", + }, + { kind: "issue", key: '["github","github.com","me/app","3"]', title: "", state: undefined }, + ], + ); + assert.deepStrictEqual(noted[1]!.address, { + projectId, + host: "github.com", + repository: "me/app", + number: 7, + }); + }).pipe(Effect.provide(forge)), +); + +it("a step's pull requests are the ones its thread was linked to while it ran", () => { + const link = (number: number, linkedAt: string, source = "agent") => ({ + host: "github.com", + repository: "me/app", + number, + url: `https://github.com/me/app/pull/${number}`, + source, + linkedAt, + snapshot: null, + }); + const references = WorkflowForge.linkedPullRequestReferences( + { + projectId, + pullRequests: [ + link(1, "2026-01-01T00:00:00.000Z"), + link(2, "2026-01-01T00:10:00.000Z"), + link(3, "2026-01-01T00:10:00.000Z", "stack-dismissed"), + ] as never, + }, + Date.parse("2026-01-01T00:05:00.000Z"), + ); + assert.deepStrictEqual( + references.map((reference) => [reference.key, reference.url]), + [['["github.com","me/app",2]', "https://github.com/me/app/pull/2"]], + ); +}); diff --git a/apps/server/src/workflows/WorkflowForge.ts b/apps/server/src/workflows/WorkflowForge.ts new file mode 100644 index 0000000000000..dab867593b4dd --- /dev/null +++ b/apps/server/src/workflows/WorkflowForge.ts @@ -0,0 +1,455 @@ +// Issues and pull requests for workflows: the same trackers and hosts the app's own Issues and +// Pull requests pages read, through the project's credentials. A step names a project the way +// an agent step does, by id or by folder. +import { + IssueDetail, + IssueListEntry, + type IssueCreateResult, + type IssueListState, + type IssueRef, + type PullRequestAction, + type PullRequestDetail, + PullRequestListEntry, + type PullRequestListState, + type PullRequestMergeMethod, + type PullRequestRef, + ProjectId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import * as IssueService from "../issue/IssueService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; +import * as PullRequestService from "../pullRequest/PullRequestService.ts"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import { + normalizeThreadPullRequestKey, + threadPullRequestsOf, +} from "../sourceControl/threadPullRequests.ts"; +import { issueReference, noteReference, pullRequestReference } from "./runReferences.ts"; +import { isProjectPath } from "./WorkflowAgents.ts"; + +export class WorkflowForgeError extends Schema.TaggedError()( + "WorkflowForgeError", + { reason: Schema.String }, +) { + override get message(): string { + return this.reason; + } +} + +/** What an issue trigger gives its run, and what `issues.list` returns rows of. */ +export const Issue = IssueListEntry; +export type Issue = typeof Issue.Type; +/** What a pull request trigger gives its run, and what `pullRequests.list` returns rows of. */ +export const PullRequest = PullRequestListEntry; +export type PullRequest = typeof PullRequest.Type; +export { IssueDetail }; + +/** An issue by its web address, or as a trigger or a listing gave it. */ +export type IssueAddress = + | { readonly project: string; readonly url: string } + | Pick; +/** A pull request by its web address, or as a trigger or a listing gave it. */ +export type PullRequestAddress = + | { readonly project: string; readonly url: string } + | Pick; + +/** Where a pull request stands, as a wait on it gives it. */ +export const PullRequestStanding = Schema.Struct({ + state: Schema.Literals(["open", "closed", "merged"]), + /** `none` when the host lists no checks for it. */ + checks: Schema.Literals(["passing", "failing", "pending", "none"]), + mergeability: Schema.Literals(["mergeable", "conflicting", "unknown"]), + url: Schema.String, +}); +export type PullRequestStanding = typeof PullRequestStanding.Type; +export type PullRequestUntil = "checks" | "merged" | "closed"; +/** What a wait on a pull request keeps for the engine to look at. */ +export interface PullRequestWatch { + readonly kind: "pullRequest"; + readonly until: PullRequestUntil; + readonly pullRequest: + | { readonly project: string; readonly url: string } + | { + readonly projectId: string; + readonly host: string; + readonly repository: string; + readonly number: number; + }; +} + +// Checks take a moment to be listed after a push, so "none" only counts once it has stayed none. +const NO_CHECKS_AFTER_MS = 2 * 60_000; + +/** Required checks decide when the host marks any as required; otherwise all of them do. */ +export const standingOf = ( + detail: Pick, +): PullRequestStanding => { + const listed = detail.checks.filter((check) => check.placeholder !== true); + const counted = listed.some((check) => check.required === true) + ? listed.filter((check) => check.required === true) + : listed; + const failing = counted.some( + (check) => + check.status === "failure" || + check.status === "cancelled" || + // Nothing moves it but a person, so a run waiting for it would wait for good. + check.status === "action-required", + ); + const pending = counted.some((check) => check.status === "pending"); + return { + state: detail.state, + // Pending first: the wait is for none of them still running, even once one has failed. + checks: counted.length === 0 ? "none" : pending ? "pending" : failing ? "failing" : "passing", + mergeability: detail.mergeability, + url: detail.url, + }; +}; + +/** Whether a wait `until` this is over, the host having listed no checks for `withoutChecksMs`. */ +export const isSettled = ( + until: PullRequestUntil, + standing: PullRequestStanding, + withoutChecksMs: number, +): boolean => { + if (standing.state !== "open") return true; + if (until !== "checks") return false; + if (standing.checks === "none") return withoutChecksMs >= NO_CHECKS_AFTER_MS; + return standing.checks !== "pending"; +}; + +export interface IssueQuery { + readonly project: string; + /** Defaults to open. */ + readonly state?: IssueListState | undefined; + /** Label names an issue must carry, every one of them. */ + readonly labels?: ReadonlyArray | undefined; + /** Free text the tracker matches itself. */ + readonly query?: string | undefined; + readonly assignee?: string | undefined; + readonly sort?: "updated" | "created" | undefined; + readonly limit?: number | undefined; +} +export interface PullRequestQuery { + readonly project: string; + /** Defaults to open. */ + readonly state?: PullRequestListState | undefined; + readonly query?: string | undefined; + readonly limit?: number | undefined; +} + +type PullRequestSeen = Parameters[1]; +/** A pull request as a run's reference, under the key every way of naming it shares. */ +export const pullRequestReferenceOf = ( + ref: Pick, + seen?: PullRequestSeen, +) => + pullRequestReference( + { + projectId: ref.projectId, + ...normalizeThreadPullRequestKey({ + host: ref.host ?? "", + repository: ref.repository, + number: ref.number, + ...(seen?.url === undefined ? {} : { url: seen.url }), + }), + }, + seen, + ); + +/** The pull requests linked to a thread from `sinceMillis` on, as references of its step. */ +export const linkedPullRequestReferences = ( + thread: Parameters[0] & { readonly projectId: ProjectId }, + sinceMillis: number | undefined, +) => + threadPullRequestsOf(thread) + .filter( + (link) => + link.source !== "stack-dismissed" && + (sinceMillis === undefined || Date.parse(link.linkedAt) >= sinceMillis), + ) + .map((link) => + pullRequestReferenceOf( + { + projectId: thread.projectId, + host: link.host, + repository: link.repository, + number: link.number, + }, + link.snapshot === null + ? { url: link.url } + : { url: link.url, title: link.snapshot.title, state: link.snapshot.state }, + ), + ); + +export class WorkflowForge extends Context.Service< + WorkflowForge, + { + readonly issues: { + readonly list: (query: IssueQuery) => Effect.Effect, WorkflowForgeError>; + readonly read: (issue: IssueAddress) => Effect.Effect; + readonly comment: ( + issue: IssueAddress, + body: string, + ) => Effect.Effect; + readonly setState: ( + issue: IssueAddress, + state: string, + ) => Effect.Effect; + readonly create: (input: { + readonly project: string; + readonly title: string; + readonly body?: string | undefined; + readonly labels?: ReadonlyArray | undefined; + readonly assignees?: ReadonlyArray | undefined; + }) => Effect.Effect; + }; + readonly pullRequests: { + readonly list: ( + query: PullRequestQuery, + ) => Effect.Effect, WorkflowForgeError>; + readonly read: ( + pullRequest: PullRequestAddress, + ) => Effect.Effect; + readonly comment: ( + pullRequest: PullRequestAddress, + body: string, + ) => Effect.Effect; + readonly act: ( + pullRequest: PullRequestAddress, + action: PullRequestAction, + options?: { readonly mergeMethod?: PullRequestMergeMethod | undefined }, + ) => Effect.Effect; + }; + } +>()("t3/workflows/WorkflowForge") {} + +const failed = + (what: string) => + (cause: unknown): WorkflowForgeError => + new WorkflowForgeError({ + reason: `${what}: ${cause instanceof Error ? cause.message : String(cause)}`, + }); + +const missing = (what: string) => () => + Effect.fail( + new WorkflowForgeError({ + reason: `${what} are not available to workflows on this server.`, + }), + ); +/** For an engine with no trackers behind it: every call says so. */ +export const unavailable = WorkflowForge.of({ + issues: { + list: missing("Issues"), + read: missing("Issues"), + comment: missing("Issues"), + setState: missing("Issues"), + create: missing("Issues"), + }, + pullRequests: { + list: missing("Pull requests"), + read: missing("Pull requests"), + comment: missing("Pull requests"), + act: missing("Pull requests"), + }, +}); + +export const layer = Layer.effect( + WorkflowForge, + Effect.gen(function* () { + const issues = yield* IssueService.IssueService; + const pullRequests = yield* PullRequestService.PullRequestService; + const projects = yield* ProjectService.ProjectService; + + const projectIdOf = Effect.fn("WorkflowForge.projectIdOf")(function* (project: string) { + if (!isProjectPath(project)) return ProjectId.make(project); + const found = yield* projects + .getByWorkspaceRoot(project) + .pipe(Effect.mapError(failed("Could not read the project"))); + if (Option.isNone(found)) { + return yield* new WorkflowForgeError({ reason: `No project is registered at ${project}.` }); + } + return found.value.id; + }); + + const issueRef = Effect.fn("WorkflowForge.issueRef")(function* (issue: IssueAddress) { + if (!("project" in issue)) { + return { + projectId: issue.projectId, + tracker: issue.tracker, + host: issue.host, + scope: issue.scope, + key: issue.key, + } satisfies IssueRef; + } + const resolved = yield* issues + .resolveUrl(issue.url, yield* projectIdOf(issue.project)) + .pipe(Effect.mapError(failed(`Could not find the issue at ${issue.url}`))); + return { + projectId: resolved.projectId, + tracker: resolved.tracker, + host: resolved.host, + scope: resolved.scope, + key: resolved.key, + } satisfies IssueRef; + }); + + const pullRequestRef = Effect.fn("WorkflowForge.pullRequestRef")(function* ( + pullRequest: PullRequestAddress, + ) { + if (!("project" in pullRequest)) { + return { + projectId: pullRequest.projectId, + host: pullRequest.host, + repository: pullRequest.repository, + number: pullRequest.number, + } satisfies PullRequestRef; + } + const parsed = sourceControlDefinitions.parseChangeRequestUrl(pullRequest.url)?.link; + if (parsed === undefined) { + return yield* new WorkflowForgeError({ + reason: `${pullRequest.url} is not a pull request address.`, + }); + } + const key = normalizeThreadPullRequestKey(parsed); + return { + projectId: yield* projectIdOf(pullRequest.project), + host: key.host, + repository: key.repository, + number: key.number, + } satisfies PullRequestRef; + }); + + // An address that is a whole listing row already says what the item is called. + const seenOf = (address: object) => ({ + ...("title" in address && typeof address.title === "string" ? { title: address.title } : {}), + ...("url" in address && typeof address.url === "string" ? { url: address.url } : {}), + }); + const issueTouched = (ref: IssueRef, address: IssueAddress) => + noteReference({ ...issueReference(ref), ...seenOf(address) }); + const pullRequestTouched = (ref: PullRequestRef, seen: PullRequestSeen) => + noteReference(pullRequestReferenceOf(ref, seen)); + + return WorkflowForge.of({ + issues: { + list: Effect.fn("WorkflowForge.issues.list")(function* (query) { + const result = yield* issues + .list({ + projectId: yield* projectIdOf(query.project), + state: query.state ?? "open", + ...(query.labels === undefined ? {} : { labels: [...query.labels] }), + ...(query.query === undefined ? {} : { query: query.query }), + ...(query.assignee === undefined ? {} : { assignee: query.assignee }), + ...(query.sort === undefined ? {} : { sort: query.sort }), + ...(query.limit === undefined ? {} : { limit: query.limit }), + }) + .pipe(Effect.mapError(failed("Could not list issues"))); + // A listing answers with what it could read. One that read nothing is a failure. + const problem = result.errors[0]; + if (result.entries.length === 0 && problem !== undefined) { + return yield* new WorkflowForgeError({ + reason: `Could not list issues: ${problem.message}`, + }); + } + return result.entries; + }), + read: Effect.fn("WorkflowForge.issues.read")(function* (issue) { + const ref = yield* issueRef(issue); + const detail = yield* issues + .detail(ref) + .pipe(Effect.mapError(failed("Could not read the issue"))); + yield* noteReference(issueReference(ref, detail)); + return detail; + }), + comment: Effect.fn("WorkflowForge.issues.comment")(function* (issue, body) { + const ref = yield* issueRef(issue); + yield* issues + .comment({ ...ref, body }) + .pipe(Effect.mapError(failed("Could not comment on the issue"))); + yield* issueTouched(ref, issue); + }), + setState: Effect.fn("WorkflowForge.issues.setState")(function* (issue, state) { + const ref = yield* issueRef(issue); + yield* issues + .setState({ ...ref, state }) + .pipe(Effect.mapError(failed("Could not change the issue's state"))); + yield* issueTouched(ref, issue); + }), + create: Effect.fn("WorkflowForge.issues.create")(function* (input) { + const scope = yield* issues + .projectScope(yield* projectIdOf(input.project)) + .pipe(Effect.mapError(failed("Could not find the project's issue tracker"))); + const created = yield* issues + .create({ + projectId: scope.projectId, + tracker: scope.tracker, + host: scope.host, + scope: scope.scope, + title: input.title, + body: input.body ?? "", + labels: [...(input.labels ?? [])], + assignees: [...(input.assignees ?? [])], + }) + .pipe(Effect.mapError(failed("Could not file the issue"))); + yield* noteReference({ + ...issueReference({ ...scope, key: created.key }), + title: input.title, + url: created.url, + state: "open", + }); + return created; + }), + }, + pullRequests: { + list: Effect.fn("WorkflowForge.pullRequests.list")(function* (query) { + const result = yield* pullRequests + .list({ + projectId: yield* projectIdOf(query.project), + state: query.state ?? "open", + ...(query.query === undefined ? {} : { query: query.query }), + ...(query.limit === undefined ? {} : { limit: query.limit }), + }) + .pipe(Effect.mapError(failed("Could not list pull requests"))); + const problem = result.errors[0]; + if (result.entries.length === 0 && problem !== undefined) { + return yield* new WorkflowForgeError({ + reason: `Could not list pull requests: ${problem.message}`, + }); + } + return result.entries; + }), + read: Effect.fn("WorkflowForge.pullRequests.read")(function* (pullRequest) { + const ref = yield* pullRequestRef(pullRequest); + // Fresh, not a held copy: checks that passed before a push must not end a wait after it. + const detail = yield* pullRequests + .detail({ ...ref, allowStale: false }) + .pipe(Effect.mapError(failed("Could not read the pull request"))); + yield* pullRequestTouched(ref, detail); + return detail; + }), + comment: Effect.fn("WorkflowForge.pullRequests.comment")(function* (pullRequest, body) { + const ref = yield* pullRequestRef(pullRequest); + yield* pullRequests + .comment({ ...ref, body }) + .pipe(Effect.mapError(failed("Could not comment on the pull request"))); + yield* pullRequestTouched(ref, seenOf(pullRequest)); + }), + act: Effect.fn("WorkflowForge.pullRequests.act")(function* (pullRequest, action, options) { + const ref = yield* pullRequestRef(pullRequest); + yield* pullRequests + .runAction({ + ...ref, + action, + ...(options?.mergeMethod === undefined ? {} : { mergeMethod: options.mergeMethod }), + }) + .pipe(Effect.mapError(failed(`Could not ${action} the pull request`))); + yield* pullRequestTouched(ref, seenOf(pullRequest)); + }), + }, + }); + }), +); diff --git a/apps/server/src/workflows/WorkflowRuntime.test.ts b/apps/server/src/workflows/WorkflowRuntime.test.ts new file mode 100644 index 0000000000000..344e6d871efd9 --- /dev/null +++ b/apps/server/src/workflows/WorkflowRuntime.test.ts @@ -0,0 +1,464 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; +import { WorkflowAgents } from "./WorkflowAgents.ts"; +import * as WorkflowEngine from "./WorkflowEngine.ts"; +import * as WorkflowRuntime from "./WorkflowRuntime.ts"; +import { engineTag, type WorkflowDefinition } from "./workflow.ts"; +import * as Workflows from "./Workflows.ts"; + +/** Waits to be let go. */ +const hold = `T3.workflow("hold", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map(T3.wait("go", { returns: Schema.String }), (said) => Option.getOrElse(said, () => "nobody")), +); +`; +const greet = (says: string) => `const { workflow } = T3; +workflow("greet", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.succeed(${JSON.stringify(says)}), +); +`; + +/** + * A folder holding `hold.ts`, and the workflow runtime over it on a fresh database. `engine` + * stands in for the real one, which needs the clock to run for as long as it is up. + */ +const setup = Effect.fn("setup")(function* ( + wrap: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem = (fileSystem) => fileSystem, + engine?: (definitions: ReadonlyArray) => Layer.Layer, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-defs-" }); + const directory = path.join(home, "workflows"); + const at = (name: string) => path.join(directory, name); + yield* fileSystem.makeDirectory(directory); + yield* fileSystem.writeFileString(at("hold.ts"), hold); + const database = NodeSqliteClient.layer({ filename: path.join(home, "state.sqlite") }); + yield* Effect.provide(WorkflowsMigration, database); + const made = WorkflowRuntime.make( + Effect.succeed( + (definitions: ReadonlyArray) => + engine?.(definitions) ?? + WorkflowEngine.layer(definitions).pipe( + Layer.provide(Layer.mock(WorkflowAgents)({})), + Layer.provide(database), + Layer.provide(NodeCrypto.layer), + ), + ), + directory, + Effect.succeed(true), + ).pipe(Effect.provideService(FileSystem.FileSystem, wrap(fileSystem))); + return { fileSystem, at, directory, made, runtime: Layer.effectContext(made) }; +}); + +it.effect( + "every file in the folder defines workflows, and a saved file is verified before it runs", + () => + Effect.gen(function* () { + const { fileSystem, at, runtime } = yield* setup(); + + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, (run) => run.status === "waiting"); + + // A file that does not parse is not written, and says where it breaks. + const broken = yield* definitions.save("greet.ts", "T3.workflow(\n 'x',\n];\n"); + assert.isFalse(broken.changed); + assert.deepStrictEqual( + broken.problems.map((problem) => [problem.file, problem.line]), + [["greet.ts", 3]], + ); + // Nor is one that defines what another file already does, or drops what a run needs. + const twice = yield* definitions.save("again.ts", hold); + assert.include( + twice.problems[0]?.message ?? "", + "hold@1 is defined twice, in again.ts and hold.ts", + ); + const dropped = yield* definitions.save("hold.ts", greet("hello")); + assert.include( + dropped.problems[0]?.message ?? "", + "hold@1 is no longer defined, and 1 of its runs", + ); + // Nor one that exports something shaped like a workflow without what the engine walks. + const shaped = yield* definitions.save( + "shaped.ts", + 'export default [{ name: "shaped", version: 1, body: () => Effect.void }];\n', + ); + assert.include(shaped.problems[0]?.message ?? "", "is not a workflow"); + // Nor one with an option nothing reads, or a time a schedule cannot fire at. + const misspelt = yield* definitions.save( + "misspelt.ts", + 'T3.workflow("misspelt", { version: 1, payload: Schema.Struct({}), retries: 2 }, () => Effect.void);\n', + ); + assert.include(misspelt.problems[0]?.message ?? "", "does not take `retries`"); + const late = yield* definitions.save( + "late.ts", + 'T3.workflow("late", { version: 1, payload: T3.Tick, triggers: [T3.daily("9am")] }, () => Effect.void);\n', + ); + assert.include(late.problems[0]?.message ?? "", "24-hour time"); + const banana = yield* definitions.save( + "banana.ts", + 'T3.workflow("banana", { version: 1, payload: T3.Tick, triggers: [T3.every("banana")] }, () => Effect.void);\n', + ); + assert.include(banana.problems[0]?.message ?? "", 'Write one such as "5 minutes"'); + const twoHooks = yield* definitions.save( + "hooks.ts", + 'T3.workflow("hooks", { version: 1, payload: T3.WebhookRequest, triggers: [T3.webhook("in"), T3.webhook("in")] }, () => Effect.void);\n', + ); + assert.include(twoHooks.problems[0]?.message ?? "", 'two hooks named "in"'); + assert.include((yield* definitions.remove("hold.ts")).problems[0]?.message ?? "", "hold@1"); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => file.name), + ["hold.ts"], + ); + // The same change made outside the app is refused as a whole: the file still reads as the + // version that runs, until it is put back. + const told = (wanted: boolean) => + workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), + Stream.runHead, + ); + yield* fileSystem.writeFileString(at("hold.ts"), greet("hello")); + yield* told(true); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => file.workflows), + [["hold@1"]], + ); + // Only that file is held back: another file's change still runs, and the held one says why. + const other = + 'T3.workflow("other", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n'; + // A file the folder's naming leaves out says so, instead of never running without a word. + yield* fileSystem.writeFileString(at("my flow.ts"), other); + assert.deepStrictEqual(yield* definitions.save("other.ts", other), { + changed: true, + problems: [], + }); + yield* workflows.start("other", {}, { idempotencyKey: "o" }); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => [file.name, file.problems.length]), + [ + ["hold.ts", 1], + ["other.ts", 0], + ], + ); + assert.deepStrictEqual( + (yield* definitions.read).problems.map((problem) => problem.file), + ["my flow.ts"], + ); + yield* fileSystem.remove(at("my flow.ts")); + assert.deepStrictEqual(yield* definitions.remove("other.ts"), { + changed: true, + problems: [], + }); + yield* fileSystem.writeFileString(at("hold.ts"), hold); + yield* told(false); + + // A new file that passes is there from now on, and what it defines can be started. + const saved = { changed: true, problems: [] }; + assert.deepStrictEqual(yield* definitions.save("greet.ts", greet("hello")), saved); + assert.equal(yield* fileSystem.readFileString(at("greet.ts")), greet("hello")); + const greeted = yield* workflows.start("greet", {}, { idempotencyKey: "g" }); + const done = yield* workflows.waitFor(greeted.runId, (run) => run.status === "completed"); + assert.equal(done.result, "hello"); + // The run that was waiting came through the reload and can still be let go. + yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" }); + const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed"); + assert.equal(freed.result, "go on"); + + // Someone breaks a file outside the app: its last good version keeps running, and the + // other files go on changing. + const problem = (wanted: boolean) => + workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), + Stream.runHead, + ); + yield* fileSystem.writeFileString(at("greet.ts"), "T3.workflow("); + yield* problem(true); + const read = yield* definitions.read; + assert.deepStrictEqual( + read.files.map((file) => [file.name, file.problems.length]), + [ + ["greet.ts", 1], + ["hold.ts", 0], + ], + ); + const still = yield* workflows.start("greet", {}, { idempotencyKey: "g2" }); + assert.equal( + (yield* workflows.waitFor(still.runId, (run) => run.status === "completed")).result, + "hello", + ); + // And fixes it, saying something else, this time as the file's one default export. + yield* fileSystem.writeFileString( + at("greet.ts"), + greet("hi").replace("\nworkflow(", "\nexport default workflow("), + ); + yield* problem(false); + const fixed = yield* workflows.start("greet", {}, { idempotencyKey: "g3" }); + assert.equal( + (yield* workflows.waitFor(fixed.runId, (run) => run.status === "completed")).result, + "hi", + ); + // A file taken away takes its workflows with it. + assert.deepStrictEqual(yield* definitions.remove("greet.ts"), saved); + const gone = yield* workflows + .start("greet", {}, { idempotencyKey: "g4" }) + .pipe(Effect.flip); + assert.equal(gone._tag, "WorkflowNotRegisteredError"); + // With no file left, nothing runs, and the runs that ended can still be read. + assert.deepStrictEqual(yield* definitions.remove("hold.ts"), saved); + assert.equal((yield* workflows.get(held.runId)).run.status, "completed"); + assert.includeMembers( + (yield* workflows.list()).map((run) => run.runId), + [held.runId, greeted.runId], + ); + }).pipe( + Effect.provide(runtime), + Effect.scoped, + Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "a folder that cannot be listed keeps its workflows and is looked at again, and an engine that cannot start leaves the last one running", + () => + Effect.gen(function* () { + let refuse = false; + // What each engine was built to run. One that registers `broken` does not come up. + const builds: Array> = []; + // No file events: only the runtime's own retry can pick up what changed. + const { at, fileSystem, runtime } = yield* setup( + (real) => ({ + ...real, + exists: (target) => + refuse + ? Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "exists", + pathOrDescriptor: target, + }), + ) + : real.exists(target), + watch: () => Stream.never, + }), + (definitions) => + definitions.some((definition) => definition.name === "broken") + ? Layer.effect(Workflows.Workflows, Effect.die(new Error("broken took it down"))) + : Layer.sync(Workflows.Workflows, () => { + builds.push(definitions.map(engineTag)); + return Workflows.disabled; + }), + ); + + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const revision = Effect.map( + Stream.runHead(workflows.watch), + (snapshot) => Option.getOrThrow(snapshot).definition?.revision ?? 0, + ); + refuse = true; + // Written, but the folder could not be listed, so it is not said to run. + const unlisted = yield* definitions.save("greet.ts", greet("hi")); + assert.isTrue(unlisted.changed); + assert.include(unlisted.problems[0]?.message ?? "", "could not be read"); + // What was loaded stays, and greet is not taken in yet. + assert.deepStrictEqual(builds, [["hold@1"]]); + const before = yield* revision; + refuse = false; + yield* TestClock.adjust("30 seconds"); + yield* workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.revision ?? 0) > before), + Stream.runHead, + ); + assert.deepStrictEqual(builds.at(-1), ["greet@1", "hold@1"]); + + // A definition that passes the checks but takes the engine down at start changes nothing. + yield* fileSystem.writeFileString( + at("broken.ts"), + 'T3.workflow("broken", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n', + ); + const fellBack = yield* definitions.save("greet.ts", greet("hello")); + assert.isTrue(fellBack.changed); + assert.include(fellBack.problems[0]?.message ?? "", "did not start"); + assert.deepStrictEqual(builds.slice(1), [ + ["greet@1", "hold@1"], + ["greet@1", "hold@1"], + ]); + assert.include( + (yield* Stream.runHead(workflows.watch)).pipe(Option.getOrThrow).definition?.problem ?? + "", + "did not start", + ); + }).pipe(Effect.provide(runtime), Effect.scoped); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a file that never finishes loading is given up on, and later files still load", () => + Effect.gen(function* () { + const { at, fileSystem } = yield* setup(); + yield* fileSystem.writeFileString(at("stuck.ts"), "await new Promise(() => {});\n"); + yield* fileSystem.writeFileString(at("greet.ts"), greet("hi")); + const stuck = yield* WorkflowRuntime.loadDefinitions(at("stuck.ts"), 0, 50).pipe(Effect.flip); + assert.include(String(stuck.cause), "did not finish loading"); + const loaded = yield* WorkflowRuntime.loadDefinitions(at("greet.ts")); + assert.deepStrictEqual( + loaded.map((definition) => definition.name), + ["greet"], + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a file given up on registers nothing into the file that loads after it", () => + Effect.gen(function* () { + const { at, fileSystem } = yield* setup(); + yield* fileSystem.writeFileString( + at("slow.ts"), + 'await new Promise((resolve) => { globalThis.t3TestResume = resolve; });\nT3.workflow("slow", { version: 1, payload: Schema.Struct({}) }, () => Effect.void);\n', + ); + // The second file goes on loading until the first one's top level has run to its end. + yield* fileSystem.writeFileString( + at("next.ts"), + `${greet("hi")}globalThis.t3TestResume();\nawait new Promise((resolve) => setImmediate(resolve));\n`, + ); + yield* WorkflowRuntime.loadDefinitions(at("slow.ts"), 0, 50).pipe(Effect.flip); + const loaded = yield* WorkflowRuntime.loadDefinitions(at("next.ts")); + assert.deepStrictEqual( + loaded.map((definition) => definition.name), + ["greet"], + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +// Vitest's module runner loads a file its own way; only Node keeps a CommonJS file by its path. +it.live("a file without imports or exports loads again after it changes", () => + Effect.gen(function* () { + const { at, fileSystem } = yield* setup(); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + yield* fileSystem.writeFileString(at("greet.ts"), greet("hi")); + const twice = ` + import * as NodeFS from "node:fs"; + import * as NodeServices from "@effect/platform-node/NodeServices"; + import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; + import { loadDefinitions } from ${JSON.stringify(new URL("./WorkflowRuntime.ts", import.meta.url).href)}; + const file = process.argv.at(-1); + const program = Effect.gen(function* () { + const first = yield* loadDefinitions(file, 1); + NodeFS.writeFileSync(file, NodeFS.readFileSync(file, "utf8").replace('"hi"', '"hello"')); + const second = yield* loadDefinitions(file, 2); + return [first.length, second.length]; + }); + console.log(JSON.stringify(await Effect.runPromise(Effect.provide(program, NodeServices.layer)))); + `; + const child = yield* spawner.spawn( + ChildProcess.make( + process.execPath, + ["--input-type=module", "--eval", twice, at("greet.ts")], + { cwd: import.meta.dirname }, + ), + ); + const [stdout, stderr] = yield* Effect.all( + [ + child.stdout.pipe(Stream.decodeText(), Stream.mkString), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + ], + { concurrency: "unbounded" }, + ); + assert.equal(stdout.trim(), "[1,1]", stderr); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a change held back by a run goes in once that run ends, with no further edit", () => + Effect.gen(function* () { + // The folder's changes are told by hand, so the test does not hang on a watcher starting. + const changed = yield* Queue.unbounded(); + const { fileSystem, at, runtime } = yield* setup((fileSystem) => ({ + ...fileSystem, + watch: () => Stream.fromQueue(changed), + })); + yield* Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const definitions = yield* WorkflowRuntime.WorkflowDefinitions; + const held = yield* workflows.start("hold", {}, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, (run) => run.status === "waiting"); + const problem = (wanted: boolean) => + workflows.watch.pipe( + Stream.filter((snapshot) => (snapshot.definition?.problem != null) === wanted), + Stream.runHead, + ); + yield* fileSystem.writeFileString(at("hold.ts"), greet("hello")); + yield* Queue.offer(changed, { _tag: "Update", path: at("hold.ts") }); + yield* problem(true); + yield* workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" }); + yield* workflows.waitFor(held.runId, (run) => run.status === "completed"); + // Nothing is told of the folder now: the held change goes in on its own. + yield* problem(false); + assert.deepStrictEqual( + (yield* definitions.read).files.map((file) => file.workflows), + [["greet@1"]], + ); + }).pipe( + Effect.provide(runtime), + Effect.scoped, + Effect.raceFirst(Effect.forever(TestClock.adjust("1 second"))), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "workflows are off until turned on, and a run left waiting when they are turned off goes on once they are on again", + () => + Effect.gen(function* () { + const { fileSystem, at, directory, made } = yield* setup(); + // Its top level counts the times it was loaded. + yield* fileSystem.writeFileString( + at("counted.ts"), + "globalThis.t3GatedLoads = (globalThis.t3GatedLoads ?? 0) + 1;\nexport default [];\n", + ); + const loads = () => (globalThis as { t3GatedLoads?: number }).t3GatedLoads ?? 0; + yield* Effect.gen(function* () { + const { turn, context } = yield* WorkflowRuntime.gate(made, directory); + const workflows = Context.get(context, Workflows.Workflows); + const definitions = Context.get(context, WorkflowRuntime.WorkflowDefinitions); + const start = workflows.start("hold", {}, { idempotencyKey: "h" }); + + assert.equal((yield* Effect.flip(start)).message, Workflows.OFF); + assert.equal((yield* Effect.flip(workflows.list())).message, Workflows.OFF); + assert.deepStrictEqual((yield* definitions.read).files, []); + assert.equal(loads(), 0); + + yield* turn(true); + assert.equal(loads(), 1); + const held = yield* start; + yield* workflows.waitFor(held.runId, (run) => run.status === "waiting"); + + yield* turn(false); + const signal = workflows.signal({ runId: held.runId, wait: "go" }, "go on", { id: "s1" }); + assert.equal((yield* Effect.flip(signal)).message, Workflows.OFF); + + yield* turn(true); + yield* signal; + const freed = yield* workflows.waitFor(held.runId, (run) => run.status === "completed"); + assert.equal(freed.result, "go on"); + }).pipe(Effect.scoped, Effect.raceFirst(Effect.forever(TestClock.adjust("1 second")))); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); diff --git a/apps/server/src/workflows/WorkflowRuntime.ts b/apps/server/src/workflows/WorkflowRuntime.ts new file mode 100644 index 0000000000000..8a7502789189f --- /dev/null +++ b/apps/server/src/workflows/WorkflowRuntime.ts @@ -0,0 +1,978 @@ +// Workflows in the running server: every file in one folder defines some, and the folder can +// change while the server runs. A file that loads replaces what it defined before; one that does +// not keeps its last good version running. With no definitions there is no engine, unless runs +// from before are kept: then one with nothing registered serves their history. +import * as NodeAsyncHooks from "node:async_hooks"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- the CommonJS cache is cleared in the same tick as the import. +import * as NodeFS from "node:fs"; +import * as NodeModule from "node:module"; +import * as NodeURL from "node:url"; + +import type { + WorkflowDefinitionChangeResult, + WorkflowDefinitionFiles, + WorkflowDefinitionProblem, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Config from "effect/Config"; +import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; + +import * as ServerConfig from "../config.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { engineTag, text, type WorkflowDefinition } from "./workflow.ts"; +import type * as WorkflowEngine from "./WorkflowEngine.ts"; +import * as WorkflowAgentThreads from "./WorkflowAgentThreads.ts"; +import * as WorkflowForge from "./WorkflowForge.ts"; +import * as Workflows from "./Workflows.ts"; + +/** A folder of definition files, or one file, in place of the folder in the T3 home. */ +const definitionsOverride = Config.String("T3CODE_WORKFLOWS").pipe(Config.option); + +// An editor saves in several writes, and a save from here is followed by its own file event. +const RELOAD_SETTLE = "300 millis"; +// How often a change held back by unfinished runs is tried again, so it goes in once they end. +const HELD_RETRY = "15 seconds"; +// A folder that could not be listed is looked at again, since no file event may follow. +const LIST_RETRY = "30 seconds"; +// A leading dot is how a file is kept out: a draft being checked, an editor's swap file. +// One name in the folder, never a path: the name is also the key a save and a removal go by. +const DEFINITION_FILE = /^[A-Za-z0-9_][\w.-]*\.(ts|mts|js|mjs)$/; +const NAMING = + "Name the file with letters, digits, dashes, underscores and dots, ending in .ts: for example release.ts."; + +export class WorkflowDefinitionsLoadError extends Schema.TaggedError()( + "WorkflowDefinitionsLoadError", + { module: Schema.String, cause: Schema.Defect() }, +) { + override get message(): string { + return `Could not load workflow definitions from ${this.module}.`; + } +} + +/** The definition files of this server, for a person to read and change. */ +export class WorkflowDefinitions extends Context.Service< + WorkflowDefinitions, + { + /** The files as they are on disk now, with what is wrong with them. */ + readonly read: Effect.Effect; + /** + * Verify `source` as the file `name`, and when nothing is wrong write it and run it from now + * on. A file that was written can still fail to run, and then says why. + */ + readonly save: (name: string, source: string) => Effect.Effect; + /** Take a file away, unless runs still need what it defines. */ + readonly remove: (name: string) => Effect.Effect; + } +>()("t3/workflows/WorkflowRuntime/WorkflowDefinitions") {} + +const isDefinition = (value: unknown): value is WorkflowDefinition => + typeof value === "object" && + value !== null && + typeof (value as WorkflowDefinition).name === "string" && + typeof (value as WorkflowDefinition).version === "number" && + typeof (value as WorkflowDefinition).body === "function" && + // The engine walks these at start, and a file can export an object that only looks like one. + Array.isArray((value as WorkflowDefinition).triggers) && + Array.isArray((value as WorkflowDefinition).resumeAfter); + +// The API is handed to a file as globals, which the whole process shares, so files load one at +// a time. A load that was given up on still runs, so `T3.workflow` registers with the load whose +// code calls it, and with none once that load is over. +const loading = Semaphore.makeUnsafe(1); +// A file whose top-level code never settles would otherwise hold every later load. Real time, +// since importing a module is. +const LOAD_DEADLINE_MS = 20_000; + +interface Evaluation { + readonly registered: Array; + open: boolean; +} +const evaluating = new NodeAsyncHooks.AsyncLocalStorage(); +// Counts loads across runtimes: one started again would otherwise get back the modules of the last. +let loads = 0; +const required = NodeModule.createRequire(import.meta.url); + +/** A file with no `import` or `export` loads as CommonJS, which Node keeps by path, not address. */ +const forget = (file: string) => { + delete required.cache[file]; + try { + delete required.cache[NodeFS.realpathSync(file)]; + } catch { + // Gone already, so nothing can be kept under its real path either. + } +}; + +const within = (work: Promise, ms: number): Promise => { + let timer: ReturnType | undefined; + const late = new Promise((resolve) => { + // @effect-diagnostics-next-line globalTimers:off -- an import runs on real time, not a test clock. + timer = setTimeout(resolve, ms, undefined); + }); + return Promise.race([work, late]).finally(() => clearTimeout(timer)); +}; + +const evaluate = async (url: string, evaluation: Evaluation): Promise> => { + const api = await import("./api.ts"); + const { Duration, Effect: effect, Option: option, Schedule, Schema: schema, ...t3 } = api; + const workflow = ((...input: Parameters) => { + const current = evaluating.getStore(); + if (current === undefined || !current.open) { + throw new Error( + "T3.workflow was called after its file finished loading. Call it at the top of the file.", + ); + } + const definition = api.workflow(...input); + current.registered.push(definition); + return definition; + }) as typeof api.workflow; + Object.assign(globalThis, { + T3: { ...t3, workflow }, + Effect: effect, + Schema: schema, + Option: option, + Duration, + Schedule, + }); + const loaded = (await evaluating.run(evaluation, () => import(url))) as { + readonly default?: unknown; + "module.exports"?: unknown; + }; + // A file with no `import` or `export` loads as CommonJS, whose default is its `module.exports`: + // an empty object unless the file set one, which says nothing about what it defines. + const commonJs = "module.exports" in loaded; + const exported = + commonJs && + typeof loaded.default === "object" && + loaded.default !== null && + !Array.isArray(loaded.default) && + Object.keys(loaded.default).length === 0 + ? undefined + : loaded.default; + // One workflow exported by itself is as good as a list of one. + const listed = + exported === undefined + ? [] + : Array.isArray(exported) + ? exported + : isDefinition(exported) + ? [exported] + : undefined; + if (listed === undefined) { + throw new Error( + "The default export is not a workflow or a list of them. Call T3.workflow(…), or export what it returned.", + ); + } + return [...new Set([...evaluation.registered, ...listed])]; +}; + +/** + * The workflows a file defines: every `T3.workflow(…)` it calls, and any list it exports. + * `load` tells one loading of a file from the next: Node keeps a module by its address, so the + * same address would give back the file as it was the first time. + */ +export const loadDefinitions = Effect.fn("WorkflowRuntime.loadDefinitions")(function* ( + module: string, + load = 0, + deadlineMs = LOAD_DEADLINE_MS, +) { + const path = yield* Path.Path; + const file = path.resolve(module); + const url = NodeURL.pathToFileURL(file).href + (load === 0 ? "" : `?${load}`); + const definitions = yield* Effect.tryPromise({ + try: () => { + const evaluation: Evaluation = { registered: [], open: true }; + forget(file); + return within(evaluate(url, evaluation), deadlineMs).finally(() => { + evaluation.open = false; + forget(file); + }); + }, + catch: (cause) => new WorkflowDefinitionsLoadError({ module, cause }), + }).pipe(loading.withPermits(1)); + if (definitions === undefined) { + return yield* new WorkflowDefinitionsLoadError({ + module, + cause: `It did not finish loading within ${deadlineMs / 1000} seconds. Something at the top of the file waits for good.`, + }); + } + if (!definitions.every(isDefinition)) { + return yield* new WorkflowDefinitionsLoadError({ + module, + cause: "Something it exports is not a workflow. Export only what `T3.workflow` returned.", + }); + } + return definitions; +}); + +/** What a load error says, with the line of `file` it points at when it names one. */ +const loadProblem = ( + error: WorkflowDefinitionsLoadError, + loadedFrom: string, + file: string, +): WorkflowDefinitionProblem => { + const cause = error.cause; + const stack = cause instanceof Error ? (cause.stack ?? "") : ""; + const name = loadedFrom.split(/[\\/]/).at(-1) ?? loadedFrom; + // Node names the place as `file:///…/name.ts:12` or `…/name.ts:12:5`, with a `?n` when reloaded. + const at = stack.split(name).find((rest) => /^(\?\d+)?:\d+/.test(rest)); + const line = at === undefined ? undefined : Number(/^(?:\?\d+)?:(\d+)/.exec(at)?.[1]); + return { message: text(cause), file, ...(line === undefined ? {} : { line }) }; +}; + +/** + * What is wrong between files that each loaded, given the runs that have not ended, with the + * files that could each be the cause. + */ +const definitionProblems = ( + files: ReadonlyArray<{ + readonly name: string; + readonly definitions: ReadonlyArray; + }>, + unfinished: ReadonlyArray<{ readonly workflow: string; readonly version: number }>, + before: ReadonlyMap> = new Map(), +): ReadonlyArray<{ + readonly problem: WorkflowDefinitionProblem; + readonly files: ReadonlyArray; + readonly clash: boolean; +}> => { + const where = new Map>(); + for (const file of files) { + for (const definition of file.definitions) { + where.set(engineTag(definition), [...(where.get(engineTag(definition)) ?? []), file.name]); + } + } + const waiting = new Map(); + for (const run of unfinished) { + const tag = engineTag({ name: run.workflow, version: run.version }); + if (!where.has(tag)) waiting.set(tag, (waiting.get(tag) ?? 0) + 1); + } + return [ + ...[...where] + .filter(([, names]) => names.length > 1) + .map(([tag, names]) => ({ + problem: { + message: `${tag} is defined twice, in ${[...new Set(names)].join(" and ")}. A workflow's name and version name one body.`, + }, + files: [...new Set(names)], + clash: true, + })), + ...[...waiting].map(([tag, runs]) => ({ + problem: { + message: `${tag} is no longer defined, and ${runs} of its runs ${runs === 1 ? "has" : "have"} not ended. Keep that version until they end, or cancel them first.`, + }, + files: [...before] + .filter(([, definitions]) => + definitions.some((definition) => engineTag(definition) === tag), + ) + .map(([name]) => name), + clash: false, + })), + ]; +}; + +/** + * `engine` gives the layer that runs a set of definitions. It is asked for only once there is + * something to run or `kept` says there are runs to read, since the engine's modules are not worth + * loading for nothing. `where` is the folder of definition files, or one file. + */ +export const make = Effect.fn("WorkflowRuntime.make")(function* ( + engine: Effect.Effect< + (definitions: ReadonlyArray) => Layer.Layer + >, + where: string, + kept: Effect.Effect, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const target = path.resolve(where); + const single = DEFINITION_FILE.test(path.basename(target)); + const directory = single ? path.dirname(target) : target; + yield* Effect.ignore(fileSystem.makeDirectory(directory, { recursive: true })); + const outer = yield* Scope.Scope; + const services = yield* Effect.context(); + + // One reload at a time, and callers during one wait for the engine that comes out of it. + const lock = yield* Semaphore.make(1); + let ready = Deferred.makeUnsafe(); + let engineScope: Scope.Closeable | undefined; + let running: ReadonlyArray = []; + let imported = false; + /** Each file as it was last looked at, so one that did not change is not loaded again. */ + const seen = new Map(); + /** The last version of each file that loaded, which runs while a newer one does not. */ + const good = new Map>(); + /** Files that loaded or went away since, kept apart until the change as a whole is taken. */ + const pending = new Map | null>(); + const broken = new Map(); + /** Files whose change clashes with another file or drops what a run needs, and why. */ + const held = new Map>(); + let between: ReadonlyArray = []; + /** Code files in the folder that are not loaded because of their name. */ + let misnamed: ReadonlyArray = []; + let retrying = false; + let unstarted = false; + const state = yield* SubscriptionRef.make<{ revision: number; problem: string | null }>({ + revision: 0, + problem: null, + }); + const told = (problem: WorkflowDefinitionProblem) => + problem.file === undefined ? problem.message : `${problem.file}: ${problem.message}`; + const report = Effect.suspend(() => { + const problems = [...broken.values(), ...[...held.values()].flat(), ...misnamed, ...between]; + return SubscriptionRef.update(state, (current) => ({ + revision: current.revision + 1, + problem: problems.length === 0 ? null : problems.map(told).join("\n"), + })); + }); + + /** Every name in the folder, or the one file. */ + const entries = Effect.gen(function* () { + if (single) { + return (yield* fileSystem.exists(target)) ? [path.basename(target)] : []; + } + // A folder that is not there yet is empty. One that cannot be read just now is not: it + // fails, and what was loaded stays. + if (!(yield* fileSystem.exists(directory))) return []; + return (yield* fileSystem.readDirectory(directory)).toSorted(); + }); + const definitionNames = (all: ReadonlyArray) => + all.filter((entry) => DEFINITION_FILE.test(entry)); + const names = Effect.map(entries, definitionNames); + + /** A fresh engine for these definitions in its own scope, or the failure that stopped it. */ + const build = Effect.fn("WorkflowRuntime.build")(function* ( + definitions: ReadonlyArray, + ) { + const scope = yield* Scope.fork(outer); + const layerEngine = yield* engine; + imported = true; + const built = yield* Effect.suspend(() => + Layer.buildWithScope(layerEngine(definitions), scope), + ).pipe(Effect.provideContext(services), Effect.exit); + if (Exit.isFailure(built)) yield* Scope.close(scope, Exit.void); + else engineScope = scope; + return built; + }); + + const boot = Effect.fn("WorkflowRuntime.boot")( + function* (definitions: ReadonlyArray) { + const next = Deferred.makeUnsafe(); + ready = next; + const previous = running; + if (engineScope !== undefined) yield* Scope.close(engineScope, Exit.void); + engineScope = undefined; + running = []; + if (definitions.length === 0 && !imported && !(yield* kept)) { + yield* Deferred.succeed(next, Workflows.disabled); + return null; + } + const built = yield* build(definitions); + if (Exit.isSuccess(built)) { + running = definitions; + yield* Deferred.succeed(next, Context.get(built.value, Workflows.Workflows)); + if (definitions.length > 0) { + yield* Effect.logInfo("Workflows registered", { + directory, + workflows: definitions.map(engineTag), + }); + } + return null; + } + // What ran before comes back, so definitions that cannot start take nothing down. + const restored = yield* build(previous); + if (Exit.isSuccess(restored)) { + running = previous; + yield* Deferred.succeed(next, Context.get(restored.value, Workflows.Workflows)); + } else { + // Nobody may be left waiting on an engine that never came up. + yield* Deferred.succeed(next, Workflows.disabled); + } + return `The workflow engine did not start: ${text(Cause.squash(built.cause))}`; + }, + // Once `ready` is replaced it must be settled, or every caller waits on it for good. + Effect.uninterruptible, + ); + + const unfinished = Effect.suspend(() => + running.length === 0 + ? Effect.succeed([]) + : Effect.flatMap(Deferred.await(ready), (service) => service.unfinished), + ); + /** The workflows the file at `from` defines, or what is wrong with it as the file `name`. */ + const load = Effect.fn("WorkflowRuntime.load")(function* (from: string, name: string) { + const definitions = yield* loadDefinitions(from, ++loads).pipe( + Effect.provideContext(services), + Effect.result, + ); + return definitions._tag === "Failure" + ? ({ problem: loadProblem(definitions.failure, from, name) } as const) + : ({ definitions: definitions.success } as const); + }); + /** What would run with these files, in the folder's order. */ + const gathered = (files: ReadonlyMap>) => + [...files] + .toSorted(([left], [right]) => left.localeCompare(right)) + .map(([name, definitions]) => ({ name, definitions })); + + // Set once `reload` exists, which it schedules again; the indirection keeps its type inferred. + let retryLater: Effect.Effect = Effect.void; + /** Take in what changed in the folder, and run the result unless something is wrong with it. */ + const reload = Effect.fn("WorkflowRuntime.reload")(function* () { + const listed = yield* Effect.option(entries); + if (Option.isNone(listed)) { + yield* Effect.logWarning( + "The workflows folder could not be read; its workflows stay as they are", + ); + yield* retryLater; + return false; + } + const present = definitionNames(listed.value); + // A leading dot keeps a file out on purpose; any other code file left out is a surprise. + const wasMisnamed = misnamed; + misnamed = listed.value + .filter((entry) => /^[^.].*\.(ts|mts|js|mjs)$/.test(entry) && !DEFINITION_FILE.test(entry)) + .map((entry) => ({ message: `It is not loaded. ${NAMING}`, file: entry })); + const renamed = + misnamed.map((problem) => problem.file).join("/") !== + wasMisnamed.map((problem) => problem.file).join("/"); + let changed = false; + for (const problem of misnamed) { + if (!wasMisnamed.some((known) => known.file === problem.file)) { + yield* Effect.logWarning( + "A file in the workflows folder is not loaded because of its name", + problem, + ); + } + } + for (const name of present) { + const file = path.join(directory, name); + const source = yield* fileSystem.readFileString(file).pipe(Effect.option); + if (Option.isNone(source) || seen.get(name) === source.value) continue; + seen.set(name, source.value); + changed = true; + const loaded = yield* load(file, name); + if (loaded.definitions === undefined) { + broken.set(name, loaded.problem); + pending.delete(name); + yield* Effect.logWarning("A workflow definitions file was not loaded", loaded.problem); + continue; + } + broken.delete(name); + pending.set(name, loaded.definitions); + } + for (const name of [...seen.keys()].filter((known) => !present.includes(known))) { + seen.delete(name); + pending.set(name, null); + broken.delete(name); + changed = true; + } + // Asked again while something stands between files: the runs that held a version may be over. + if (!changed && between.length === 0 && held.size === 0) { + if (renamed) yield* report; + return true; + } + const runs = yield* unfinished; + // A change that clashes is held back like a file that does not load: that file keeps its last + // good version, a new one stays out, and every other change is taken. + held.clear(); + let next = new Map(good); + let problems: ReturnType = []; + let blamed = true; + while (blamed) { + blamed = false; + next = new Map(good); + for (const [name, definitions] of pending) { + if (held.has(name)) continue; + if (definitions === null) next.delete(name); + else next.set(name, definitions); + } + problems = definitionProblems(gathered(next), runs, good); + for (const { problem, files: involved, clash } of problems) { + const changing = involved.filter((name) => pending.has(name) && !held.has(name)); + // Between new files that define the same workflow, the first in the folder's order stays. + const culprits = + clash && changing.length === involved.length ? changing.slice(1) : changing; + for (const name of culprits) { + held.set(name, [...(held.get(name) ?? []), { ...problem, file: name }]); + blamed = true; + } + } + } + if (held.size > 0) { + yield* Effect.logWarning("Some workflow definition changes were not taken", { + problems: [...held.values()].flat(), + }); + } + // What is left was so before any of these changes, so it holds none of them back. + const standing = problems.map((entry) => entry.problem); + if (standing.length > 0) { + yield* Effect.logWarning("Workflow definitions have problems", { problems: standing }); + } + const taking = [...pending.keys()].filter((name) => !held.has(name)); + // An engine that did not start is tried again, as the runs it tripped on may have ended. + if (taking.length === 0 && !unstarted) { + between = standing; + yield* report; + return true; + } + good.clear(); + for (const [name, definitions] of next) good.set(name, definitions); + for (const name of taking) pending.delete(name); + const failed = yield* boot(gathered(next).flatMap((file) => file.definitions)); + unstarted = failed !== null; + between = failed === null ? standing : [...standing, { message: failed }]; + yield* report; + return true; + }); + + retryLater = Effect.suspend(() => { + if (retrying) return Effect.void; + retrying = true; + return Effect.suspend(() => { + retrying = false; + return lock.withPermits(1)(reload()); + }).pipe( + Effect.delay(LIST_RETRY), + Effect.catchCause((cause) => + Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)), + ), + Effect.forkIn(outer), + Effect.asVoid, + ); + }); + + yield* lock.withPermits(1)(reload()); + // No file defines anything yet, though runs kept from before may still be read. + if (!(yield* Deferred.isDone(ready))) yield* boot([]); + + // The folder, not a file: an editor that saves by renaming replaces the file it was watching. + yield* fileSystem.watch(directory).pipe( + Stream.debounce(RELOAD_SETTLE), + Stream.runForEach(() => + lock + .withPermits(1)(reload()) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)), + ), + ), + ), + Effect.catchCause((cause) => + Effect.logWarning("Workflow definitions are not watched for changes", Cause.pretty(cause)), + ), + Effect.forkIn(outer), + ); + + yield* Effect.sleep(HELD_RETRY).pipe( + Effect.andThen( + Effect.suspend(() => (held.size > 0 ? lock.withPermits(1)(reload()) : Effect.void)), + ), + Effect.catchCause((cause) => + Effect.logWarning("Reloading workflow definitions failed", Cause.pretty(cause)), + ), + Effect.forever, + Effect.forkIn(outer), + ); + + const current = Effect.suspend(() => Deferred.await(ready)); + // A watcher outlives the engine it began on: each reload hands it the next one's stream. + const followed = (pick: (service: Workflows.Workflows["Service"]) => Stream.Stream) => + SubscriptionRef.changes(state).pipe( + Stream.switchMap((at) => + Stream.unwrap(Effect.map(current, pick)).pipe(Stream.map((value) => [value, at] as const)), + ), + ); + const service = Workflows.Workflows.of({ + start: Effect.fn("Workflows.start")(function* (...input) { + return yield* (yield* current).start(...input); + }), + signal: Effect.fn("Workflows.signal")(function* (...input) { + return yield* (yield* current).signal(...input); + }), + answer: Effect.fn("Workflows.answer")(function* (...input) { + return yield* (yield* current).answer(...input); + }), + resume: Effect.fn("Workflows.resume")(function* (...input) { + return yield* (yield* current).resume(...input); + }), + cancel: Effect.fn("Workflows.cancel")(function* (...input) { + return yield* (yield* current).cancel(...input); + }), + get: Effect.fn("Workflows.get")(function* (...input) { + return yield* (yield* current).get(...input); + }), + list: Effect.fn("Workflows.list")(function* (...input) { + return yield* (yield* current).list(...input); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* (...input) { + // A reload replaces the engine, and a wait on the old one would never hear of the run again. + while (true) { + // Noted before the engine is read, so a reload that lands in between is still heard of. + const { revision } = yield* SubscriptionRef.get(state); + const live = yield* current; + const reloaded = SubscriptionRef.changes(state).pipe( + Stream.filter((at) => at.revision !== revision), + Stream.runHead, + ); + const waited = yield* live + .waitFor(...input) + .pipe(Effect.asSome, Effect.raceFirst(Effect.as(reloaded, Option.none()))); + if (Option.isSome(waited)) return waited.value; + } + }), + questions: Effect.flatMap(current, (live) => live.questions), + unfinished: Effect.flatMap(current, (live) => live.unfinished), + hooks: Effect.flatMap(current, (live) => live.hooks), + deliver: Effect.fn("Workflows.deliver")(function* (...input) { + return yield* (yield* current).deliver(...input); + }), + stored: Effect.fn("Workflows.stored")(function* (...input) { + return yield* (yield* current).stored(...input); + }), + storeSet: Effect.fn("Workflows.storeSet")(function* (...input) { + return yield* (yield* current).storeSet(...input); + }), + storeDelete: Effect.fn("Workflows.storeDelete")(function* (...input) { + return yield* (yield* current).storeDelete(...input); + }), + watch: followed((live) => live.watch).pipe( + Stream.map(([snapshot, at]) => ({ ...snapshot, definition: at })), + ), + counts: followed((live) => live.counts).pipe(Stream.map(([counts]) => counts)), + sweep: Effect.flatMap(current, (live) => live.sweep), + }); + + const alone = { message: `This server reads its workflows from ${target} alone.` }; + /** Why `name` cannot be a file here, if it cannot. */ + const refused = (name: string): WorkflowDefinitionProblem | undefined => + single && name !== path.basename(target) + ? alone + : DEFINITION_FILE.test(name) + ? undefined + : { message: NAMING }; + /** What is wrong with the folder once `change` is made to the files that load. */ + const wouldBreak = Effect.fn("WorkflowRuntime.wouldBreak")(function* ( + change: (files: Map>) => void, + ) { + const files = new Map(good); + change(files); + return definitionProblems(gathered(files), yield* unfinished, good).map( + (entry) => entry.problem, + ); + }); + + const refusal = (problems: ReadonlyArray) => ({ + changed: false, + problems, + }); + /** What keeps a change to the file `name` from running, once it is made on disk. */ + const taken = Effect.fn("WorkflowRuntime.taken")(function* (name: string) { + const listed = yield* reload(); + const problem = broken.get(name); + return { + changed: true, + problems: listed + ? [...(problem === undefined ? [] : [problem]), ...(held.get(name) ?? []), ...between] + : [{ message: `${directory} could not be read just now, so the change does not run yet.` }], + }; + }); + + const save = Effect.fn("WorkflowRuntime.save")(function* (name: string, source: string) { + const no = refused(name); + if (no !== undefined) return refusal([no]); + const file = path.join(directory, name); + // Beside the real file, so what it imports resolves the same way. The dot keeps it out. + const draft = path.join(directory, `.${name}.check-${loads + 1}${path.extname(name)}`); + const checked = yield* fileSystem.writeFileString(draft, source).pipe( + Effect.andThen(load(draft, name)), + Effect.ensuring(Effect.ignore(fileSystem.remove(draft))), + Effect.catchTags({ + PlatformError: (error) => + Effect.succeed({ + problem: { message: `Could not write in ${directory}: ${text(error)}` }, + } as const), + }), + ); + if (!("definitions" in checked)) return refusal([checked.problem]); + const definitions = checked.definitions; + const problems = yield* wouldBreak((files) => files.set(name, definitions)); + if (problems.length > 0) return refusal(problems); + const written = yield* fileSystem.writeFileString(file, source).pipe(Effect.result); + if (written._tag === "Failure") { + return refusal([{ message: `Could not write ${file}: ${text(written.failure)}` }]); + } + return yield* taken(name); + }); + + const remove = Effect.fn("WorkflowRuntime.remove")(function* (name: string) { + const no = single ? alone : refused(name); + if (no !== undefined) return refusal([no]); + const problems = yield* wouldBreak((files) => files.delete(name)); + if (problems.length > 0) return refusal(problems); + const removed = yield* fileSystem.remove(path.join(directory, name)).pipe(Effect.result); + if (removed._tag === "Failure") { + return refusal([{ message: `Could not delete ${name}: ${text(removed.failure)}` }]); + } + return yield* taken(name); + }); + + return Context.make(Workflows.Workflows, service).pipe( + Context.add( + WorkflowDefinitions, + WorkflowDefinitions.of({ + read: Effect.gen(function* () { + const files = yield* Effect.forEach( + yield* Effect.orElseSucceed(names, () => []), + (name) => + fileSystem.readFileString(path.join(directory, name)).pipe( + Effect.orElseSucceed(() => ""), + Effect.map((source) => { + const problem = broken.get(name); + return { + name, + source, + workflows: (good.get(name) ?? []).map(engineTag), + problems: [ + ...(problem === undefined ? [] : [problem]), + ...(held.get(name) ?? []), + ], + }; + }), + ), + ); + const at = yield* SubscriptionRef.get(state); + // A file held back after it was deleted has no entry of its own to say so. + const gone = [...held] + .filter(([name]) => !files.some((file) => file.name === name)) + .flatMap(([, problems]) => problems); + return { directory, single, files, problems: [...misnamed, ...between, ...gone], ...at }; + }), + save: Effect.fn("WorkflowDefinitions.save")(function* (name, source) { + return yield* lock.withPermits(1)(save(name, source)); + }), + remove: Effect.fn("WorkflowDefinitions.remove")(function* (name) { + return yield* lock.withPermits(1)(remove(name)); + }), + }), + ), + ); +}); + +/** + * Workflows behind the Labs switch. While off, `runtime` is not run: no definition file loads and + * no engine runs, and every request is refused. Turning on runs it in a scope of its own, which + * turning off closes; runs stay stored and go on once it is on again. `where` is as for `make`. + */ +export const gate = Effect.fn("WorkflowRuntime.gate")(function* ( + runtime: Effect.Effect< + Context.Context, + E, + R | Scope.Scope + >, + where: string, +) { + const path = yield* Path.Path; + const outer = yield* Scope.Scope; + const services = yield* Effect.context(); + const target = path.resolve(where); + const single = DEFINITION_FILE.test(path.basename(target)); + const off = { message: Workflows.OFF }; + const offDefinitions = WorkflowDefinitions.of({ + read: Effect.succeed({ + directory: single ? path.dirname(target) : target, + single, + files: [], + problems: [off], + revision: 0, + problem: null, + }), + save: Effect.fn("WorkflowDefinitions.save")(function* () { + return yield* Effect.succeed({ changed: false, problems: [off] }); + }), + remove: Effect.fn("WorkflowDefinitions.remove")(function* () { + return yield* Effect.succeed({ changed: false, problems: [off] }); + }), + }); + const offContext = Context.make(Workflows.Workflows, Workflows.off).pipe( + Context.add(WorkflowDefinitions, offDefinitions), + ); + + const lock = yield* Semaphore.make(1); + let ready = Deferred.makeUnsafe>(); + Deferred.doneUnsafe(ready, Exit.succeed(offContext)); + let scope: Scope.Closeable | undefined; + const turns = yield* SubscriptionRef.make(0); + + const turn = Effect.fn("WorkflowRuntime.turn")( + function* (on: boolean) { + if (on === (scope !== undefined)) return; + const next = + Deferred.makeUnsafe>(); + ready = next; + if (scope !== undefined) yield* Scope.close(scope, Exit.void); + scope = undefined; + if (on) { + const opened = yield* Scope.fork(outer); + const started = yield* runtime.pipe( + Effect.provideService(Scope.Scope, opened), + Effect.provideContext(services), + Effect.exit, + ); + if (Exit.isSuccess(started)) { + scope = opened; + yield* Deferred.succeed(next, started.value); + } else { + yield* Scope.close(opened, Exit.void); + yield* Effect.logWarning("Workflows did not start", Cause.pretty(started.cause)); + } + } + if (scope === undefined) yield* Deferred.succeed(next, offContext); + yield* SubscriptionRef.update(turns, (count) => count + 1); + yield* Effect.logInfo(scope === undefined ? "Workflows are off" : "Workflows are on"); + }, + // Once `ready` is replaced it must be settled, or every caller waits on it for good. + Effect.uninterruptible, + lock.withPermits(1), + ); + + const live = Effect.suspend(() => Deferred.await(ready)); + const current = Effect.map(live, Context.get(Workflows.Workflows)); + const definitions = Effect.map(live, Context.get(WorkflowDefinitions)); + // A watcher outlives a turn: each one hands it the next service's stream. + const followed = (pick: (service: Workflows.Workflows["Service"]) => Stream.Stream) => + SubscriptionRef.changes(turns).pipe( + Stream.switchMap(() => Stream.unwrap(Effect.map(current, pick))), + ); + const service = Workflows.Workflows.of({ + start: Effect.fn("Workflows.start")(function* (...input) { + return yield* (yield* current).start(...input); + }), + signal: Effect.fn("Workflows.signal")(function* (...input) { + return yield* (yield* current).signal(...input); + }), + answer: Effect.fn("Workflows.answer")(function* (...input) { + return yield* (yield* current).answer(...input); + }), + resume: Effect.fn("Workflows.resume")(function* (...input) { + return yield* (yield* current).resume(...input); + }), + cancel: Effect.fn("Workflows.cancel")(function* (...input) { + return yield* (yield* current).cancel(...input); + }), + get: Effect.fn("Workflows.get")(function* (...input) { + return yield* (yield* current).get(...input); + }), + list: Effect.fn("Workflows.list")(function* (...input) { + return yield* (yield* current).list(...input); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* (...input) { + // Off, nothing changes a run; a wait goes on once workflows are on again. + while (true) { + const turned = yield* SubscriptionRef.get(turns); + const service = yield* current; + const next = SubscriptionRef.changes(turns).pipe( + Stream.filter((count) => count !== turned), + Stream.runHead, + ); + const waited = yield* service + .waitFor(...input) + .pipe(Effect.asSome, Effect.raceFirst(Effect.as(next, Option.none()))); + if (Option.isSome(waited)) return waited.value; + } + }), + questions: Effect.flatMap(current, (service) => service.questions), + unfinished: Effect.flatMap(current, (service) => service.unfinished), + hooks: Effect.flatMap(current, (service) => service.hooks), + deliver: Effect.fn("Workflows.deliver")(function* (...input) { + return yield* (yield* current).deliver(...input); + }), + stored: Effect.fn("Workflows.stored")(function* (...input) { + return yield* (yield* current).stored(...input); + }), + storeSet: Effect.fn("Workflows.storeSet")(function* (...input) { + return yield* (yield* current).storeSet(...input); + }), + storeDelete: Effect.fn("Workflows.storeDelete")(function* (...input) { + return yield* (yield* current).storeDelete(...input); + }), + watch: followed((service) => service.watch), + counts: followed((service) => service.counts), + sweep: Effect.flatMap(current, (service) => service.sweep), + }); + + return { + turn, + context: Context.make(Workflows.Workflows, service).pipe( + Context.add( + WorkflowDefinitions, + WorkflowDefinitions.of({ + read: Effect.flatMap(definitions, (files) => files.read), + save: Effect.fn("WorkflowDefinitions.save")(function* (name, source) { + return yield* (yield* definitions).save(name, source); + }), + remove: Effect.fn("WorkflowDefinitions.remove")(function* (name) { + return yield* (yield* definitions).remove(name); + }), + }), + ), + ), + }; +}); + +/** + * The workflow service for this server, and its definition files: those in the `workflows` + * folder of the T3 home, or wherever `T3CODE_WORKFLOWS` points instead. A file that does not + * load is reported and never stops the server. Nothing runs until `workflowsEnabled` is on. + */ +export const layer = Layer.effectContext( + Effect.gen(function* () { + const override = yield* definitionsOverride; + const config = yield* ServerConfig.ServerConfig; + const forge = Layer.succeed(WorkflowForge.WorkflowForge, yield* WorkflowForge.WorkflowForge); + const sql = yield* SqlClient.SqlClient; + const settings = yield* ServerSettings.ServerSettingsService; + const where = Option.getOrElse(override, () => config.workflowsDir); + const changes = yield* settings.subscribeChanges; + const gated = yield* gate( + make( + Effect.map( + Effect.promise((): Promise => import("./WorkflowEngine.ts")), + (engine) => (definitions) => + engine + .layer(definitions) + .pipe(Layer.provide(WorkflowAgentThreads.layer), Layer.provide(forge)), + ), + where, + sql`SELECT 1 FROM workflow_runs LIMIT 1`.pipe( + Effect.map((rows) => rows.length > 0), + Effect.orElseSucceed(() => true), + ), + ), + where, + ); + const enabled = yield* settings.getSettings.pipe( + Effect.map((current) => current.workflowsEnabled), + Effect.orElseSucceed(() => false), + ); + yield* gated.turn(enabled); + yield* changes.pipe( + Stream.map((current) => current.workflowsEnabled), + Stream.runForEach(gated.turn), + Effect.forkScoped, + ); + return gated.context; + }), +); diff --git a/apps/server/src/workflows/WorkflowStore.test.ts b/apps/server/src/workflows/WorkflowStore.test.ts new file mode 100644 index 0000000000000..7fa6daa8c0208 --- /dev/null +++ b/apps/server/src/workflows/WorkflowStore.test.ts @@ -0,0 +1,424 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as PubSub from "effect/PubSub"; +import type * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; + +import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; +import * as MilestoneHub from "../milestones/MilestoneHub.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; + +const withStore = ( + use: Effect.Effect, +) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-store-" }); + const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") }); + const migrated = Layer.effectDiscard(WorkflowsMigration); + return yield* Effect.provide( + use, + WorkflowStore.layer.pipe( + Layer.provideMerge(Layer.merge(migrated, MilestoneHub.layer)), + Layer.provide(database), + ), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); + +it.effect("a run still waits while one of the things it started side by side is out", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + yield* store.runStarted({ + runId: "r1", + workflow: "duo", + version: 1, + engineTag: "duo@1", + idempotencyKey: "k", + input: {}, + }); + // Started again under its key: nothing changed, so nobody is told. + yield* Effect.scoped( + Effect.gen(function* () { + const told = yield* PubSub.subscribe(store.changes); + yield* store.runStarted({ + runId: "r1", + workflow: "duo", + version: 1, + engineTag: "duo@1", + idempotencyKey: "k", + input: {}, + }); + assert.equal(yield* PubSub.remaining(told), 0); + }), + ); + const now = Effect.map(store.run("r1"), (run) => [run?.status, run?.detail]); + yield* store.stepStarted("r1", "left", "agent"); + yield* store.stepStarted("r1", "right", "agent"); + yield* store.stepStarted("r1", "approve", "ask"); + yield* store.runStatus("r1", "waiting", "agent left"); + + yield* store.stepEnded("r1", "left", "completed", null); + yield* store.runResumed("r1"); + assert.deepStrictEqual(yield* now, ["waiting", "agent right"]); + + yield* store.stepEnded("r1", "right", "completed", null); + yield* store.runResumed("r1"); + assert.deepStrictEqual(yield* now, ["waiting", "approve"]); + + yield* store.stepEnded("r1", "approve", "completed", null); + yield* store.runResumed("r1"); + assert.deepStrictEqual(yield* now, ["running", null]); + + // One of them failed and paused the run: the others ending do not take that back. + yield* store.stepStarted("r1", "again", "agent"); + yield* store.stepStarted("r1", "beside", "agent"); + yield* store.stepStarted("r1", "later", "wait"); + yield* store.runPaused("r1", "again gave up", true); + yield* store.stepEnded("r1", "beside", "completed", null); + yield* store.runResumed("r1"); + yield* store.runStatus("r1", "waiting", "later"); + const paused = yield* store.run("r1"); + assert.deepStrictEqual( + [paused?.status, paused?.detail, Number(paused?.pauses), Number(paused?.held)], + ["paused", "again gave up", 1, 1], + ); + // The sweep's resume is for the pause it read, not for one that came after it. + assert.isTrue(yield* store.runUnpaused("r1")); + yield* store.runPaused("r1", "gave up again"); + assert.isFalse( + yield* store.runUnpaused("r1", { pauses: 1, updatedAt: paused?.updated_at ?? "" }), + ); + assert.equal((yield* store.run("r1"))?.status, "paused"); + }), + ), +); + +it.effect("a key is taken by the first run started under it, whatever its version", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + for (const version of [1, 2]) { + yield* store.runStarted({ + runId: `r${version}`, + workflow: "fix", + version, + engineTag: `fix@${version}`, + idempotencyKey: "k", + input: {}, + }); + } + assert.isUndefined(yield* store.run("r2")); + assert.equal((yield* store.runByKey("fix", "k"))?.run_id, "r1"); + }), + ), +); + +it.effect("keeps each thing a run touched once, with what the latest touch knew", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const issue = { kind: "issue", key: "i1", address: { scope: "me/app", key: "1" } }; + yield* store.referenceNoted("r1", null, { + ...issue, + title: "Crash", + url: "https://x/1", + state: "open", + }); + yield* store.referenceNoted("r1", "triage", { ...issue, title: "" }); + // A kind the engine has never heard of comes back as it went in. + const machine = { kind: "machine", key: "m1", address: { id: [1, 2] }, title: "box" }; + yield* store.referenceNoted("r1", "make", machine); + yield* store.referenceNoted("r1", "fix", { + ...issue, + title: "Crash at noon", + state: "closed", + }); + yield* Effect.scoped( + Effect.gen(function* () { + const told = yield* PubSub.subscribe(store.changes); + // Seen again by a step that already touched it, with nothing new: nobody is told. + yield* store.referenceNoted("r1", "triage", { ...issue, title: "" }); + assert.equal(yield* PubSub.remaining(told), 0); + }), + ); + assert.deepStrictEqual(yield* store.references("r1"), [ + { + ...issue, + title: "Crash at noon", + url: "https://x/1", + state: "closed", + steps: ["triage", "fix"], + origin: "trigger", + }, + { ...machine, url: null, state: null, steps: ["make"], origin: "step" }, + ]); + assert.deepStrictEqual(yield* store.references("r2"), []); + }), + ), +); + +it.effect("counts what waits on a person, and finds the run's latest agent thread", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const start = (runId: string) => + store.runStarted({ + runId, + workflow: "fix", + version: 1, + engineTag: "fix@1", + idempotencyKey: runId, + input: {}, + }); + assert.deepStrictEqual(yield* store.counts, { needsYou: 0, active: 0, total: 0 }); + yield* Effect.forEach(["r1", "r2", "r3"], start); + yield* store.runPaused("r1", "the build failed"); + assert.isTrue(yield* store.runEnded("r3", "completed", null, null)); + // A second ending, such as a cancel that lost the race, is not recorded and says so. + assert.isFalse(yield* store.runEnded("r3", "cancelled", "late", null)); + assert.equal((yield* store.run("r3"))?.status, "completed"); + // Every run still going, with no list limit: the guard on dropping a version reads this. + assert.equal((yield* store.unfinished).length, 2); + yield* store.waitOpened({ + runId: "r2", + name: "merge", + workflow: "fix", + key: undefined, + token: "t", + schemaJson: "{}", + requestJson: '{"title":"Merge?"}', + watchJson: null, + deadline: null, + }); + // A paused run and an open question each wait on someone; a plain wait does not. + yield* store.waitOpened({ + runId: "r2", + name: "ci", + workflow: "fix", + key: undefined, + token: "u", + schemaJson: "{}", + requestJson: null, + watchJson: null, + deadline: null, + }); + assert.deepStrictEqual(yield* store.counts, { needsYou: 2, active: 2, total: 3 }); + + assert.isNull(yield* store.latestThread("r2")); + yield* store.stepStarted("r2", "write", "agent"); + yield* store.stepThread("r2", "write", "thread-1", null, "turn-1"); + yield* store.stepStarted("r2", "review", "agent"); + yield* store.stepThread("r2", "review", "thread-2", "env-b", "turn-2"); + assert.deepStrictEqual(yield* store.latestThread("r2"), { + threadId: "thread-2", + environmentId: "env-b", + }); + }), + ), +); + +it.effect("one buffered signal goes to one wait, and a claimed wait keeps what woke it", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const open = (runId: string) => + Effect.andThen( + store.runStarted({ + runId, + workflow: "gate", + version: 1, + engineTag: "gate@1", + idempotencyKey: runId, + input: {}, + }), + store.waitOpened({ + runId, + name: "go", + workflow: "gate", + key: "ready", + token: `token-${runId}`, + schemaJson: "{}", + requestJson: null, + watchJson: null, + deadline: null, + }), + ); + yield* open("r1"); + yield* open("r2"); + // The parts of an address are kept apart: this one is for another workflow's other key. + yield* store.mailPut({ + signalId: "other", + address: { workflow: "gate:ready", channel: "x" }, + valueJson: "1", + expiresAt: "2999-01-01T00:00:00.000Z", + }); + assert.isUndefined(yield* store.mailNext([{ workflow: "gate", channel: "ready:x" }])); + + yield* store.mailPut({ + signalId: "s1", + address: { workflow: "gate", channel: "ready" }, + valueJson: '"yes"', + expiresAt: "2999-01-01T00:00:00.000Z", + }); + const woke = { expired: false, value: "yes" }; + assert.equal(yield* store.mailDeliver("s1", "r1", "go", woke), "delivered"); + // The second wait finds the signal gone and stays open for the next one. + assert.equal(yield* store.mailDeliver("s1", "r2", "go", woke), "gone"); + assert.isDefined(yield* store.waitAt({ runId: "r2", wait: "go" })); + assert.isTrue(yield* store.signalSeen("s1")); + // Nor can the id, sent again straight to that wait, claim it: one id wakes one wait. + assert.isFalse(yield* store.waitSignalled("r2", "go", woke, "s1")); + assert.isDefined(yield* store.waitAt({ runId: "r2", wait: "go" })); + // And a kept copy of an id that already woke a wait straight wakes none: the two sends of a + // retry that overlapped, one buffered and one delivered. + yield* store.mailPut({ + signalId: "s1", + address: { workflow: "gate", channel: "ready" }, + valueJson: '"yes"', + expiresAt: "2999-01-01T00:00:00.000Z", + }); + assert.equal(yield* store.mailDeliver("s1", "r2", "go", woke), "gone"); + assert.isDefined(yield* store.waitAt({ runId: "r2", wait: "go" })); + // It is dropped, so a wait looking through its mail is not handed it again. + assert.isUndefined(yield* store.mailNext([{ workflow: "gate", channel: "ready" }])); + // A wait that is already claimed takes no second wake. + assert.equal(yield* store.mailDeliver("other", "r1", "go", woke), "claimed"); + + // Its wake is redone once the claim has gone unanswered for a while. + assert.deepStrictEqual(yield* store.waitsToWake, []); + yield* TestClock.adjust("1 minute"); + const again = yield* store.waitsToWake; + assert.deepStrictEqual( + again.map((wait) => [wait.run_id, wait.woke_json]), + [["r1", JSON.stringify(woke)]], + ); + + // An id is remembered as long as its signal could have been kept, so a sender's retry + // within a long time to live is still the same signal. + yield* open("r3"); + yield* store.mailPut({ + signalId: "long", + address: { runId: "r3", wait: "go" }, + valueJson: '"yes"', + expiresAt: "1970-01-31T00:00:00.000Z", + }); + assert.equal(yield* store.mailDeliver("long", "r3", "go", woke), "delivered"); + yield* TestClock.adjust("10 days"); + yield* store.mailExpire; + assert.isTrue(yield* store.signalSeen("long")); + }), + ), +); + +it.effect("tells the milestone hub of each run and question transition once", () => + withStore( + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const hub = yield* MilestoneHub.MilestoneHub; + const start = { + runId: "r1", + workflow: "review", + version: 1, + engineTag: "review@1", + idempotencyKey: "k", + input: {}, + }; + const ask = (name: string, request: Schema.Json) => + store.waitOpened({ + runId: "r1", + name, + workflow: "review", + key: undefined, + token: `token-${name}`, + schemaJson: "{}", + requestJson: WorkflowStore.jsonText(request), + watchJson: null, + deadline: null, + }); + yield* store.runStarted(start); + yield* store.runStarted(start); + yield* ask("approve", { title: "Ship it?" }); + yield* ask("approve", { title: "Ship it?" }); + // A wait nobody is asked is no question. + yield* store.waitOpened({ + runId: "r1", + name: "checks", + workflow: "review", + key: undefined, + token: "token-checks", + schemaJson: "{}", + requestJson: null, + watchJson: null, + deadline: null, + }); + yield* store.waitSignalled("r1", "approve", { expired: false, value: true }); + yield* store.waitSignalled("r1", "approve", { expired: false, value: false }); + yield* store.waitSignalled("r1", "checks", { expired: false, value: null }); + yield* ask("later", {}); + yield* store.waitSignalled("r1", "later", { expired: true, value: null }); + yield* ask("last", { title: "Anything else?" }); + yield* store.runPaused("r1", "agent failed"); + yield* store.runPaused("r1", "agent failed again"); + yield* store.runUnpaused("r1"); + yield* store.runUnpaused("r1"); + // A run another run invoked is muted unless asked for, as a subagent's thread is. + yield* store.runStarted({ + ...start, + runId: "r2", + idempotencyKey: "child", + parent: { runId: "r1", wait: "child" }, + }); + yield* store.runEnded("r1", "cancelled", "stopped by a person", null); + yield* store.runEnded("r1", "completed", null, null); + + assert.notInclude( + (yield* hub.recent()).events.map((event) => event.workflowRunId), + "r2", + ); + const { events } = yield* hub.recent({ filter: { includeSubagentChildren: true } }); + assert.deepStrictEqual( + events.map((event): unknown => { + const { id: _id, occurredAt: _at, ...rest } = event; + return rest; + }), + [ + { type: "workflow.run_started" }, + { type: "workflow.needs_input", step: "approve", question: "Ship it?" }, + { type: "workflow.input_resolved", step: "approve", resolution: "answered" }, + { type: "workflow.needs_input", step: "later", question: "later" }, + { type: "workflow.input_resolved", step: "later", resolution: "expired" }, + { type: "workflow.needs_input", step: "last", question: "Anything else?" }, + { type: "workflow.run_paused", reason: "agent failed" }, + { type: "workflow.run_resumed" }, + { + type: "workflow.run_started", + isSubagentChild: true, + workflowRunId: "r2", + runTitle: "review child", + parentWorkflowRunId: "r1", + }, + { type: "workflow.input_resolved", step: "last", resolution: "cancelled" }, + { type: "workflow.run_ended", outcome: "cancelled", detail: "stopped by a person" }, + ].map((news) => ({ + projectId: null, + threadId: null, + parentThreadId: null, + actor: { type: "system" }, + isSubagentChild: false, + workflowRunId: "r1", + workflow: "review", + runTitle: "review k", + parentWorkflowRunId: null, + ...news, + })), + ); + }), + ), +); diff --git a/apps/server/src/workflows/WorkflowStore.ts b/apps/server/src/workflows/WorkflowStore.ts new file mode 100644 index 0000000000000..17d2b4c4bf358 --- /dev/null +++ b/apps/server/src/workflows/WorkflowStore.ts @@ -0,0 +1,1142 @@ +import { + type MilestoneEvent, + MilestoneId, + type WorkflowCounts, + WorkflowRun, + type WorkflowRunReference, + WorkflowRunStatus, + WorkflowStep, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as PubSub from "effect/PubSub"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as MilestoneHub from "../milestones/MilestoneHub.ts"; + +export { WorkflowRun, WorkflowRunStatus, WorkflowStep }; + +/** Where a signal goes: one wait of one run, or whichever run of a workflow waits on a channel. */ +export type SignalAddress = + | { readonly runId: string; readonly wait: string } + | { readonly workflow: string; readonly channel: string }; + +/** The run that invoked another, and the wait in it that hears how the other ended. */ +export interface RunParent { + readonly runId: string; + readonly wait: string; +} + +export interface RunRow { + readonly run_id: string; + readonly workflow: string; + readonly idempotency_key: string; + readonly version: number | bigint; + readonly engine_tag: string; + readonly title: string; + readonly status: WorkflowRunStatus; + readonly detail: string | null; + readonly result_json: string | null; + readonly input_json: string | null; + readonly parent_run_id: string | null; + readonly parent_wait: string | null; + readonly pauses: number | bigint; + /** Paused until a person resumes it, whatever the workflow's `resumeAfter` says. */ + readonly held: number | bigint; + readonly started_at: string; + readonly updated_at: string; + readonly ended_at: string | null; +} +export interface StepRow { + readonly name: string; + readonly kind: WorkflowStep["kind"]; + readonly status: WorkflowStep["status"]; + readonly attempts: number | bigint; + readonly detail: string | null; + readonly thread_id: string | null; + readonly environment_id: string | null; + readonly result_json: string | null; + readonly said: string | null; + readonly started_at: string; + readonly ended_at: string | null; +} +export interface WaitRow { + readonly run_id: string; + readonly name: string; + readonly token: string; + readonly schema_json: string; + readonly request_json: string | null; + readonly watch_json: string | null; + readonly deadline: string | null; + readonly opened_at: string; + /** What it was woken with, once it has been. */ + readonly woke_json: string | null; +} + +/** Something a run touched, as the one that touched it knows it. */ +export interface ReferenceInput { + readonly kind: string; + readonly key: string; + readonly address: Schema.Json; + /** Empty when the toucher does not know it; a title already kept stays. */ + readonly title: string; + readonly url?: string | null | undefined; + readonly state?: string | null | undefined; +} +interface ReferenceRow { + readonly kind: string; + readonly key: string; + readonly address_json: string; + readonly title: string; + readonly url: string | null; + readonly state: string | null; + readonly steps_json: string; + readonly origin: WorkflowRunReference["origin"]; +} + +// Rows keep JSON as text. Everything stored was a JSON value when it was written. +export const jsonText = (value: Schema.Json): string => JSON.stringify(value); +export const jsonValue = (text: string): Schema.Json => JSON.parse(text) as Schema.Json; + +const now = Effect.map(DateTime.now, DateTime.formatIso); + +type WorkflowMilestone = Extract; +/** What a workflow milestone says beyond its envelope and its run. */ +type WorkflowMilestoneNews = WorkflowMilestone extends infer Event + ? Event extends WorkflowMilestone + ? Omit< + Event, + | "id" + | "occurredAt" + | "projectId" + | "threadId" + | "parentThreadId" + | "actor" + | "isSubagentChild" + | "workflowRunId" + | "workflow" + | "runTitle" + | "parentWorkflowRunId" + > + : never + : never; +// A wake is one write away from its claim. A claim this old without its run moving had none. +const WAKE_REDONE_AFTER = Duration.seconds(30); +// Long enough for a sender's retries, short enough that the table stays small. +// Enough to read what a step said; the page that shows it is not a place for a whole report. +const STEP_RESULT_KEPT = 8_000; +const SIGNAL_IDS_KEPT = Duration.days(7); +const REFERENCE_TITLE_KEPT = 300; +const idsKeptUntil = Effect.map(DateTime.now, (at) => + DateTime.formatIso(DateTime.addDuration(at, SIGNAL_IDS_KEPT)), +); +// A tuple, so no name or key can be read as part of the other. +const mailAddress = (address: SignalAddress) => + JSON.stringify( + "runId" in address + ? ["run", address.runId, address.wait] + : ["key", address.workflow, address.channel], + ); + +export class WorkflowStore extends Context.Service< + WorkflowStore, + { + readonly changes: PubSub.PubSub; + readonly runStarted: (run: { + readonly runId: string; + readonly workflow: string; + readonly version: number; + readonly engineTag: string; + readonly idempotencyKey: string; + readonly input: Schema.Json; + readonly parent?: RunParent | undefined; + }) => Effect.Effect; + readonly runStatus: ( + runId: string, + status: "running" | "waiting", + detail: string | null, + ) => Effect.Effect; + /** + * A wait or an agent of the run is over. The run is running again, unless another it started + * side by side is still out, which it then waits on. + */ + readonly runResumed: (runId: string) => Effect.Effect; + /** `held` unsaid keeps what the run had: a run put back to paused is still held. */ + readonly runPaused: (runId: string, detail: string, held?: boolean) => Effect.Effect; + /** + * A paused run is running again. With `current`, only while that is still the pause: the + * sweep's deadline was worked out from it. False when the run was not changed. + */ + readonly runUnpaused: ( + runId: string, + current?: { readonly pauses: number; readonly updatedAt: string }, + ) => Effect.Effect; + /** The person's resume has reached the engine, so the run no longer waits for one. */ + readonly runUnheld: (runId: string) => Effect.Effect; + readonly runEnded: ( + runId: string, + status: "completed" | "stopped" | "skipped" | "cancelled", + detail: string | null, + result: Schema.Json, + ) => Effect.Effect; + readonly runTitle: (runId: string, title: string) => Effect.Effect; + /** Marks the step running and returns how many times it has now been started. */ + readonly stepStarted: ( + runId: string, + name: string, + kind: WorkflowStep["kind"], + ) => Effect.Effect; + readonly stepEnded: ( + runId: string, + name: string, + status: "completed" | "failed", + detail: string | null, + ) => Effect.Effect; + readonly waitOpened: (wait: { + readonly runId: string; + readonly name: string; + readonly workflow: string; + readonly key: string | undefined; + readonly token: string; + readonly schemaJson: string; + /** What a person is asked, when this wait is a question. */ + readonly requestJson: string | null; + /** What the engine looks at to end this wait by itself. */ + readonly watchJson: string | null; + readonly deadline: string | null; + }) => Effect.Effect; + readonly waitClosed: (runId: string, name: string) => Effect.Effect; + /** The wait takes signals again, under a fresh wake: what woke it was not for it. */ + readonly waitReopened: (runId: string, name: string, token: string) => Effect.Effect; + /** Takes the wait for one signal. False when another signal already has it. */ + /** + * Claims an open wait for one wake and keeps what it is woken with. False when something else + * already claimed it. A signal's id is recorded with the claim, so a retry never claims twice. + */ + readonly waitSignalled: ( + runId: string, + name: string, + woke: Schema.Json, + signalId?: string, + ) => Effect.Effect; + /** Waits claimed a while ago whose runs are still not past them: their wake is redone. */ + readonly waitsToWake: Effect.Effect>; + /** The run's waits that were claimed and are still open, whose wakes a resume sends. */ + readonly waitsClaimed: (runId: string) => Effect.Effect>; + /** + * Hands one buffered signal to one wait, or to none: the claim and the removal happen + * together. `gone` when another wait took the signal, `claimed` when the wait was already woken. + */ + readonly mailDeliver: ( + signalId: string, + runId: string, + name: string, + woke: Schema.Json, + ) => Effect.Effect<"delivered" | "gone" | "claimed">; + /** Runs that were not ended while the run that invoked them was cancelled. */ + readonly orphans: Effect.Effect>; + /** Runs ended before `before`, with no step still going, whose engine journal is still kept. */ + readonly prunable: ( + before: string, + limit: number, + ) => Effect.Effect>; + readonly enginePruned: (runId: string) => Effect.Effect; + /** Every run in this state, however many: the sweep must not miss old ones past a page. */ + readonly everyRun: ( + status: "running" | "waiting" | "paused", + ) => Effect.Effect>; + /** What each run that has not ended is a run of, with no limit. */ + readonly unfinished: Effect.Effect< + ReadonlyArray<{ readonly workflow: string; readonly version: number }> + >; + /** Whether a signal with this id already woke a wait. */ + readonly signalSeen: (signalId: string) => Effect.Effect; + /** Counts one more arrival at `name` in this run and returns the count. */ + readonly mark: (runId: string, name: string) => Effect.Effect; + /** The runs this one invoked that have not ended. */ + readonly children: (runId: string) => Effect.Effect>; + /** The steps a cancelled run left in flight are over: nothing will end them. */ + readonly stepsCancelled: (runId: string, except: string) => Effect.Effect; + /** Cancelled runs whose `onEnd` has not completed and may still be tried, with its tries. */ + readonly runsToEnd: ( + step: string, + tries: number, + ) => Effect.Effect< + ReadonlyArray< + RunRow & { + readonly end_attempts: number | bigint | null; + readonly end_ended_at: string | null; + } + > + >; + /** Cancelled runs with a step other than `except` still going: their cancel was cut short. */ + readonly cancelsCutShort: (except: string) => Effect.Effect>; + /** Ended runs whose parent still waits to hear of it. */ + readonly untold: Effect.Effect>; + readonly stepThread: ( + runId: string, + name: string, + threadId: string, + environment: string | null, + turnId: string, + ) => Effect.Effect; + /** The threads of agent steps still running in this run, with each step's own turn. */ + readonly runningThreads: (runId: string) => Effect.Effect< + ReadonlyArray<{ + readonly threadId: string; + readonly environment?: string; + readonly turnId?: string; + }> + >; + readonly waitAt: (address: SignalAddress) => Effect.Effect; + /** Every open wait on `key`, in one workflow or in all of them. */ + readonly waitsOn: ( + key: string, + workflow: string | undefined, + ) => Effect.Effect>; + readonly waitsPastDeadline: Effect.Effect>; + readonly requests: Effect.Effect>; + /** Open waits the engine ends by looking at something. */ + readonly watches: Effect.Effect>; + /** The thread of the run's latest agent step, if it has had one. */ + readonly latestThread: ( + runId: string, + ) => Effect.Effect<{ readonly threadId: string; readonly environmentId: string | null } | null>; + readonly counts: Effect.Effect; + /** Keep what a step produced for a person to read. A large value is kept as its start. */ + readonly stepResult: ( + runId: string, + name: string, + value: Schema.Json, + /** What an agent said in closing, when its result is data and not that reply. */ + said?: string, + ) => Effect.Effect; + /** Say something about a step that is under way, such as when its sleep ends. */ + readonly stepDetail: (runId: string, name: string, detail: string) => Effect.Effect; + readonly mailPut: (mail: { + readonly signalId: string; + readonly address: SignalAddress; + readonly valueJson: string; + readonly expiresAt: string; + }) => Effect.Effect; + /** The oldest signal kept for any of these addresses, but `passed`. It stays until `mailDelete`. */ + readonly mailNext: ( + addresses: ReadonlyArray, + passed?: ReadonlySet, + ) => Effect.Effect< + | { + readonly signalId: string; + readonly valueJson: string; + readonly address: SignalAddress; + } + | undefined + >; + readonly mailDelete: (signalId: string) => Effect.Effect; + readonly mailExpire: Effect.Effect; + readonly run: (runId: string) => Effect.Effect; + /** The run a workflow was started as under `key`, of whichever version. */ + readonly runByKey: (workflow: string, key: string) => Effect.Effect; + readonly runs: (status: WorkflowRunStatus | undefined) => Effect.Effect>; + /** Runs by what they are a run of and what they were started as, newest first. */ + readonly runsWhere: (filter: { + readonly workflow?: string | undefined; + readonly status?: WorkflowRunStatus | undefined; + readonly keyPrefix?: string | undefined; + }) => Effect.Effect>; + readonly triggerNext: (triggerId: string) => Effect.Effect; + readonly triggerSet: (triggerId: string, nextAt: string) => Effect.Effect; + /** Forgets every trigger but these, so one that comes back starts over. */ + readonly triggersKeep: (triggerIds: ReadonlyArray) => Effect.Effect; + /** The hook's token: the one kept for it, or `fresh` from now on. */ + readonly hookToken: (hookId: string, fresh: string) => Effect.Effect; + readonly steps: (runId: string) => Effect.Effect>; + /** + * Keep that the run touched something: from a step, or with no step from what started it. A + * later touch of the same thing keeps what it knows that is new and adds its step. + */ + readonly referenceNoted: ( + runId: string, + step: string | null, + reference: ReferenceInput, + ) => Effect.Effect; + /** What the run touched, in the order it first did. */ + readonly references: (runId: string) => Effect.Effect>; + } +>()("t3/workflows/WorkflowStore") {} + +export const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const changes = yield* PubSub.unbounded(); + // A write here is bookkeeping for a run the engine already journaled: failing it would park a + // healthy run, so a database that cannot take it is a defect of the process instead. + const write = (runId: string, effect: Effect.Effect) => + effect.pipe(Effect.orDie, Effect.andThen(PubSub.publish(changes, runId)), Effect.asVoid); + const waitColumns = sql`run_id, name, token, schema_json, request_json, watch_json, deadline, opened_at, woke_json`; + + const hub = yield* Effect.serviceOption(MilestoneHub.MilestoneHub); + /** Tells the milestone hub of a transition this store just wrote, under an id stable for it. */ + const tell = Effect.fn("WorkflowStore.tell")(function* ( + runId: string, + key: string, + at: string, + news: WorkflowMilestoneNews, + ) { + if (Option.isNone(hub)) return; + const [run] = yield* sql>` + SELECT workflow, title, parent_run_id FROM workflow_runs WHERE run_id = ${runId} + `.pipe(Effect.orDie); + if (run === undefined) return; + yield* hub.value.publish({ + id: MilestoneId.make(`${news.type}:${key}`), + occurredAt: at, + projectId: null, + threadId: null, + parentThreadId: null, + actor: { type: "system" }, + isSubagentChild: run.parent_run_id !== null, + workflowRunId: runId, + workflow: run.workflow, + runTitle: run.title, + parentWorkflowRunId: run.parent_run_id, + ...news, + } as WorkflowMilestone); + }); + const questionTitle = (wait: Pick) => { + const request = wait.request_json === null ? null : jsonValue(wait.request_json); + const title = + request !== null && typeof request === "object" && !Array.isArray(request) + ? (request as { readonly title?: unknown }).title + : undefined; + return typeof title === "string" && title.trim() !== "" ? title : wait.name; + }; + /** A question claimed by an answer or its timeout is resolved, whichever claimed it. */ + const questionClaimed = Effect.fn("WorkflowStore.questionClaimed")(function* ( + runId: string, + name: string, + woke: Schema.Json, + at: string, + ) { + if (Option.isNone(hub)) return; + const [wait] = yield* sql>` + SELECT request_json, opened_at FROM workflow_waits WHERE run_id = ${runId} AND name = ${name} + `.pipe(Effect.orDie); + if (wait === undefined || wait.request_json === null) return; + const expired = + woke !== null && + typeof woke === "object" && + (woke as { readonly expired?: unknown }).expired === true; + yield* tell(runId, `${runId}:${name}:${wait.opened_at}`, at, { + type: "workflow.input_resolved", + step: name, + resolution: expired ? "expired" : "answered", + }); + }); + + return WorkflowStore.of({ + changes, + runStarted: Effect.fn("WorkflowStore.runStarted")(function* (run) { + const at = yield* now; + // A start under a key that already has its run changes nothing, and tells nobody. + const inserted = yield* sql` + INSERT INTO workflow_runs ( + run_id, workflow, version, engine_tag, idempotency_key, title, status, input_json, + parent_run_id, parent_wait, started_at, updated_at + ) VALUES ( + ${run.runId}, ${run.workflow}, ${run.version}, ${run.engineTag}, + ${run.idempotencyKey}, ${`${run.workflow} ${run.idempotencyKey}`}, 'running', + ${jsonText(run.input)}, ${run.parent?.runId ?? null}, ${run.parent?.wait ?? null}, + ${at}, ${at} + ) + ON CONFLICT DO NOTHING + RETURNING run_id + `.pipe(Effect.orDie); + if (inserted.length === 0) return; + yield* PubSub.publish(changes, run.runId); + yield* tell(run.runId, run.runId, at, { type: "workflow.run_started" }); + }), + runStatus: Effect.fn("WorkflowStore.runStatus")(function* (runId, status, detail) { + const at = yield* now; + yield* write( + runId, + sql` + UPDATE workflow_runs + SET status = ${status}, detail = ${detail}, updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + `, + ); + }), + runResumed: Effect.fn("WorkflowStore.runResumed")(function* (runId) { + const at = yield* now; + // One statement, so two of them ending at once cannot leave the run on one that has ended. + yield* write( + runId, + sql` + WITH out AS ( + SELECT CASE WHEN kind IN ('agent', 'sleep') THEN kind || ' ' || name ELSE name END + AS detail + FROM workflow_steps + WHERE run_id = ${runId} AND status = 'running' + AND kind IN ('wait', 'ask', 'agent', 'sleep') + ORDER BY started_at, rowid LIMIT 1 + ) + UPDATE workflow_runs + SET status = CASE WHEN EXISTS (SELECT 1 FROM out) THEN 'waiting' ELSE 'running' END, + detail = (SELECT detail FROM out), updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + `, + ); + }), + runPaused: Effect.fn("WorkflowStore.runPaused")(function* (runId, detail, held) { + const at = yield* now; + const reason = detail.slice(0, 2000); + const paused = yield* sql` + UPDATE workflow_runs + SET status = 'paused', detail = ${reason}, pauses = pauses + 1, + held = ${held === undefined ? sql`held` : held ? 1 : 0}, updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + RETURNING run_id + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + if (paused.length > 0) { + yield* tell(runId, `${runId}:${at}`, at, { type: "workflow.run_paused", reason }); + } + }), + runUnpaused: Effect.fn("WorkflowStore.runUnpaused")(function* (runId, current) { + const at = yield* now; + const rows = yield* sql` + UPDATE workflow_runs SET status = 'running', detail = NULL, updated_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL AND status = 'paused' + AND (${current === undefined ? 1 : 0} = 1 + OR (pauses = ${current?.pauses ?? 0} AND updated_at = ${current?.updatedAt ?? ""})) + RETURNING run_id + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + if (rows.length === 0) return false; + yield* tell(runId, `${runId}:${at}`, at, { type: "workflow.run_resumed" }); + return true; + }), + runUnheld: Effect.fn("WorkflowStore.runUnheld")(function* (runId) { + // A pause since then set its own `held`. + yield* write( + runId, + sql`UPDATE workflow_runs SET held = 0 WHERE run_id = ${runId} AND status != 'paused'`, + ); + }), + runEnded: Effect.fn("WorkflowStore.runEnded")(function* (runId, status, detail, result) { + const at = yield* now; + const resultJson = jsonText(result); + // False when another outcome was recorded first: the run ended some other way. + const ended = yield* sql + .withTransaction( + Effect.gen(function* () { + const rows = yield* sql` + UPDATE workflow_runs + SET status = ${status}, detail = ${detail}, result_json = ${resultJson}, + pauses = 0, updated_at = ${at}, ended_at = ${at} + WHERE run_id = ${runId} AND ended_at IS NULL + RETURNING run_id + `; + const closed = yield* sql>` + DELETE FROM workflow_waits WHERE run_id = ${runId} + RETURNING name, request_json, opened_at + `; + return { ended: rows.length > 0, closed }; + }), + ) + .pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + if (!ended.ended) return false; + for (const wait of ended.closed) { + if (wait.request_json === null) continue; + yield* tell(runId, `${runId}:${wait.name}:${wait.opened_at}`, at, { + type: "workflow.input_resolved", + step: wait.name, + resolution: "cancelled", + }); + } + yield* tell(runId, runId, at, { type: "workflow.run_ended", outcome: status, detail }); + return true; + }), + runTitle: Effect.fn("WorkflowStore.runTitle")(function* (runId, title) { + yield* write( + runId, + sql`UPDATE workflow_runs SET title = ${title.slice(0, 200)} WHERE run_id = ${runId}`, + ); + }), + stepStarted: Effect.fn("WorkflowStore.stepStarted")(function* (runId, name, kind) { + const at = yield* now; + const rows = yield* sql<{ attempts: number | bigint }>` + INSERT INTO workflow_steps (run_id, name, kind, status, attempts, started_at) + VALUES (${runId}, ${name}, ${kind}, 'running', 1, ${at}) + ON CONFLICT (run_id, name) DO UPDATE + SET status = 'running', attempts = attempts + 1, detail = NULL, ended_at = NULL, + started_at = excluded.started_at + RETURNING attempts + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, runId); + return Number(rows[0]?.attempts ?? 1); + }), + stepEnded: Effect.fn("WorkflowStore.stepEnded")(function* (runId, name, status, detail) { + const at = yield* now; + yield* write( + runId, + sql.withTransaction( + Effect.andThen( + sql` + UPDATE workflow_steps + SET status = ${status}, detail = ${detail === null ? null : detail.slice(0, 2000)}, ended_at = ${at} + WHERE run_id = ${runId} AND name = ${name} + `, + // A step that finished is progress: the next pause is the first in a row again. + status === "completed" + ? // Not while paused: a step beside the one that failed is no progress past it. + sql` + UPDATE workflow_runs SET pauses = 0 + WHERE run_id = ${runId} AND ended_at IS NULL AND status != 'paused' + ` + : Effect.void, + ), + ), + ); + }), + waitOpened: Effect.fn("WorkflowStore.waitOpened")(function* (wait) { + const at = yield* now; + const opened = yield* sql` + INSERT INTO workflow_waits ( + run_id, name, workflow, token, key, schema_json, request_json, watch_json, deadline, + opened_at + ) VALUES ( + ${wait.runId}, ${wait.name}, ${wait.workflow}, ${wait.token}, ${wait.key ?? null}, + ${wait.schemaJson}, ${wait.requestJson}, ${wait.watchJson}, ${wait.deadline}, ${at} + ) + ON CONFLICT (run_id, name) DO NOTHING + RETURNING name + `.pipe(Effect.orDie); + yield* PubSub.publish(changes, wait.runId); + if (opened.length === 0 || wait.requestJson === null) return; + yield* tell(wait.runId, `${wait.runId}:${wait.name}:${at}`, at, { + type: "workflow.needs_input", + step: wait.name, + question: questionTitle({ name: wait.name, request_json: wait.requestJson }), + }); + }), + waitClosed: Effect.fn("WorkflowStore.waitClosed")(function* (runId, name) { + yield* write( + runId, + sql`DELETE FROM workflow_waits WHERE run_id = ${runId} AND name = ${name}`, + ); + }), + waitReopened: Effect.fn("WorkflowStore.waitReopened")(function* (runId, name, token) { + yield* write( + runId, + sql` + UPDATE workflow_waits SET token = ${token}, signalled_at = NULL, woke_json = NULL + WHERE run_id = ${runId} AND name = ${name} + `, + ); + }), + waitSignalled: Effect.fn("WorkflowStore.waitSignalled")( + function* (runId, name, woke, signalId) { + const at = yield* now; + const taken = yield* sql` + UPDATE workflow_waits SET signalled_at = ${at}, woke_json = ${jsonText(woke)} + WHERE run_id = ${runId} AND name = ${name} AND signalled_at IS NULL + RETURNING name + `; + if (taken.length > 0 && signalId !== undefined) { + const receipt = yield* sql` + INSERT INTO workflow_signals (signal_id, kept_until) + VALUES (${signalId}, MAX(${yield* idsKeptUntil}, COALESCE( + (SELECT expires_at FROM workflow_mail WHERE signal_id = ${signalId}), '' + ))) + ON CONFLICT (signal_id) DO NOTHING + RETURNING signal_id + `; + // The id already woke a wait, so this one is not claimed: the transaction undoes it. + if (receipt.length === 0) return yield* Effect.fail("seen" as const); + } + return taken.length > 0; + }, + (effect, runId, name, woke) => + sql.withTransaction(effect).pipe( + Effect.catchIf( + (error) => error === "seen", + () => Effect.succeed(false), + ), + Effect.orDie, + Effect.tap((taken) => + taken + ? Effect.flatMap(now, (at) => questionClaimed(runId, name, woke, at)) + : Effect.void, + ), + ), + ), + waitsToWake: Effect.gen(function* () { + const before = DateTime.formatIso( + DateTime.subtractDuration(yield* DateTime.now, WAKE_REDONE_AFTER), + ); + return yield* sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE woke_json IS NOT NULL AND signalled_at <= ${before} + AND run_id IN (SELECT run_id FROM workflow_runs WHERE ended_at IS NULL) + `.pipe(Effect.orDie); + }), + waitsClaimed: Effect.fn("WorkflowStore.waitsClaimed")(function* (runId) { + return yield* sql` + SELECT ${waitColumns} FROM workflow_waits WHERE run_id = ${runId} AND woke_json IS NOT NULL + `.pipe(Effect.orDie); + }), + mailDeliver: Effect.fn("WorkflowStore.mailDeliver")(function* (signalId, runId, name, woke) { + const at = yield* now; + const outcome = yield* sql + .withTransaction( + Effect.gen(function* () { + // A kept copy of an id that already woke a wait straight is spent: it is dropped, so + // it wakes no second wait and is not offered again. + const seen = yield* sql`SELECT 1 FROM workflow_signals WHERE signal_id = ${signalId}`; + if (seen.length > 0) { + yield* sql`DELETE FROM workflow_mail WHERE signal_id = ${signalId}`; + return "gone" as const; + } + const claimed = yield* sql` + UPDATE workflow_waits SET signalled_at = ${at}, woke_json = ${jsonText(woke)} + WHERE run_id = ${runId} AND name = ${name} AND signalled_at IS NULL + RETURNING name + `; + if (claimed.length === 0) return "claimed" as const; + const taken = yield* sql<{ expires_at: string }>` + DELETE FROM workflow_mail WHERE signal_id = ${signalId} RETURNING expires_at + `; + // Failing undoes the claim: the wait stays open for a signal that is still there. + const copy = taken[0]; + if (copy === undefined) return yield* Effect.fail("gone" as const); + const keep = yield* idsKeptUntil; + const receipt = yield* sql` + INSERT INTO workflow_signals (signal_id, kept_until) + VALUES (${signalId}, ${copy.expires_at > keep ? copy.expires_at : keep}) + ON CONFLICT (signal_id) DO NOTHING + RETURNING signal_id + `; + // Delivered straight in the meantime: undone, and the next look drops the copy above. + if (receipt.length === 0) return yield* Effect.fail("gone" as const); + return "delivered" as const; + }), + ) + .pipe( + Effect.catchIf( + (error) => error === "gone", + () => Effect.succeed("gone" as const), + ), + Effect.orDie, + ); + if (outcome === "delivered") yield* questionClaimed(runId, name, woke, at); + return outcome; + }), + prunable: Effect.fn("WorkflowStore.prunable")(function* (before, limit) { + return yield* sql<{ run_id: string; engine_tag: string }>` + SELECT run_id, engine_tag FROM workflow_runs r + WHERE ended_at IS NOT NULL AND ended_at < ${before} AND engine_pruned_at IS NULL + AND NOT EXISTS ( + SELECT 1 FROM workflow_steps s WHERE s.run_id = r.run_id AND s.status = 'running' + ) + ORDER BY ended_at LIMIT ${limit} + `.pipe(Effect.orDie); + }), + enginePruned: Effect.fn("WorkflowStore.enginePruned")(function* (runId) { + const at = yield* now; + yield* sql` + UPDATE workflow_runs SET engine_pruned_at = ${at} WHERE run_id = ${runId} + `.pipe(Effect.orDie); + }), + orphans: sql` + SELECT c.* FROM workflow_runs c + JOIN workflow_runs p ON p.run_id = c.parent_run_id + WHERE c.ended_at IS NULL AND p.status = 'cancelled' + `.pipe(Effect.orDie), + unfinished: sql<{ workflow: string; version: number | bigint }>` + SELECT workflow, version FROM workflow_runs WHERE ended_at IS NULL + `.pipe( + Effect.map((rows) => + rows.map((row) => ({ workflow: row.workflow, version: Number(row.version) })), + ), + Effect.orDie, + ), + everyRun: Effect.fn("WorkflowStore.everyRun")(function* (status) { + return yield* sql`SELECT * FROM workflow_runs WHERE status = ${status}`.pipe( + Effect.orDie, + ); + }), + signalSeen: Effect.fn("WorkflowStore.signalSeen")(function* (signalId) { + const rows = yield* sql` + SELECT 1 FROM workflow_signals WHERE signal_id = ${signalId} + `.pipe(Effect.orDie); + return rows.length > 0; + }), + mark: Effect.fn("WorkflowStore.mark")(function* (runId, name) { + const rows = yield* sql<{ count: number | bigint }>` + INSERT INTO workflow_marks (run_id, name, count) VALUES (${runId}, ${name}, 1) + ON CONFLICT (run_id, name) DO UPDATE SET count = count + 1 + RETURNING count + `.pipe(Effect.orDie); + return Number(rows[0]?.count ?? 1); + }), + children: Effect.fn("WorkflowStore.children")(function* (runId) { + return yield* sql` + SELECT * FROM workflow_runs WHERE parent_run_id = ${runId} AND ended_at IS NULL + `.pipe(Effect.orDie); + }), + stepsCancelled: Effect.fn("WorkflowStore.stepsCancelled")(function* (runId, except) { + const at = yield* now; + yield* write( + runId, + sql` + UPDATE workflow_steps SET status = 'failed', detail = 'cancelled', ended_at = ${at} + WHERE run_id = ${runId} AND status = 'running' AND name != ${except} + `, + ); + }), + runsToEnd: Effect.fn("WorkflowStore.runsToEnd")(function* (step, tries) { + return yield* sql< + RunRow & { end_attempts: number | bigint | null; end_ended_at: string | null } + >` + SELECT r.*, s.attempts AS end_attempts, s.ended_at AS end_ended_at + FROM workflow_runs r + LEFT JOIN workflow_steps s ON s.run_id = r.run_id AND s.name = ${step} + WHERE r.status = 'cancelled' + AND (s.status IS NULL OR (s.status != 'completed' AND s.attempts < ${tries})) + `.pipe(Effect.orDie); + }), + cancelsCutShort: Effect.fn("WorkflowStore.cancelsCutShort")(function* (except) { + return yield* sql` + SELECT r.* FROM workflow_runs r + WHERE r.status = 'cancelled' AND EXISTS ( + SELECT 1 FROM workflow_steps s + WHERE s.run_id = r.run_id AND s.status = 'running' AND s.name != ${except} + ) + `.pipe(Effect.orDie); + }), + untold: sql` + SELECT c.* FROM workflow_waits w + JOIN workflow_runs c ON c.parent_run_id = w.run_id AND c.parent_wait = w.name + WHERE w.signalled_at IS NULL AND c.ended_at IS NOT NULL + `.pipe(Effect.orDie), + stepThread: Effect.fn("WorkflowStore.stepThread")( + function* (runId, name, threadId, environment, turnId) { + yield* write( + runId, + sql` + UPDATE workflow_steps + SET thread_id = ${threadId}, environment_id = ${environment}, turn_id = ${turnId} + WHERE run_id = ${runId} AND name = ${name} + `, + ); + }, + ), + runningThreads: Effect.fn("WorkflowStore.runningThreads")(function* (runId) { + const rows = yield* sql<{ + thread_id: string; + environment_id: string | null; + turn_id: string | null; + }>` + SELECT thread_id, environment_id, turn_id FROM workflow_steps + WHERE run_id = ${runId} AND status = 'running' AND thread_id IS NOT NULL + `.pipe(Effect.orDie); + return rows.map((row) => ({ + threadId: row.thread_id, + ...(row.environment_id === null ? {} : { environment: row.environment_id }), + ...(row.turn_id === null ? {} : { turnId: row.turn_id }), + })); + }), + waitAt: Effect.fn("WorkflowStore.waitAt")(function* (address) { + const rows = yield* ( + "runId" in address + ? sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE run_id = ${address.runId} AND name = ${address.wait} AND signalled_at IS NULL + ` + : sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE workflow = ${address.workflow} AND key = ${address.channel} AND signalled_at IS NULL + ORDER BY opened_at LIMIT 1 + ` + ).pipe(Effect.orDie); + return rows[0]; + }), + waitsOn: Effect.fn("WorkflowStore.waitsOn")(function* (key, workflow) { + return yield* sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE key = ${key} AND signalled_at IS NULL + AND (${workflow ?? null} IS NULL OR workflow = ${workflow ?? null}) + ORDER BY opened_at + `.pipe(Effect.orDie); + }), + waitsPastDeadline: Effect.flatMap(now, (at) => + sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE deadline IS NOT NULL AND deadline <= ${at} AND signalled_at IS NULL + `.pipe(Effect.orDie), + ), + latestThread: Effect.fn("WorkflowStore.latestThread")(function* (runId) { + const rows = yield* sql<{ thread_id: string; environment_id: string | null }>` + SELECT thread_id, environment_id FROM workflow_steps + WHERE run_id = ${runId} AND thread_id IS NOT NULL + ORDER BY started_at DESC, rowid DESC LIMIT 1 + `.pipe(Effect.orDie); + const row = rows[0]; + return row === undefined + ? null + : { threadId: row.thread_id, environmentId: row.environment_id }; + }), + counts: sql<{ questions: number; paused: number; active: number; total: number }>` + SELECT + (SELECT COUNT(*) FROM workflow_waits + WHERE request_json IS NOT NULL AND signalled_at IS NULL) AS questions, + (SELECT COUNT(*) FROM workflow_runs WHERE status = 'paused') AS paused, + (SELECT COUNT(*) FROM workflow_runs WHERE ended_at IS NULL) AS active, + (SELECT COUNT(*) FROM workflow_runs) AS total + `.pipe( + Effect.orDie, + Effect.map((rows) => ({ + needsYou: Number(rows[0]?.questions ?? 0) + Number(rows[0]?.paused ?? 0), + active: Number(rows[0]?.active ?? 0), + total: Number(rows[0]?.total ?? 0), + })), + ), + stepResult: Effect.fn("WorkflowStore.stepResult")(function* (runId, name, value, said) { + const full = jsonText(value); + const kept = + full.length <= STEP_RESULT_KEPT ? full : jsonText(`${full.slice(0, STEP_RESULT_KEPT)}…`); + const words = said?.trim() ?? ""; + const keptSaid = + words === "" + ? null + : words.length <= STEP_RESULT_KEPT + ? words + : `${words.slice(0, STEP_RESULT_KEPT)}…`; + yield* sql` + UPDATE workflow_steps SET result_json = ${kept}, said = ${keptSaid} + WHERE run_id = ${runId} AND name = ${name} + `.pipe(Effect.orDie); + }), + stepDetail: Effect.fn("WorkflowStore.stepDetail")(function* (runId, name, detail) { + yield* write( + runId, + sql`UPDATE workflow_steps SET detail = ${detail} WHERE run_id = ${runId} AND name = ${name}`, + ); + }), + requests: sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE request_json IS NOT NULL AND signalled_at IS NULL ORDER BY opened_at + `.pipe(Effect.orDie), + watches: sql` + SELECT ${waitColumns} FROM workflow_waits + WHERE watch_json IS NOT NULL AND signalled_at IS NULL ORDER BY opened_at + `.pipe(Effect.orDie), + mailPut: Effect.fn("WorkflowStore.mailPut")(function* (mail) { + yield* sql + .withTransaction( + Effect.andThen( + sql` + INSERT INTO workflow_mail (signal_id, address, value_json, expires_at) + VALUES (${mail.signalId}, ${mailAddress(mail.address)}, ${mail.valueJson}, ${mail.expiresAt}) + ON CONFLICT (signal_id) DO NOTHING + `, + // A copy kept by a retry that raced the first delivery outlives no receipt of it. + sql` + UPDATE workflow_signals SET kept_until = ${mail.expiresAt} + WHERE signal_id = ${mail.signalId} AND kept_until < ${mail.expiresAt} + `, + ), + ) + .pipe(Effect.orDie); + }), + mailNext: Effect.fn("WorkflowStore.mailNext")(function* (addresses, passed = new Set()) { + for (const address of addresses) { + const rows = yield* sql<{ signal_id: string; value_json: string }>` + SELECT signal_id, value_json FROM workflow_mail + WHERE address = ${mailAddress(address)} ORDER BY rowid + `.pipe(Effect.orDie); + const mail = rows.find((row) => !passed.has(row.signal_id)); + if (mail !== undefined) { + return { signalId: mail.signal_id, valueJson: mail.value_json, address }; + } + } + return undefined; + }), + mailDelete: Effect.fn("WorkflowStore.mailDelete")(function* (signalId) { + yield* sql`DELETE FROM workflow_mail WHERE signal_id = ${signalId}`.pipe(Effect.orDie); + }), + mailExpire: Effect.gen(function* () { + const at = yield* DateTime.now; + yield* sql`DELETE FROM workflow_mail WHERE expires_at <= ${DateTime.formatIso(at)}`; + yield* sql`DELETE FROM workflow_signals WHERE kept_until <= ${DateTime.formatIso(at)}`; + }).pipe(Effect.orDie), + run: Effect.fn("WorkflowStore.run")(function* (runId) { + const rows = yield* sql`SELECT * FROM workflow_runs WHERE run_id = ${runId}`.pipe( + Effect.orDie, + ); + return rows[0]; + }), + runByKey: Effect.fn("WorkflowStore.runByKey")(function* (workflow, key) { + const rows = yield* sql` + SELECT * FROM workflow_runs WHERE workflow = ${workflow} AND idempotency_key = ${key} + ORDER BY started_at LIMIT 1 + `.pipe(Effect.orDie); + return rows[0]; + }), + runsWhere: Effect.fn("WorkflowStore.runsWhere")(function* (filter) { + const prefix = filter.keyPrefix ?? null; + // A range, not LIKE, which would read `%` and `_` in a key as patterns. + return yield* sql` + SELECT * FROM workflow_runs + WHERE (${filter.workflow ?? null} IS NULL OR workflow = ${filter.workflow ?? null}) + AND (${filter.status ?? null} IS NULL OR status = ${filter.status ?? null}) + AND (${prefix} IS NULL OR ( + idempotency_key >= ${prefix} AND idempotency_key < ${`${prefix ?? ""}\u{10FFFF}`} + )) + ORDER BY started_at DESC, rowid DESC LIMIT 500 + `.pipe(Effect.orDie); + }), + runs: Effect.fn("WorkflowStore.runs")(function* (status) { + return yield* ( + status === undefined + ? // Skipped runs are counted apart, so a trigger that skips most of what it brings does + // not push the runs that did something out of the list. + sql` + SELECT * FROM ( + SELECT * FROM workflow_runs + WHERE NOT (status = 'skipped' AND parent_run_id IS NULL) + ORDER BY started_at DESC LIMIT 500 + ) + UNION ALL + SELECT * FROM ( + SELECT * FROM workflow_runs + WHERE status = 'skipped' AND parent_run_id IS NULL + ORDER BY started_at DESC LIMIT 500 + ) + ORDER BY started_at DESC + ` + : sql` + SELECT * FROM workflow_runs WHERE status = ${status} + ORDER BY started_at DESC LIMIT 500 + ` + ).pipe(Effect.orDie); + }), + triggerNext: Effect.fn("WorkflowStore.triggerNext")(function* (triggerId) { + const rows = yield* sql<{ next_at: string }>` + SELECT next_at FROM workflow_triggers WHERE trigger_id = ${triggerId} + `.pipe(Effect.orDie); + return rows[0]?.next_at; + }), + triggerSet: Effect.fn("WorkflowStore.triggerSet")(function* (triggerId, nextAt) { + yield* sql` + INSERT INTO workflow_triggers (trigger_id, next_at) VALUES (${triggerId}, ${nextAt}) + ON CONFLICT (trigger_id) DO UPDATE SET next_at = excluded.next_at + `.pipe(Effect.orDie); + }), + triggersKeep: Effect.fn("WorkflowStore.triggersKeep")(function* (triggerIds) { + const kept = yield* sql<{ trigger_id: string }>`SELECT trigger_id FROM workflow_triggers`; + for (const { trigger_id } of kept) { + if (triggerIds.includes(trigger_id)) continue; + yield* sql`DELETE FROM workflow_triggers WHERE trigger_id = ${trigger_id}`; + } + }, Effect.orDie), + hookToken: Effect.fn("WorkflowStore.hookToken")(function* (hookId, fresh) { + yield* sql` + INSERT INTO workflow_hooks (hook_id, token) VALUES (${hookId}, ${fresh}) + ON CONFLICT (hook_id) DO NOTHING + `; + const rows = yield* sql<{ token: string }>` + SELECT token FROM workflow_hooks WHERE hook_id = ${hookId} + `; + return rows[0]?.token ?? fresh; + }, Effect.orDie), + steps: Effect.fn("WorkflowStore.steps")(function* (runId) { + return yield* sql` + SELECT name, kind, status, attempts, detail, thread_id, environment_id, result_json, + said, started_at, ended_at + FROM workflow_steps WHERE run_id = ${runId} ORDER BY started_at, rowid + `.pipe(Effect.orDie); + }), + referenceNoted: Effect.fn("WorkflowStore.referenceNoted")(function* (runId, step, reference) { + const at = yield* now; + const addressJson = jsonText(reference.address); + const title = reference.title.slice(0, REFERENCE_TITLE_KEPT); + const changed = yield* sql + .withTransaction( + Effect.gen(function* () { + const rows = yield* sql` + SELECT kind, key, address_json, title, url, state, steps_json, origin + FROM workflow_run_references + WHERE run_id = ${runId} AND kind = ${reference.kind} AND key = ${reference.key} + `; + const row = rows[0]; + if (row === undefined) { + yield* sql` + INSERT INTO workflow_run_references ( + run_id, kind, key, address_json, title, url, state, steps_json, origin, noted_at + ) VALUES ( + ${runId}, ${reference.kind}, ${reference.key}, ${addressJson}, ${title}, + ${reference.url ?? null}, ${reference.state ?? null}, + ${jsonText(step === null ? [] : [step])}, ${step === null ? "trigger" : "step"}, + ${at} + ) + `; + return true; + } + const steps = jsonValue(row.steps_json) as ReadonlyArray; + const next = { + address_json: addressJson, + title: title === "" ? row.title : title, + url: reference.url ?? row.url, + state: reference.state ?? row.state, + steps_json: + step === null || steps.includes(step) ? row.steps_json : jsonText([...steps, step]), + }; + // A touch that says nothing new is no change, so a look every minute costs no list. + if ( + next.address_json === row.address_json && + next.title === row.title && + next.url === row.url && + next.state === row.state && + next.steps_json === row.steps_json + ) { + return false; + } + yield* sql` + UPDATE workflow_run_references + SET address_json = ${next.address_json}, title = ${next.title}, url = ${next.url}, + state = ${next.state}, steps_json = ${next.steps_json} + WHERE run_id = ${runId} AND kind = ${reference.kind} AND key = ${reference.key} + `; + return true; + }), + ) + .pipe(Effect.orDie); + if (changed) yield* PubSub.publish(changes, runId); + }), + references: Effect.fn("WorkflowStore.references")(function* (runId) { + const rows = yield* sql` + SELECT kind, key, address_json, title, url, state, steps_json, origin + FROM workflow_run_references WHERE run_id = ${runId} ORDER BY rowid + `.pipe(Effect.orDie); + return rows.map((row) => ({ + kind: row.kind, + key: row.key, + address: jsonValue(row.address_json), + title: row.title, + url: row.url, + state: row.state, + steps: jsonValue(row.steps_json) as ReadonlyArray, + origin: row.origin, + })); + }), + }); +}); + +export const layer = Layer.effect(WorkflowStore, make); diff --git a/apps/server/src/workflows/Workflows.test.ts b/apps/server/src/workflows/Workflows.test.ts new file mode 100644 index 0000000000000..cc56f6cd79a8a --- /dev/null +++ b/apps/server/src/workflows/Workflows.test.ts @@ -0,0 +1,2424 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { assert, it } from "@effect/vitest"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import { ProjectId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Latch from "effect/Latch"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; + +import { daily, every, Tick, webhook, WebhookRequest } from "./triggers.ts"; +import { issues, pullRequests } from "./forgeApi.ts"; +import { cancel, runs, signal, signalAll, start, store } from "./stepServices.ts"; +import { type InRun, invoke, skip, sleep, step, stop, title, wait, workflow } from "./workflow.ts"; +import { type AgentResult, WorkflowAgentError, WorkflowAgents } from "./WorkflowAgents.ts"; +import WorkflowsMigration from "../persistence/Migrations/110_Workflows.ts"; +import * as WorkflowEngine from "./WorkflowEngine.ts"; +import { + Issue, + pullRequestReferenceOf, + unavailable, + WorkflowForge, + WorkflowForgeError, +} from "./WorkflowForge.ts"; +import { issueReference, noteReference } from "./runReferences.ts"; +import { agent, ask } from "./workflowAgent.ts"; +import * as Workflows from "./Workflows.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; +import type { WorkflowRun, WorkflowRunStatus } from "./WorkflowStore.ts"; + +const once = { retry: { times: 0 } } as const; + +/** Holds the `work` step of an `owned` run in `busy` mode until the test lets it go. */ +interface Latch { + readonly entered: Deferred.Deferred; + readonly release: Deferred.Deferred; + readonly cleaned: Deferred.Deferred; + /** Holds the `bad` step of a `sibling` run until the test lets it go. */ + readonly bad: Deferred.Deferred; +} + +/** A workflow whose `flaky` step fails until `failures` reaches zero, counting every execution. */ +const definitions = ( + counts: Ref.Ref>, + failures: Ref.Ref, + latch: Latch, +) => { + const count = (name: string) => + Ref.updateAndGet(counts, (all) => ({ ...all, [name]: (all[name] ?? 0) + 1 })).pipe( + Effect.map((all) => all[name]!), + ); + return [ + workflow( + "owned", + { + version: 1, + payload: Schema.Struct({ mode: Schema.Literals(["finish", "stop", "hold", "busy"]) }), + // Counted by how the run ended, and failing for as long as `failures` says. + onEnd: (payload, end) => + Effect.gen(function* () { + // The engine's setting for reading integers must not reach a cleanup either. + if (yield* SqlClient.SafeIntegers) return yield* Effect.fail("SafeIntegers leaked"); + if (payload.mode === "busy") { + // Says whether the step it cleans up after had finished. + const all = yield* Ref.get(counts); + yield* count(`end:busy:${all["work"] === 1 ? "after" : "before"} work`); + return yield* Deferred.succeed(latch.cleaned, undefined); + } + const left = yield* Ref.getAndUpdate(failures, (rest) => Math.max(0, rest - 1)); + if (left > 0) return yield* Effect.fail("the machine would not go"); + yield* count(`end:${payload.mode}:${end.outcome}:${end.reason ?? ""}`); + }), + }, + (payload) => + Effect.gen(function* () { + if (payload.mode === "busy") { + yield* step( + "work", + { returns: Schema.Number }, + Effect.andThen( + Effect.andThen( + Deferred.succeed(latch.entered, undefined), + Deferred.await(latch.release), + ), + count("work"), + ), + ); + } + yield* step("take", { returns: Schema.Number, ...once }, count("take")); + if (payload.mode === "stop") return yield* stop("no need"); + if (payload.mode === "hold") yield* wait("go", { returns: Schema.String }); + }), + ), + workflow( + "flaky", + { + version: 1, + payload: Schema.Struct({ id: Schema.String, settle: Schema.optional(Schema.Boolean) }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + if (payload.settle === true) { + const tried = yield* step.try( + "settled", + { returns: Schema.Number }, + Effect.flatMap( + Ref.getAndUpdate(failures, (left) => Math.max(0, left - 1)), + (left) => (left > 0 ? Effect.fail("the dependency is down") : count("settled")), + ), + ); + return tried.outcome === "done" ? `settled ${tried.value}` : `gave up: ${tried.reason}`; + } + yield* step("before", { returns: Schema.Number, ...once }, count("before")); + const attempt = yield* step( + "flaky", + { returns: Schema.Number, ...once }, + Effect.flatMap( + Ref.getAndUpdate(failures, (left) => Math.max(0, left - 1)), + (left) => (left > 0 ? Effect.fail("the dependency is down") : count("flaky")), + ), + ); + return `done on attempt ${attempt}`; + }), + ), + /** Fails `bad` beside an open wait, as long as `failures` says. */ + workflow("sibling", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map( + Effect.all( + [ + step( + "bad", + { returns: Schema.Number, ...once }, + Effect.andThen( + Effect.andThen(Deferred.await(latch.bad), count("bad tries")), + Effect.flatMap( + Ref.getAndUpdate(failures, (left) => Math.max(0, left - 1)), + (left) => (left > 0 ? Effect.fail("the dependency is down") : count("bad")), + ), + ), + ), + wait("sib", { returns: Schema.String }), + ], + { concurrency: 2 }, + ), + ([bad, sib]) => `${bad} ${Option.getOrElse(sib, () => "none")}`, + ), + ), + workflow( + "review", + { + version: 1, + payload: Schema.Struct({ change: Schema.String, timeout: Schema.optional(Schema.String) }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + yield* title(`review of ${payload.change}`); + yield* sleep("settle", "1 millis"); + const [a, b] = yield* Effect.all( + [ + step("check/a", { returns: Schema.Number, ...once }, count("check/a")), + step("check/b", { returns: Schema.Number, ...once }, count("check/b")), + ], + { concurrency: 2 }, + ); + const verdict = yield* wait("verdict", { + returns: Schema.Struct({ merge: Schema.Boolean }), + channel: payload.change, + ...(payload.timeout === undefined ? {} : { timeout: "0 millis" }), + }); + if (Option.isNone(verdict)) return yield* stop("nobody answered"); + yield* step("after", { returns: Schema.Number, ...once }, count("after")); + return `${a + b} checks, merge: ${verdict.value.merge}`; + }), + ), + /** Reads a number from text, which its JSON Schema cannot say: any string fits that. */ + workflow("reading", { version: 1, payload: Schema.Struct({}), returns: Schema.Number }, () => + Effect.map( + wait("count", { returns: Schema.FiniteFromString }), + Option.getOrElse(() => -1), + ), + ), + workflow( + "broken", + { + version: 1, + payload: Schema.Struct({ + how: Schema.Literals(["dies", "unstorable", "undefined", "nested"]), + }), + }, + (payload): Effect.Effect => { + if (payload.how === "dies") { + return step( + "dies", + { returns: Schema.Void, ...once }, + Effect.die(new Error("null dereference")), + ); + } + if (payload.how === "undefined") { + // No `returns`: read as JSON reads it, without the undefined fields. + return Effect.map( + step.try("void", { returns: Schema.Void, ...once }, Effect.void), + (r) => ({ r, id: undefined, list: [undefined] }), + ); + } + if (payload.how === "nested") { + return step( + "nested", + { returns: Schema.Json, ...once }, + Effect.succeed({ deep: [{ id: undefined }] } as unknown as Schema.Json), + ); + } + return Effect.asVoid( + step("unstorable", { returns: Schema.Int, ...once }, Effect.succeed(1.5)), + ); + }, + ), + workflow("twice", { version: 1, payload: Schema.Struct({}) }, () => + Effect.gen(function* () { + yield* step("same", { returns: Schema.Void, ...once }, Effect.void); + yield* step("same", { returns: Schema.Void, ...once }, Effect.void); + }), + ), + workflow("reserved", { version: 1, payload: Schema.Struct({}) }, () => + step("onEnd", { returns: Schema.Void, ...once }, Effect.void), + ), + ...[1, 2].map((version) => + workflow("versioned", { version, payload: Schema.Struct({}), returns: Schema.Number }, () => + Effect.succeed(version), + ), + ), + ]; +}; + +/** Write a change, ask a person whether to merge it, then land it in the writer's own thread. */ +const tally = store.entry("tally", Schema.Number); +const stored = [ + /** Counts itself in the store, with the first try of the step failing after it counted. */ + workflow( + "tally", + { + version: 1, + payload: Schema.Struct({ wrong: Schema.optional(Schema.Boolean) }), + returns: Schema.Number, + }, + (payload) => + payload.wrong === true + ? step( + "read", + { returns: Schema.Number, ...once }, + Effect.as(store.entry("tally", Schema.String).get, 0), + ) + : step( + "count", + { returns: Schema.Number, ...once }, + tally + .update((current) => Option.getOrElse(current, () => 0) + 1) + .pipe(Effect.map(Option.getOrElse(() => 0))), + ), + ), + /** Waits in line for a door that `opener` opens. */ + workflow( + "door", + { version: 1, payload: Schema.Struct({ door: Schema.String }), returns: Schema.String }, + (payload) => + Effect.map( + wait("open", { returns: Schema.String, channel: payload.door }), + Option.getOrElse(() => "never"), + ), + ), + workflow( + "opener", + { version: 1, payload: Schema.Struct({ door: Schema.String, fail: Schema.Boolean }) }, + (payload) => + step( + "open", + { returns: Schema.Void, retry: { times: 1 } }, + Effect.gen(function* () { + // Written and taken back together when the step fails after writing. + yield* store.transaction( + Effect.gen(function* () { + yield* store.entry(`doors/${payload.door}`, Schema.String).set("open"); + const tries = yield* store + .entry(`tries/${payload.door}`, Schema.Number) + .update((current) => Option.getOrElse(current, () => 0) + 1); + if (payload.fail && Option.contains(tries, 1)) return yield* Effect.fail("slipped"); + }), + ); + yield* signal({ workflow: "door", channel: payload.door }, "came in"); + }), + ), + ), + /** Opens two doors, fails, and on its second try opens the second and a third. */ + workflow( + "relay", + { version: 1, payload: Schema.Struct({ doors: Schema.Array(Schema.String) }) }, + (payload) => + step( + "pass", + { returns: Schema.Void, retry: { times: 1 } }, + Effect.gen(function* () { + const tries = yield* store + .entry("relay-tries", Schema.Number) + .update((current) => Option.getOrElse(current, () => 0) + 1); + const [a, b, c] = payload.doors; + const doors = Option.contains(tries, 1) ? [a!, b!] : [b!, c!]; + for (const door of doors) yield* signal({ workflow: "door", channel: door }, "came in"); + if (Option.contains(tries, 1)) return yield* Effect.fail("slipped"); + }), + ), + ), +]; + +const kid = workflow( + "kid", + { + version: 1, + payload: Schema.Struct({ mode: Schema.Literals(["finish", "stop", "hold"]) }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + if (payload.mode === "stop") return yield* stop("nothing to do"); + if (payload.mode === "hold") yield* wait("go", { returns: Schema.String }); + return "grown"; + }), +); +const family = [ + kid, + /** Runs a kid as part of itself and reports how the kid ended. */ + workflow( + "parent", + { + version: 1, + payload: Schema.Struct({ mode: Schema.Literals(["finish", "stop", "hold"]) }), + returns: Schema.String, + }, + (payload) => + Effect.map(invoke("kid", kid, payload), (ended) => + ended.outcome === "completed" ? ended.value : `${ended.outcome}: ${ended.reason}`, + ), + ), + /** Invokes under a name a step of its own already has, or by a name and not the definition. */ + workflow( + "clash", + { version: 1, payload: Schema.Struct({ byName: Schema.optional(Schema.Boolean) }) }, + (payload) => + payload.byName === true + ? // Files are not type-checked, so this is what one that passes a name does. + invoke("child", "kid" as unknown as typeof kid, { mode: "finish" }) + : Effect.andThen( + step("kid", { returns: Schema.Void, ...once }, Effect.void), + invoke("kid", kid, { mode: "finish" }), + ), + ), + /** Starts two kids and does not wait for them. */ + workflow( + "spawner", + { version: 1, payload: Schema.Struct({}), returns: Schema.Array(Schema.String) }, + () => + step( + "spawn", + { returns: Schema.Array(Schema.String), ...once }, + Effect.forEach(["one", "two"], (key) => + Effect.map(start(kid, { mode: "finish" }, { key: `spawned/${key}` }), (run) => run.runId), + ), + ), + ), + /** Two agents at once, the second with a minute to finish. */ + workflow("pair", { version: 1, payload: Schema.Struct({}), returns: Schema.String }, () => + Effect.map( + Effect.all( + [ + agent("left", { brief: "Left.", project: "p1" }), + agent("right", { brief: "Right.", project: "p1", timeout: "1 minute" }), + ], + { concurrency: 2 }, + ), + ([left, right]) => `${left.value} ${right.value}`, + ), + ), +]; + +const fix = workflow( + "fix", + { + version: 1, + payload: Schema.Struct({ + project: Schema.String, + environment: Schema.optional(Schema.String), + // Lands with a model of its own, which a continued thread cannot take. + reshape: Schema.optional(Schema.Boolean), + /** The address of the issue the fix is for. */ + issue: Schema.optional(Schema.String), + }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + const written = yield* agent("write", { + brief: "Write the fix.", + project: payload.project, + ...(payload.environment === undefined ? {} : { environment: payload.environment }), + ...(payload.issue === undefined + ? {} + : { issue: { project: payload.project, url: payload.issue } }), + returns: Schema.Struct({ + branch: Schema.String, + commits: Schema.optional(Schema.Number.check(Schema.isGreaterThan(0))), + }), + }); + const answer = yield* ask("merge", { + title: `Merge ${written.value.branch}?`, + choices: ["Merge", "Leave"], + data: { branch: written.value.branch }, + }); + if (Option.isNone(answer) || answer.value.choice !== "Merge") return yield* stop("left"); + const landed = yield* agent("land", { + brief: "Land it.", + thread: written.thread, + ...(payload.reshape === true ? { model: { instanceId: "codex", model: "gpt" } } : {}), + }); + return `${written.value.branch}: ${landed.value}`; + }), +); + +/** Waits at a gate with others, until whoever keeps it lets everyone through. */ +const gate = workflow( + "gate", + { version: 1, payload: Schema.Struct({ gate: Schema.String }), returns: Schema.String }, + (payload) => + Effect.map( + wait("through", { returns: Schema.String, channel: payload.gate }), + Option.getOrElse(() => "never"), + ), +); +const control = [ + gate, + /** Looks at the runs at the gates, lets one gate's through, or sends one run away. */ + workflow( + "keeper", + { + version: 1, + payload: Schema.Struct({ act: Schema.Literals(["look", "open", "dismiss", "leave"]) }), + returns: Schema.Json, + }, + (payload, run) => + step( + "act", + { returns: Schema.Json, ...once }, + Effect.gen(function* () { + const waiting = yield* runs({ workflow: gate, keyPrefix: "visit/" }); + if (payload.act === "open") return yield* signalAll({ channel: "north" }, "go on"); + if (payload.act === "leave") return yield* Effect.as(cancel(run.id, "done here"), null); + if (payload.act === "dismiss") { + const last = waiting.find((visit) => visit.key === "visit/3"); + return yield* Effect.as(cancel(last?.id ?? "", "the gate is closed"), null); + } + return waiting.map((visit) => `${visit.key} ${visit.status}`).toSorted(); + }), + ), + ), + /** Gives the job to a second agent when the first one fails, and says how it went. */ + workflow( + "fallback", + { + version: 1, + payload: Schema.Struct({ + project: Schema.String, + timeout: Schema.optional(Schema.Literal("1 minute")), + /** Says which thread the first agent's failure came back with. */ + thread: Schema.optional(Schema.Boolean), + }), + returns: Schema.String, + }, + (payload) => + Effect.gen(function* () { + const output = Schema.Struct({ head: Schema.String }); + const first = yield* agent.try("first", { + brief: "Fix it.", + project: payload.project, + returns: output, + ...(payload.timeout === undefined ? {} : { timeout: payload.timeout }), + }); + if (first.outcome === "done") return first.value.head; + const second = yield* agent.try("second", { + brief: "Fix it.", + project: "p1", + returns: output, + }); + if (second.outcome === "failed") return yield* stop(second.reason); + const where = payload.thread === true ? ` in ${first.thread?.threadId ?? "no thread"}` : ""; + return `${second.value.head} after: ${first.reason}${where}`; + }), + ), +]; + +type Started = Parameters[0]; + +/** Agents the test plays: it sees each turn start and decides how that turn ends. */ +const fakeAgents = () => { + const turns = new Map< + string, + { started: Deferred.Deferred; ended: Deferred.Deferred } + >(); + const interrupted: Array<{ + readonly threadId: string; + readonly environment?: string | undefined; + readonly turnId?: string | undefined; + }> = []; + let threads = 0; + let refusals = 0; + const unreadable = new Set(); + const unanswered = new Set(); + const unstartable = new Set(); + const turn = (key: string) => { + const known = turns.get(key); + if (known !== undefined) return known; + const made = { + started: Deferred.makeUnsafe(), + ended: Deferred.makeUnsafe(), + }; + turns.set(key, made); + return made; + }; + return { + service: WorkflowAgents.of({ + start: (input) => + Effect.gen(function* () { + // The engine's own setting for reading integers must not reach what a step calls. + if (yield* SqlClient.SafeIntegers) { + return yield* new WorkflowAgentError({ reason: "SafeIntegers leaked into a step" }); + } + if (input.project === "nowhere" || unstartable.delete(input.key)) { + return yield* new WorkflowAgentError({ reason: "No project is registered there." }); + } + yield* Deferred.succeed(turn(input.key).started, input); + // As the threads do: the issue a thread is linked to is what its step touched. + if (input.issue !== undefined && "url" in input.issue) { + yield* noteReference({ + kind: "issue", + key: input.issue.url, + address: { url: input.issue.url }, + title: "", + }); + } + return { + threadId: input.thread ?? `thread-${++threads}`, + turnId: input.key, + ...(input.environment === undefined ? {} : { environment: input.environment }), + }; + }), + result: (started) => { + const once = (keys: Set) => + [...keys].some((key) => started.turnId.endsWith(`/${key}`) && keys.delete(key)); + if (once(unreadable)) { + return Effect.fail(new WorkflowAgentError({ reason: "the result could not be read" })); + } + return once(unanswered) ? Effect.never : Deferred.await(turn(started.turnId).ended); + }, + // Counted per try, so a retry of the same stop uses up a refusal too. + interrupt: (thread) => + Effect.gen(function* () { + if (yield* SqlClient.SafeIntegers) { + return yield* new WorkflowAgentError({ reason: "SafeIntegers leaked into a stop" }); + } + if (refusals-- > 0) return yield* new WorkflowAgentError({ reason: "the link is down" }); + interrupted.push(thread); + const ended = + thread.turnId !== undefined && turns.has(thread.turnId) + ? yield* Deferred.isDone(turns.get(thread.turnId)!.ended) + : false; + return ended ? ("ended" as const) : ("stopped" as const); + }), + }), + interrupted, + /** The next read of a turn with this key fails. */ + unreadableResult: (key: string) => { + unreadable.add(key); + }, + /** The next read of a turn with this key never answers, as one that is waited past. */ + unansweredResult: (key: string) => { + unanswered.add(key); + }, + /** The turn of `runId` with this key cannot be started. */ + unstartable: (runId: string, key: string) => { + unstartable.add(`${runId}/${key}`); + }, + /** Turns down the next `count` stops. */ + refuseStops: (count: number) => { + refusals = count; + }, + /** The turn of `runId` with this key, once it has been started. */ + started: (runId: string, key: string) => Deferred.await(turn(`${runId}/${key}`).started), + end: (runId: string, key: string, result: Partial) => + Deferred.succeed(turn(`${runId}/${key}`).ended, { + ending: "completed" as const, + detail: "", + reply: "", + ...result, + }), + }; +}; + +/** While set, `nightly` turns down every tick, so its start fails. */ +const ticks = { refused: false }; +const triggered = [ + workflow( + "nightly", + { + version: 1, + payload: Tick.check(Schema.makeFilter(() => !ticks.refused || "not now")), + returns: Schema.String, + triggers: [every("1 hour")], + }, + (tick) => Effect.succeed(tick.scheduledAt), + ), + workflow( + "morning", + { version: 1, payload: Tick, triggers: [daily("09:00", { weekdays: [1, 2, 3, 4, 5] })] }, + () => Effect.void, + ), + workflow( + "inbound", + { + version: 1, + payload: WebhookRequest, + triggers: [ + webhook("push", { + key: (request) => + request.headers["x-delivery"] ?? + (JSON.parse(request.body) as { readonly delivery?: string }).delivery, + }), + ], + }, + (request) => (request.body === "ping" ? skip("only a ping") : Effect.succeed(request.body)), + ), +]; + +const PROJECT = "/home/me/app"; +const triage = workflow( + "triage", + { + version: 1, + payload: Issue, + returns: Schema.String, + triggers: [issues.opened({ project: PROJECT, labels: ["bug"] })], + }, + Effect.fn(function* (issue) { + yield* step( + "thank", + { returns: Schema.Void }, + issues.comment(issue, `Looking at ${issue.title}.`), + ); + return issue.displayKey; + }), +); +const decodeIssue = Schema.decodeSync(Issue); +const land = workflow( + "land", + { version: 1, payload: Schema.Struct({ url: Schema.String }), returns: Schema.String }, + Effect.fn(function* (payload) { + const standing = yield* pullRequests.wait( + "checks", + { project: PROJECT, url: payload.url }, + { until: "checks", timeout: "1 hour" }, + ); + return Option.match(standing, { onNone: () => "gave up", onSome: (at) => at.checks }); + }), +); +const issueAt = (key: string, createdAt: string) => + decodeIssue({ + projectId: "project-1", + projectTitle: "app", + tracker: "github", + host: "github.com", + scope: "me/app", + key, + displayKey: `#${key}`, + title: `Issue ${key}`, + url: `https://github.com/me/app/issues/${key}`, + author: null, + state: { name: "open", category: "open" }, + createdAt, + updatedAt: createdAt, + closedAt: null, + assignees: [], + labels: [], + commentCount: 0, + }); +/** A tracker that lists what the test put in it and remembers what was said. */ +// The real trackers read the server's own tables, which do not decode under the engine's BigInts. +const asTheServerReads = (answer: () => A) => + Effect.flatMap(SqlClient.SafeIntegers, (bigInts) => + bigInts + ? Effect.fail(new WorkflowForgeError({ reason: "called with the engine's BigInts on" })) + : Effect.sync(answer), + ); + +const fakeForge = () => { + const open: Array = []; + const asked: Array[0]> = []; + const comments: Array = []; + const pullRequest = { + state: "open", + mergeability: "mergeable", + url: "https://github.com/me/app/pull/7", + checks: [{ name: "test", status: "pending", description: null, url: null }], + }; + return { + open, + asked, + comments, + pullRequest, + service: WorkflowForge.of({ + ...unavailable, + pullRequests: { + ...unavailable.pullRequests, + // Only what a wait looks at; the rest of a pull request is the host's business. + read: () => + asTheServerReads(() => structuredClone(pullRequest)).pipe( + Effect.tap((read) => + noteReference( + pullRequestReferenceOf( + { + projectId: ProjectId.make("project-1"), + host: "github.com", + repository: "me/app", + number: 7, + }, + { url: read.url, state: read.state }, + ), + ), + ), + Effect.map((read) => read as never), + ), + }, + issues: { + ...unavailable.issues, + list: (query) => + asTheServerReads(() => { + asked.push(query); + return open; + }), + comment: (issue, body) => + asTheServerReads( + () => void comments.push(`${"key" in issue ? issue.key : issue.url}: ${body}`), + ).pipe( + Effect.andThen("key" in issue ? noteReference(issueReference(issue)) : Effect.void), + ), + }, + }), + }; +}; + +const harness = Effect.fnUntraced(function* (store?: typeof WorkflowStore.layer) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflows-" }); + const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") }); + yield* Effect.provide(WorkflowsMigration, database); + const counts = yield* Ref.make>({}); + const failures = yield* Ref.make(0); + const latch: Latch = { + entered: yield* Deferred.make(), + release: yield* Deferred.make(), + cleaned: yield* Deferred.make(), + bad: yield* Deferred.make(), + }; + // One database file, so a second engine built from it is the server after a restart. + const agents = fakeAgents(); + const forge = fakeForge(); + const all = [ + triage, + land, + ...definitions(counts, failures, latch), + fix, + ...triggered, + ...stored, + ...family, + ...control, + ]; + const engineOf = (registered: typeof all) => + WorkflowEngine.layer(registered, store).pipe( + Layer.provide(Layer.succeed(WorkflowAgents, agents.service)), + Layer.provide(Layer.succeed(WorkflowForge, forge.service)), + Layer.provide(database), + Layer.provide(NodeCrypto.layer), + ); + // The engine polls its message store, backs off between retries and bounds its shutdown, all + // on the clock, so time runs for as long as a server is up, shutdown included. A test closes + // `clock` to hold time still until it has seen what it waits for. + const clock = yield* Latch.make(true); + /** With `registered`, a server whose files define only those. */ + const boot = (use: Effect.Effect, registered = all) => + Effect.raceFirst( + Effect.scoped(Effect.provide(use, engineOf(registered))), + Effect.forever(Effect.andThen(clock.await, TestClock.adjust("1 second"))), + ); + return { counts, failures, latch, boot, agents, forge, clock, database }; +}); + +/** The store the engine writes to, for a test to leave what a crash would have left. */ +const exposedStore = () => { + const made = Deferred.makeUnsafe(); + return { + layer: Layer.effect( + WorkflowStore.WorkflowStore, + Effect.tap(WorkflowStore.make, (store) => Deferred.succeed(made, store)), + ), + store: Deferred.await(made), + }; +}; + +/** The review workflow sleeps first, which is waiting too; this is its wait for a verdict. */ +const atVerdict = (run: WorkflowRun) => run.status === "waiting" && run.detail === "verdict"; +const status = + (...statuses: ReadonlyArray) => + (run: WorkflowRun) => + statuses.includes(run.status); + +it.effect( + "a failing step pauses its run, and resuming runs that step again and nothing before it", + () => + Effect.gen(function* () { + const { counts, failures, boot, database } = yield* harness(); + yield* Ref.set(failures, 2); + const runId = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start("flaky", { id: "a" }, { idempotencyKey: "a" }); + const again = yield* workflows.start("flaky", { id: "a" }, { idempotencyKey: "a" }); + assert.equal(again.runId, runId); + + const paused = yield* workflows.waitFor(runId, status("paused")); + assert.include(paused.detail ?? "", "the dependency is down"); + assert.equal(paused.pauses, 1); + // It says when it tries again by itself, which is after it paused. + assert.isTrue(paused.resumesAt !== null && paused.resumesAt > paused.updatedAt); + + yield* workflows.resume(runId); + const pausedAgain = yield* workflows.waitFor(runId, (run) => run.pauses === 2); + assert.equal(pausedAgain.status, "paused"); + return runId; + }), + ); + + // The server restarts while the run is paused. Nothing retries it until it is resumed. + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.equal((yield* workflows.get(runId)).run.status, "paused"); + yield* workflows.resume(runId); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "done on attempt 1"); + assert.equal(done.pauses, 0); + const { steps } = yield* workflows.get(runId); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.status, step.attempts]), + [ + ["before", "completed", 1], + ["flaky", "completed", 3], + ], + ); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { before: 1, flaky: 1 }); + + // An hour after it ended its engine journal goes, and starting its key again is still that run. + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const journal = Effect.flatMap( + SqlClient.SqlClient, + (sql) => sql<{ readonly n: number | bigint }>` + SELECT COUNT(*) AS n FROM cluster_messages WHERE entity_id = ${runId} + `, + ).pipe( + Effect.map((rows) => Number(rows[0]?.n ?? 0)), + Effect.provide(database), + ); + assert.isAbove(yield* journal, 0); + yield* TestClock.adjust("2 hours"); + yield* workflows.sweep; + assert.equal(yield* journal, 0); + const again = yield* workflows.start("flaky", { id: "a" }, { idempotencyKey: "a" }); + assert.equal(again.runId, runId); + assert.equal((yield* workflows.get(runId)).run.status, "completed"); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { before: 1, flaky: 1 }); + + // `step.try` hands the failure to the workflow instead of pausing, and runs once by default. + yield* Ref.set(failures, 1); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "flaky", + { id: "b", settle: true }, + { idempotencyKey: "b" }, + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "gave up: the dependency is down"); + assert.equal(done.pauses, 0); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal to a paused run is kept for the resume and does not run the failed step", () => + Effect.gen(function* () { + const { counts, failures, latch, boot } = yield* harness(); + yield* Ref.set(failures, 2); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start("sibling", {}, { idempotencyKey: "sib" }); + yield* workflows.waitFor(runId, (run) => run.status === "waiting" && run.detail === "sib"); + yield* Deferred.succeed(latch.bad, undefined); + yield* workflows.waitFor(runId, status("paused")); + assert.equal( + yield* workflows.signal({ runId, wait: "sib" }, "x", { id: "sib-x" }), + "delivered", + ); + yield* workflows.resume(runId); + const again = yield* workflows.waitFor(runId, (run) => run.pauses === 2); + assert.equal(again.status, "paused"); + yield* workflows.resume(runId); + const done = yield* workflows.waitFor(runId, status("completed", "paused")); + assert.deepStrictEqual([done.status, done.result], ["completed", "1 x"]); + const bad = (yield* workflows.get(runId)).steps.find((step) => step.name === "bad"); + assert.equal(bad?.attempts, 3); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { "bad tries": 3, bad: 1 }); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait survives a restart, checks what it is signalled with, and steps run once", () => + Effect.gen(function* () { + const { counts, boot } = yield* harness(); + const runId = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "review", + { change: "c1" }, + { idempotencyKey: "c1" }, + ); + const waiting = yield* workflows.waitFor(runId, atVerdict); + assert.equal(waiting.title, "review of c1"); + // The sleep before the wait is a step a person can see. + const slept = (yield* workflows.get(runId)).steps.find((step) => step.name === "settle"); + assert.deepStrictEqual([slept?.kind, slept?.status], ["sleep", "completed"]); + const wrong = yield* workflows + .signal({ runId, wait: "verdict" }, { merge: "yes" }, { id: "s0" }) + .pipe(Effect.flip); + assert.include(wrong.message, "merge"); + return runId; + }), + ); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // Addressed by key: the sender knows the change, not the run. + assert.equal( + yield* workflows.signal( + { workflow: "review", channel: "c1" }, + { merge: true }, + { id: "s1" }, + ), + "delivered", + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + }), + ); + assert.deepStrictEqual(yield* Ref.get(counts), { "check/a": 1, "check/b": 1, after: 1 }); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal its wait cannot read leaves the wait open for one it can", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start("reading", {}, { idempotencyKey: "t1" }); + yield* workflows.waitFor(runId, status("waiting")); + yield* workflows.signal({ runId, wait: "count" }, "many", { id: "t-many" }); + // Delivered straight or kept until the wait opens again: either way it is read. + yield* workflows.signal({ runId, wait: "count" }, "5", { id: "t-5" }); + const done = yield* workflows.waitFor(runId, status("completed", "paused")); + assert.deepStrictEqual([done.status, done.result], ["completed", 5]); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal sent before its wait opens is delivered when it does", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.equal( + yield* workflows.signal( + { workflow: "review", channel: "c2" }, + { merge: false }, + { id: "s2" }, + ), + "buffered", + ); + const { runId } = yield* workflows.start( + "review", + { change: "c2" }, + { idempotencyKey: "c2" }, + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: false"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a signal buffered as its wait opens is still delivered to that wait", () => + Effect.gen(function* () { + const looked = yield* Deferred.make(); + const opened = yield* Deferred.make(); + const checked = yield* Deferred.make(); + // Holds the signal between finding no wait and buffering, while the wait opens and finds no mail. + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.gen(function* () { + const real = yield* WorkflowStore.make; + let first = true; + return WorkflowStore.WorkflowStore.of({ + ...real, + waitAt: (address) => + Effect.tap(real.waitAt(address), () => { + if (!("channel" in address) || address.channel !== "c9" || !first) return Effect.void; + first = false; + return Effect.andThen(Deferred.succeed(looked, undefined), Deferred.await(opened)); + }), + mailNext: (addresses, passed) => + Effect.tap(real.mailNext(addresses, passed), (mail) => + mail === undefined && !first ? Deferred.succeed(checked, undefined) : Effect.void, + ), + }); + }), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const sent = yield* Effect.forkChild( + workflows.signal({ workflow: "review", channel: "c9" }, { merge: true }, { id: "s9" }), + ); + yield* Deferred.await(looked); + const { runId } = yield* workflows.start( + "review", + { change: "c9" }, + { idempotencyKey: "c9" }, + ); + // Released once the open wait has looked for mail and found none. + yield* Deferred.await(checked); + yield* Deferred.succeed(opened, undefined); + assert.equal(yield* Fiber.join(sent), "delivered"); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait another signal claimed first wakes with that signal's value", () => + Effect.gen(function* () { + // A second signal claims the wait just before the early mail is handed to it. + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.gen(function* () { + const real = yield* WorkflowStore.make; + return WorkflowStore.WorkflowStore.of({ + ...real, + mailDeliver: (signalId, runId, name, woke) => + Effect.andThen( + real.waitSignalled(runId, name, { expired: false, value: { merge: true } }), + real.mailDeliver(signalId, runId, name, woke), + ), + }); + }), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.equal( + yield* workflows.signal( + { workflow: "review", channel: "c8" }, + { merge: false }, + { id: "s8" }, + ), + "buffered", + ); + const { runId } = yield* workflows.start( + "review", + { change: "c8" }, + { idempotencyKey: "c8" }, + ); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait past its timeout wakes with nothing, and a workflow may stop on its own", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "review", + { change: "c3", timeout: "now" }, + { idempotencyKey: "c3" }, + ); + yield* workflows.waitFor(runId, atVerdict); + yield* workflows.sweep; + const stopped = yield* workflows.waitFor(runId, status("stopped")); + assert.equal(stopped.detail, "nobody answered"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a cancelled run ends, and two steps with one name pause their run", () => + Effect.gen(function* () { + // The start of `v3` is cut off once its row is written, before the engine has it. + const cutOff = new Set(["v3"]); + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + runStarted: (run) => + Effect.tap(real.runStarted(run), () => + cutOff.delete(run.idempotencyKey) ? Effect.die("the server stopped") : Effect.void, + ), + }), + ), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const waiting = yield* workflows.start( + "review", + { change: "c4" }, + { idempotencyKey: "c4" }, + ); + yield* workflows.waitFor(waiting.runId, atVerdict); + yield* workflows.cancel(waiting.runId, "not needed"); + const cancelled = (yield* workflows.get(waiting.runId)).run; + assert.equal(cancelled.status, "cancelled"); + assert.equal(cancelled.detail, "not needed"); + // A cancel with no reason gives none, rather than repeating that the run was cancelled. + const unexplained = yield* workflows.start( + "review", + { change: "c5" }, + { idempotencyKey: "c5" }, + ); + yield* workflows.waitFor(unexplained.runId, atVerdict); + yield* workflows.cancel(unexplained.runId); + assert.equal((yield* workflows.get(unexplained.runId)).run.detail, null); + // A signal for the wait it had is kept as mail, not delivered to a run that ended. + assert.equal( + yield* workflows.signal( + { runId: waiting.runId, wait: "verdict" }, + { merge: true }, + { id: "s4" }, + ), + "buffered", + ); + // A file written for the old `title(name, text)` is refused, not titled with the name. + assert.throws( + () => (title as (...args: ReadonlyArray) => unknown)("name", "Release v1"), + /takes only the text/, + ); + + const twice = yield* workflows.start("twice", {}, { idempotencyKey: "t1" }); + const paused = yield* workflows.waitFor(twice.runId, status("paused")); + assert.include(paused.detail ?? "", 'named "same"'); + // The cleanup step's name is taken by nothing else. + const reserved = yield* workflows.start("reserved", {}, { idempotencyKey: "r1" }); + const refusedName = yield* workflows.waitFor(reserved.runId, status("paused")); + assert.include(refusedName.detail ?? "", "cleanup step"); + + const missing = yield* workflows + .start("nothing", {}, { idempotencyKey: "n1" }) + .pipe(Effect.flip); + assert.equal(missing._tag, "WorkflowNotRegisteredError"); + // A version asked for by name is that version or nothing, never the latest instead. + const unknownVersion = yield* workflows + .start("twice", {}, { idempotencyKey: "t2", version: 2 }) + .pipe(Effect.flip); + assert.equal(unknownVersion.message, "Version 2 of workflow twice is not registered."); + const older = yield* workflows.start("versioned", {}, { idempotencyKey: "v1", version: 1 }); + const latest = yield* workflows.start("versioned", {}, { idempotencyKey: "v2" }); + assert.equal((yield* workflows.waitFor(older.runId, status("completed"))).result, 1); + assert.equal((yield* workflows.waitFor(latest.runId, status("completed"))).result, 2); + // A key is one run of the workflow, whichever version starts it again. + assert.deepStrictEqual( + yield* workflows.start("versioned", {}, { idempotencyKey: "v1" }), + older, + ); + // A start cut off between its row and the engine is executed by the next start. + const cut = yield* Effect.exit( + workflows.start("versioned", {}, { idempotencyKey: "v3", version: 1 }), + ); + assert.isTrue(Exit.isFailure(cut)); + const again = yield* workflows.start("versioned", {}, { idempotencyKey: "v3" }); + assert.equal((yield* workflows.waitFor(again.runId, status("completed"))).result, 1); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "an agent returns checked data, a person answers, and a later step continues the thread", + () => + Effect.gen(function* () { + let kept: WorkflowStore.WorkflowStore["Service"] | undefined; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.tap(WorkflowStore.make, (real) => Effect.sync(() => void (kept = real))), + ); + const { boot, agents } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "fix", + { project: "p1", issue: "https://github.com/me/app/issues/9" }, + { idempotencyKey: "f1" }, + ); + + const write = yield* agents.started(runId, "write/0"); + assert.equal(write.project, "p1"); + assert.equal(write.thread, undefined); + assert.deepStrictEqual( + [write.outputSchema?.required, write.outputSchema?.additionalProperties], + [["branch"], false], + ); + // The number's own check reaches the agent, without the text JSON spells Infinity in. + assert.deepStrictEqual( + (write.outputSchema?.properties as Record | undefined)?.commits, + { anyOf: [{ type: "number", exclusiveMinimum: 0 }, { type: "null" }] }, + ); + // It ended its turn without a result: the same thread is asked for it, not for the work. + yield* agents.end(runId, "write/0", { reply: "done" }); + const correction = yield* agents.started(runId, "write/0/correct/0"); + assert.equal(correction.thread, "thread-1"); + assert.include(correction.prompt, "without an accepted result"); + // What it then submitted does not fit, and it is told so, not that nothing came. + yield* agents.end(runId, "write/0/correct/0", { output: { branch: 1 } }); + const misfit = yield* agents.started(runId, "write/0/correct/1"); + assert.include(misfit.prompt, "The result you submitted does not fit: Expected string"); + yield* agents.end(runId, "write/0/correct/1", { + output: { branch: "fix/1" }, + reply: "Pushed fix/1.", + }); + + yield* workflows.waitFor(runId, (run) => run.detail === "merge"); + // A person reads what the agent said beside the data it returned. + const detail = yield* workflows.get(runId); + const written = detail.steps.find((step) => step.name === "write"); + assert.deepStrictEqual( + [written?.result, written?.said], + [{ branch: "fix/1" }, "Pushed fix/1."], + ); + // Asked three times on its issue's thread, the step touched the issue once. + assert.deepStrictEqual( + detail.references.map(({ key, steps, origin }) => ({ key, steps, origin })), + [{ key: "https://github.com/me/app/issues/9", steps: ["write"], origin: "step" }], + ); + const [question] = yield* workflows.questions; + // The agent whose work raised the question is one click from it. + assert.deepStrictEqual(question?.thread, { threadId: "thread-1", environmentId: null }); + assert.deepStrictEqual(question?.request, { + title: "Merge fix/1?", + choices: ["Merge", "Leave"], + data: { branch: "fix/1" }, + }); + const refused = yield* workflows + .signal({ runId, wait: "merge" }, { choice: "Maybe" }, { id: "a0" }) + .pipe(Effect.flip); + assert.include(refused.message, "merge waits for"); + // Clicked twice: one answer, and nothing kept to answer it again. + yield* Effect.all( + [ + workflows.answer(runId, "merge", { choice: "Merge" }), + workflows.answer(runId, "merge", { choice: "Merge" }), + ], + { concurrency: "unbounded" }, + ); + yield* workflows.answer(runId, "merge", { choice: "Leave" }); + assert.isUndefined(yield* kept!.mailNext([{ runId, wait: "merge" }])); + + const land = yield* agents.started(runId, "land/0"); + assert.equal(land.thread, "thread-1"); + assert.equal(land.outputSchema, undefined); + yield* agents.end(runId, "land/0", { reply: "merged as abc123" }); + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "fix/1: merged as abc123"); + assert.deepStrictEqual(yield* workflows.questions, []); + // Each step keeps what it produced, for a person reading the run afterwards. + const { steps } = yield* workflows.get(runId); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.result]), + [ + ["write", { branch: "fix/1" }], + ["merge", { choice: "Merge" }], + ["land", "merged as abc123"], + ], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "an agent whose turn dies is tried on a new thread, then its run pauses until resumed", + () => + Effect.gen(function* () { + const exposed = exposedStore(); + const { boot, agents } = yield* harness(exposed.layer); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "fix", + { project: "p1" }, + { idempotencyKey: "f2" }, + ); + yield* agents.started(runId, "write/0"); + // Its turn is stopped before the next one starts; a stop that fails pauses the run. + agents.refuseStops(3); + yield* agents.end(runId, "write/0", { ending: "failed", detail: "failed" }); + const refused = yield* workflows.waitFor(runId, status("paused")); + assert.include(refused.detail ?? "", "the link is down"); + // A stop that did not get through is tried again by itself. + assert.isNotNull(refused.resumesAt); + assert.equal(agents.interrupted.length, 0); + yield* agents.started(runId, "write/1"); + assert.equal(agents.interrupted.length, 1); + yield* agents.end(runId, "write/1", { ending: "failed", detail: "provider error" }); + + const paused = yield* workflows.waitFor(runId, status("paused")); + assert.include(paused.detail ?? "", "provider error"); + // An agent that gave up starts its whole job again on resume: a person decides that. + assert.isNull(paused.resumesAt); + // A resume cut off before it reached the engine is put back by the sweep, still held. + yield* (yield* exposed.store).runUnpaused(runId); + const putBack = yield* workflows.waitFor(runId, status("paused")); + assert.deepStrictEqual([putBack.status, putBack.resumesAt], ["paused", null]); + yield* workflows.resume(runId); + yield* agents.started(runId, "write/2"); + yield* agents.end(runId, "write/2", { output: { branch: "fix/2" } }); + yield* workflows.waitFor(runId, (run) => run.detail === "merge"); + yield* workflows.signal({ runId, wait: "merge" }, { choice: "Leave" }, { id: "a2" }); + const stopped = yield* workflows.waitFor(runId, status("stopped")); + assert.equal(stopped.detail, "left"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "a step that dies, or whose result cannot be stored, pauses its run like any failure", + () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const dies = yield* workflows.start("broken", { how: "dies" }, { idempotencyKey: "b1" }); + const died = yield* workflows.waitFor(dies.runId, status("paused")); + assert.include(died.detail ?? "", "null dereference"); + const unstorable = yield* workflows.start( + "broken", + { how: "unstorable" }, + { idempotencyKey: "b2" }, + ); + const refused = yield* workflows.waitFor(unstorable.runId, status("paused")); + assert.include(refused.detail ?? "", "unstorable"); + assert.equal((yield* workflows.get(unstorable.runId)).steps[0]?.status, "failed"); + // Never marked done on the way, so each try counts as one more pause. + yield* workflows.waitFor(unstorable.runId, (run) => run.pauses >= 2); + + const loose = yield* workflows.start( + "broken", + { how: "undefined" }, + { idempotencyKey: "b3" }, + ); + const done = yield* workflows.waitFor(loose.runId, status("completed", "paused")); + assert.deepStrictEqual( + [done.status, done.result], + ["completed", { r: { outcome: "done" }, list: [null] }], + ); + const nested = yield* workflows.start( + "broken", + { how: "nested" }, + { idempotencyKey: "b4" }, + ); + const where = yield* workflows.waitFor(nested.runId, status("paused")); + assert.include(where.detail ?? "", "the result.deep[0].id is undefined"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "signals: one per wait, a retried id is not a second one, and early mail a wait cannot read is kept", + () => + Effect.gen(function* () { + let kept: WorkflowStore.WorkflowStore["Service"] | undefined; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.tap(WorkflowStore.make, (real) => Effect.sync(() => void (kept = real))), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const key = { workflow: "review", channel: "k1" }; + // Two signals before any run waits: the first is not what the wait expects. + yield* workflows.signal(key, { merge: "x" }, { id: "bad" }); + yield* workflows.signal(key, { merge: true }, { id: "good" }); + const first = yield* workflows.start( + "review", + { change: "k1" }, + { idempotencyKey: "k1a" }, + ); + const done = yield* workflows.waitFor(first.runId, status("completed")); + assert.equal(done.result, "2 checks, merge: true"); + // Left for whichever wait on the channel reads it, another version's perhaps. + assert.equal((yield* kept!.mailNext([key]))?.signalId, "bad"); + // The sender retries the signal that was already delivered from the mail. + assert.equal(yield* workflows.signal(key, { merge: true }, { id: "good" }), "delivered"); + + const second = yield* workflows.start( + "review", + { change: "k1" }, + { idempotencyKey: "k1b" }, + ); + const third = yield* workflows.start( + "review", + { change: "k1" }, + { idempotencyKey: "k1c" }, + ); + yield* workflows.waitFor(second.runId, atVerdict); + yield* workflows.waitFor(third.runId, atVerdict); + // Nothing was left over for them, and each new signal wakes one run. + assert.equal(yield* workflows.signal(key, { merge: false }, { id: "s1" }), "delivered"); + assert.equal(yield* workflows.signal(key, { merge: true }, { id: "s2" }), "delivered"); + const results = [ + (yield* workflows.waitFor(second.runId, status("completed"))).result, + (yield* workflows.waitFor(third.runId, status("completed"))).result, + ]; + // Each new signal woke one of the two runs, whichever opened its wait first. + assert.sameMembers( + results.map((result) => String(result).split(", ")[1]), + ["merge: false", "merge: true"], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("signals that race for the waits on one channel each wake one of them", () => + Effect.gen(function* () { + // All three senders look before any claims, and the two that lose look again together. + const barriers = [ + { at: 3, all: Deferred.makeUnsafe() }, + { at: 5, all: Deferred.makeUnsafe() }, + ]; + let looked = 0; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + waitAt: (address) => + Effect.tap(real.waitAt(address), () => { + if (!("channel" in address) || address.channel !== "k3") return Effect.void; + const at = ++looked; + const barrier = barriers.find((candidate) => at <= candidate.at); + if (barrier === undefined) return Effect.void; + return at === barrier.at + ? Deferred.succeed(barrier.all, undefined) + : Deferred.await(barrier.all); + }), + }), + ), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const runs = yield* Effect.forEach(["k3a", "k3b", "k3c"], (key) => + workflows.start("review", { change: "k3" }, { idempotencyKey: key }), + ); + yield* Effect.forEach(runs, (run) => workflows.waitFor(run.runId, atVerdict)); + const sent = yield* Effect.forEach( + ["r1", "r2", "r3"], + (id) => workflows.signal({ workflow: "review", channel: "k3" }, { merge: true }, { id }), + { concurrency: "unbounded" }, + ); + assert.deepStrictEqual(sent, ["delivered", "delivered", "delivered"]); + for (const run of runs) yield* workflows.waitFor(run.runId, status("completed")); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "onEnd runs once however the run ends, and a cancelled run's is tried until it works", + () => + Effect.gen(function* () { + const { boot, counts, failures, latch, clock } = yield* harness(); + const ended = (step: { readonly name: string }) => step.name === "onEnd"; + const heldId = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const finished = yield* workflows.start( + "owned", + { mode: "finish" }, + { idempotencyKey: "f" }, + ); + const stopped = yield* workflows.start( + "owned", + { mode: "stop" }, + { idempotencyKey: "s" }, + ); + yield* workflows.waitFor(finished.runId, status("completed")); + yield* workflows.waitFor(stopped.runId, status("stopped")); + + const held = yield* workflows.start("owned", { mode: "hold" }, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, status("waiting")); + yield* Ref.set(failures, 1); + // Time stands still from here, so no sweep tries again before the first try is read. + yield* clock.close; + yield* workflows.cancel(held.runId, "not needed"); + // The first try failed, which is on the run for a person to see. + const firstTry = (yield* workflows.get(held.runId)).steps.find(ended); + assert.deepStrictEqual( + [firstTry?.status, firstTry?.detail], + ["failed", "the machine would not go"], + ); + // The next try rests a while however often the sweep looks, and needs its version. + yield* workflows.sweep; + const rested = (yield* workflows.get(held.runId)).steps.find(ended); + assert.deepStrictEqual([rested?.status, rested?.attempts], ["failed", 1]); + assert.deepInclude(yield* workflows.unfinished, { workflow: "owned", version: 1 }); + yield* clock.open; + return held.runId; + }), + ); + // Days with the server down do not end the tries. + yield* TestClock.adjust("2 days"); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The server's own sweep makes the next try. + const { steps } = Option.getOrThrow( + yield* workflows.watch.pipe( + Stream.mapEffect(() => workflows.get(heldId)), + Stream.filter((run) => + run.steps.some((step) => ended(step) && step.status === "completed"), + ), + Stream.runHead, + ), + ); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.status, step.attempts]), + [ + ["take", "completed", 1], + ["go", "failed", 1], + ["onEnd", "completed", 2], + ], + ); + assert.notDeepInclude(yield* workflows.unfinished, { workflow: "owned", version: 1 }); + // Nothing is left to do, so another look changes nothing. + yield* workflows.sweep; + // A cleanup that works the first time is told why the run was cancelled, too. + const second = yield* workflows.start( + "owned", + { mode: "hold" }, + { idempotencyKey: "h2" }, + ); + yield* workflows.waitFor(second.runId, status("waiting")); + yield* workflows.cancel(second.runId, "changed my mind"); + const all = yield* Ref.get(counts); + assert.deepStrictEqual( + Object.entries(all).filter(([name]) => name.startsWith("end:")), + [ + ["end:finish:completed:", 1], + ["end:stop:stopped:no need", 1], + ["end:hold:cancelled:not needed", 1], + ["end:hold:cancelled:changed my mind", 1], + ], + ); + + // Cancelled with a step still going: the cleanup waits for that step to finish. + const busy = yield* workflows.start("owned", { mode: "busy" }, { idempotencyKey: "b" }); + yield* Deferred.await(latch.entered); + // The cancel itself comes back after a while, the step still going. + yield* workflows.cancel(busy.runId, "not needed"); + yield* Deferred.succeed(latch.release, undefined); + yield* Deferred.await(latch.cleaned); + assert.equal((yield* Ref.get(counts))["end:busy:after work"], 1); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "the store is shared by runs, survives a restart, and a failed transaction writes nothing", + () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const runs = yield* Effect.forEach(["a", "b", "c"], (key) => + workflows.start("tally", {}, { idempotencyKey: key }), + ); + const counted = yield* Effect.forEach(runs, (run) => + workflows.waitFor(run.runId, status("completed")), + ); + assert.sameMembers( + counted.map((run) => run.result), + [1, 2, 3], + ); + }), + ); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const next = yield* workflows.start("tally", {}, { idempotencyKey: "d" }); + assert.equal((yield* workflows.waitFor(next.runId, status("completed"))).result, 4); + // A key read with another schema is the step's failure, with the key in the reason. + const wrong = yield* workflows.start("tally", { wrong: true }, { idempotencyKey: "w" }); + const paused = yield* workflows.waitFor(wrong.runId, status("paused")); + assert.include(paused.detail ?? "", "The stored value at tally does not fit its schema"); + + // The first try fails inside the transaction, so the door it opened is not there, and + // the try count it raised is 1 again on the second try, which is the one that signals. + const waiting = yield* workflows.start("door", { door: "east" }, { idempotencyKey: "e" }); + yield* workflows.waitFor(waiting.runId, status("waiting")); + const opener = yield* workflows.start( + "opener", + { door: "east", fail: true }, + { idempotencyKey: "o" }, + ); + yield* workflows.waitFor(opener.runId, status("paused")); + assert.equal((yield* workflows.get(waiting.runId)).run.status, "waiting"); + const clean = yield* workflows.start( + "opener", + { door: "east", fail: false }, + { idempotencyKey: "o2" }, + ); + yield* workflows.waitFor(clean.runId, status("completed")); + assert.equal( + (yield* workflows.waitFor(waiting.runId, status("completed"))).result, + "came in", + ); + + // A retry sends again what the first try sent, and what it sends anew is new. + const doors = ["ra", "rb", "rc"]; + const held = yield* Effect.forEach(doors, (door) => + workflows.start("door", { door }, { idempotencyKey: door }), + ); + yield* Effect.forEach(held, (run) => workflows.waitFor(run.runId, status("waiting"))); + const relay = yield* workflows.start("relay", { doors }, { idempotencyKey: "relay" }); + yield* workflows.waitFor(relay.runId, status("completed")); + // Each try is an attempt, though both were one run of the step. + assert.equal((yield* workflows.get(relay.runId)).steps[0]?.attempts, 2); + assert.equal( + yield* workflows.signal({ workflow: "door", channel: "rc" }, "late", { id: "rc-late" }), + "buffered", + ); + const opened = yield* Effect.forEach(held, (run) => + workflows.waitFor(run.runId, status("completed")), + ); + assert.deepStrictEqual( + opened.map((run) => run.result), + ["came in", "came in", "came in"], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("an invoked run reports how it ended, and cancelling the parent cancels it", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The kid of a parent that waits on it, once the kid itself waits. + const heldKid = Effect.gen(function* () { + const kid = (yield* workflows.list({})).find( + (run) => + run.workflow === "kid" && (run.status === "running" || run.status === "waiting"), + ); + return yield* workflows.waitFor(kid!.runId, status("waiting")); + }); + const finished = yield* workflows.start( + "parent", + { mode: "finish" }, + { idempotencyKey: "f" }, + ); + const stopped = yield* workflows.start("parent", { mode: "stop" }, { idempotencyKey: "s" }); + assert.equal( + (yield* workflows.waitFor(finished.runId, status("completed"))).result, + "grown", + ); + assert.equal( + (yield* workflows.waitFor(stopped.runId, status("completed"))).result, + "stopped: nothing to do", + ); + + const held = yield* workflows.start("parent", { mode: "hold" }, { idempotencyKey: "h" }); + yield* workflows.waitFor(held.runId, (run) => run.detail === "kid"); + const child = yield* heldKid; + yield* workflows.cancel(held.runId, "not needed"); + assert.equal((yield* workflows.get(child.runId)).run.status, "cancelled"); + + // A kid cancelled by itself is an outcome its parent hears, not a failure. + const second = yield* workflows.start("parent", { mode: "hold" }, { idempotencyKey: "h2" }); + yield* workflows.waitFor(second.runId, (run) => run.detail === "kid"); + const lone = yield* heldKid; + yield* workflows.cancel(lone.runId, "changed my mind"); + assert.equal( + (yield* workflows.waitFor(second.runId, status("completed"))).result, + "cancelled: changed my mind", + ); + + const spawner = yield* workflows.start("spawner", {}, { idempotencyKey: "sp" }); + const spawned = (yield* workflows.waitFor(spawner.runId, status("completed"))) + .result as ReadonlyArray; + assert.equal(spawned.length, 2); + for (const runId of spawned) { + assert.equal((yield* workflows.waitFor(runId, status("completed"))).result, "grown"); + } + + // A name taken twice pauses the run before the kid it names is started. + const clash = yield* workflows.start("clash", {}, { idempotencyKey: "c" }); + assert.include( + (yield* workflows.waitFor(clash.runId, status("paused"))).detail ?? "", + 'named "kid"', + ); + assert.deepStrictEqual( + (yield* workflows.list()).filter((run) => run.parentRunId === clash.runId), + [], + ); + const byName = yield* workflows.start("clash", { byName: true }, { idempotencyKey: "n" }); + assert.include( + (yield* workflows.waitFor(byName.runId, status("paused"))).detail ?? "", + "invoke takes the workflow definition, not its name", + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a cancel cut off midway still tells the run that invoked it", () => + Effect.gen(function* () { + // The cancel is cut off where it stops the run's steps, as a client that went away would. + const reached = yield* Deferred.make(); + let first = true; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + stepsCancelled: (runId, except) => { + if (!first) return real.stepsCancelled(runId, except); + first = false; + return Effect.andThen(Deferred.succeed(reached, undefined), Effect.never); + }, + }), + ), + ); + const { boot } = yield* harness(store); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const parent = yield* workflows.start("parent", { mode: "hold" }, { idempotencyKey: "h" }); + yield* workflows.waitFor(parent.runId, (run) => run.detail === "kid"); + const kid = (yield* workflows.list({})).find((run) => run.workflow === "kid"); + yield* workflows.waitFor(kid!.runId, status("waiting")); + const cancelling = yield* Effect.forkChild(workflows.cancel(kid!.runId, "changed my mind")); + yield* Deferred.await(reached); + yield* Fiber.interrupt(cancelling); + assert.equal( + (yield* workflows.waitFor(parent.runId, status("completed"))).result, + "cancelled: changed my mind", + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("two agents run side by side, and one past its time limit is stopped", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const run = yield* workflows.start("pair", {}, { idempotencyKey: "p" }); + // Both have started before either has ended. + yield* agents.started(run.runId, "left/0"); + yield* agents.started(run.runId, "right/0"); + yield* agents.end(run.runId, "left/0", { reply: "done" }); + // The right one never answers. Its minute passes, and a stop that cannot get through + // pauses the run without giving the turn up, so the next try stops it. + agents.refuseStops(3); + const refused = yield* workflows.waitFor(run.runId, status("paused")); + assert.include(refused.detail ?? "", "the link is down"); + assert.equal(agents.interrupted.length, 0); + const paused = yield* workflows.waitFor( + run.runId, + (current) => current.status === "paused" && current.detail !== refused.detail, + ); + assert.include(paused.detail ?? "", "it was not done after 1m"); + assert.equal(agents.interrupted.length, 1); + const { steps } = yield* workflows.get(run.runId); + assert.deepStrictEqual(steps.map((step) => [step.name, step.status]).toSorted(), [ + ["left", "completed"], + ["right", "failed"], + ]); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a continued thread keeps how it started", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const run = yield* workflows.start( + "fix", + { project: "p1", reshape: true }, + { idempotencyKey: "r1" }, + ); + yield* agents.started(run.runId, "write/0"); + yield* agents.end(run.runId, "write/0", { output: { branch: "fix/1" } }); + yield* workflows.waitFor(run.runId, (current) => current.detail === "merge"); + yield* workflows.signal( + { runId: run.runId, wait: "merge" }, + { choice: "Merge" }, + { id: "m" }, + ); + const paused = yield* workflows.waitFor(run.runId, status("paused")); + assert.include(paused.detail ?? "", "Drop `model`"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("an agent step in a linked environment keeps its thread there", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const run = yield* workflows.start( + "fix", + { project: "/work/app", environment: "env-b" }, + { idempotencyKey: "e1" }, + ); + const write = yield* agents.started(run.runId, "write/0"); + assert.equal(write.environment, "env-b"); + yield* agents.end(run.runId, "write/0", { output: { branch: "fix/1" } }); + yield* workflows.waitFor(run.runId, status("waiting")); + yield* workflows.signal( + { runId: run.runId, wait: "merge" }, + { choice: "Merge" }, + { id: "m1" }, + ); + + // The step that continues the thread names no environment: the thread carries it. + const land = yield* agents.started(run.runId, "land/0"); + assert.equal(land.environment, "env-b"); + assert.equal(land.thread, "thread-1"); + yield* workflows.waitFor(run.runId, (current) => current.detail === "agent land"); + const { steps } = yield* workflows.get(run.runId); + assert.deepStrictEqual( + steps.filter((step) => step.kind === "agent").map((step) => step.environmentId), + ["env-b", "env-b"], + ); + yield* workflows.cancel(run.runId, "not needed"); + // Only the step's own turn: someone else's turn on that thread is left alone. + assert.deepStrictEqual(agents.interrupted, [ + { threadId: "thread-1", environment: "env-b", turnId: `${run.runId}/land/0` }, + ]); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("cancelling a run stops its agent, and a turn a person stopped is not tried again", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const cancelled = yield* workflows.start( + "fix", + { project: "p1" }, + { idempotencyKey: "x1" }, + ); + yield* agents.started(cancelled.runId, "write/0"); + yield* workflows.waitFor(cancelled.runId, (run) => run.detail === "agent write"); + const { steps } = yield* workflows.get(cancelled.runId); + yield* workflows.cancel(cancelled.runId, "not needed"); + assert.deepStrictEqual(agents.interrupted, [ + { threadId: steps[0]?.threadId ?? "no thread", turnId: `${cancelled.runId}/write/0` }, + ]); + + const stopped = yield* workflows.start("fix", { project: "p1" }, { idempotencyKey: "x2" }); + yield* agents.started(stopped.runId, "write/0"); + yield* agents.end(stopped.runId, "write/0", { ending: "stopped", detail: "interrupted" }); + const paused = yield* workflows.waitFor(stopped.runId, status("paused")); + assert.include(paused.detail ?? "", "stopped"); + // Resuming is the person saying go on: the next round starts. + yield* workflows.resume(stopped.runId); + yield* agents.started(stopped.runId, "write/1"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a watcher is sent the runs again when one changes", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const first = Option.getOrThrow(yield* Stream.runHead(workflows.watch)); + assert.deepStrictEqual([first.runs, first.questions], [[], []]); + // What exists is listed before anything has run, with what starts it. + assert.deepInclude(first.workflows, { + name: "inbound", + version: 1, + triggers: ["webhook push"], + }); + const { runId } = yield* workflows.start( + "review", + { change: "c9", timeout: "1 hour" }, + { idempotencyKey: "c9" }, + ); + const seen = yield* workflows.watch.pipe( + Stream.filter((snapshot) => snapshot.runs.some((run) => run.status === "waiting")), + Stream.runHead, + ); + assert.deepStrictEqual( + Option.getOrThrow(seen).runs.map((run) => run.runId), + [runId], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect( + "a schedule starts one run when it is due, and one for all the times a restart missed", + () => + Effect.gen(function* () { + const { boot } = yield* harness(); + const nightly = (workflows: Workflows.Workflows["Service"]) => + Effect.map(workflows.list(), (runs) => runs.filter((run) => run.workflow === "nightly")); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The first look only notes when it is next due. + yield* workflows.sweep; + assert.deepStrictEqual(yield* nightly(workflows), []); + // A start that fails is tried again, not passed over for the next time it is due. + ticks.refused = true; + yield* TestClock.adjust("61 minutes"); + yield* workflows.sweep; + assert.deepStrictEqual(yield* nightly(workflows), []); + ticks.refused = false; + yield* workflows.sweep; + yield* workflows.sweep; + const [run] = yield* nightly(workflows); + assert.equal((yield* nightly(workflows)).length, 1); + const done = yield* workflows.waitFor(run!.runId, status("completed")); + assert.match(String(done.result), /^1970-01-01T01:/); + }), + ); + yield* TestClock.adjust("3 hours"); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + yield* workflows.sweep; + yield* workflows.sweep; + assert.equal((yield* nightly(workflows)).length, 2); + }), + ); + // Taken out of the file and put back long after it was due: due one interval from then. + const others = triggered.filter((definition) => definition.name !== "nightly"); + yield* boot( + Effect.flatMap(Workflows.Workflows, (workflows) => workflows.sweep), + others, + ); + yield* TestClock.adjust("3 hours"); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + yield* workflows.sweep; + yield* workflows.sweep; + assert.equal((yield* nightly(workflows)).length, 2); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("an issue opened after the workflow loaded starts one run, which can comment on it", () => + Effect.gen(function* () { + const starts: Array = []; + const store = Layer.effect( + WorkflowStore.WorkflowStore, + Effect.map(WorkflowStore.make, (real) => + WorkflowStore.WorkflowStore.of({ + ...real, + runStarted: (run) => + Effect.andThen( + Effect.sync(() => starts.push(run.idempotencyKey)), + real.runStarted(run), + ), + }), + ), + ); + const { boot, forge } = yield* harness(store); + const triaged = (workflows: Workflows.Workflows["Service"]) => + Effect.map(workflows.list(), (runs) => runs.filter((run) => run.workflow === "triage")); + forge.open.push(issueAt("1", "1969-12-31T23:00:00.000Z")); + // Before the mark too, written the way some hosts write a time. + forge.open.push(issueAt("3", "1970-01-01T00:30:00+01:00")); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The first look only notes the time: what was there already starts nothing. + yield* workflows.sweep; + yield* TestClock.adjust("2 minutes"); + // One the workflow turns down comes first, and does not hold back the one after it. + forge.open.push({ ...issueAt("bad", "1970-01-01T00:00:30.000Z"), title: 5 } as never); + forge.open.push(issueAt("2", "1970-01-01T00:01:00.000Z")); + yield* workflows.sweep; + yield* TestClock.adjust("2 minutes"); + yield* workflows.sweep; + const [run, ...others] = yield* triaged(workflows); + assert.deepStrictEqual(others, []); + const done = yield* workflows.waitFor(run!.runId, status("completed")); + assert.equal(done.result, "#2"); + assert.deepStrictEqual(forge.comments, ["2: Looking at Issue 2."]); + // The issue that started the run is the one its step commented on. + assert.deepStrictEqual( + (yield* workflows.get(run!.runId)).references.map( + ({ kind, title, state, steps, origin }) => ({ kind, title, state, steps, origin }), + ), + [{ kind: "issue", title: "Issue 2", state: "open", steps: ["thank"], origin: "trigger" }], + ); + // A later look still lists it, and leaves the run it has alone. + const before = starts.length; + yield* TestClock.adjust("2 minutes"); + yield* workflows.sweep; + assert.deepStrictEqual(starts.slice(before), []); + assert.deepStrictEqual(forge.asked.at(-1), { + project: PROJECT, + state: "all", + sort: "created", + limit: 100, + labels: ["bug"], + query: undefined, + }); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a wait on a pull request ends when its checks have, and says how", () => + Effect.gen(function* () { + const { boot, forge } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const { runId } = yield* workflows.start( + "land", + { url: forge.pullRequest.url }, + { idempotencyKey: "pr-7" }, + ); + yield* workflows.waitFor(runId, status("waiting")); + yield* workflows.sweep; + assert.equal((yield* workflows.waitFor(runId, () => true)).status, "waiting"); + // Not a question for anyone: nothing waits on a person. + assert.deepStrictEqual(yield* workflows.questions, []); + forge.pullRequest.checks[0]!.status = "success"; + yield* TestClock.adjust("2 minutes"); + yield* workflows.sweep; + const done = yield* workflows.waitFor(runId, status("completed")); + assert.equal(done.result, "passing"); + // Each look kept it on the wait's step, and the replay after the wake added nothing. + assert.deepStrictEqual( + (yield* workflows.get(runId)).references.map(({ kind, steps, state }) => ({ + kind, + steps, + state, + })), + [{ kind: "pullRequest", steps: ["checks"], state: "open" }], + ); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a step or sleep with an option it cannot read says which and what it takes", () => + Effect.gen(function* () { + assert.throws( + () => + step( + "push", + { returns: Schema.Void, retry: { times: 2, shedule: 1 } as never }, + Effect.void, + ), + 'step("push")\'s retry does not take `shedule`', + ); + const slept = yield* Effect.exit(sleep("z", "soon" as never) as unknown as Effect.Effect); + assert.include( + String(Exit.isFailure(slept) ? Cause.squash(slept.cause) : ""), + 'sleep("z") cannot read "soon" as a duration. Write one such as "5 minutes".', + ); + }), +); + +it("hooks of different workflows never share an id", () => { + assert.notEqual(Workflows.hookId("a.b", "c"), Workflows.hookId("a", "b.c")); + assert.equal(Workflows.hookId("inbound", "push"), "wf-inbound.push"); +}); + +it.effect("a request to a hook starts a run, its retry is the same run, and a bad token none", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + const request = (body: string, delivery: string) => ({ + method: "POST", + headers: { "x-delivery": delivery }, + query: "", + body, + }); + const token = yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const [hook] = yield* workflows.hooks; + assert.equal(hook?.workflow, "inbound"); + const [hookId, token] = hook!.path.split("/").slice(-2).map(decodeURIComponent); + const deliver = (body: string, delivery: string, withToken = token!) => + workflows.deliver({ + hookId: hookId!, + token: withToken, + request: request(body, delivery), + }); + + assert.isTrue(Option.isNone(yield* deliver("hello", "d1", "not the token"))); + const first = Option.getOrThrow(yield* deliver("hello", "d1")); + assert.deepStrictEqual(Option.getOrThrow(yield* deliver("hello", "d1")), first); + const done = yield* workflows.waitFor(first.runId, status("completed")); + assert.equal(done.result, "hello"); + + const ping = Option.getOrThrow(yield* deliver("ping", "d2")); + const skipped = yield* workflows.waitFor(ping.runId, status("skipped")); + assert.equal(skipped.detail, "only a ping"); + + const send = (headers: Record, body: string) => + workflows.deliver({ + hookId: hookId!, + token: token!, + request: { method: "POST", headers, query: "", body }, + }); + // With no key from the workflow, the id the sender keeps on its retry makes it one run. + const github = { "x-github-delivery": "g1" }; + const sent = Option.getOrThrow(yield* send(github, "{}")); + assert.deepStrictEqual(Option.getOrThrow(yield* send(github, "{}")), sent); + // A key the workflow cannot read off the request turns the request down. + const unreadable = yield* send({}, "not json").pipe(Effect.flip); + assert.equal(unreadable._tag, "WorkflowInputError"); + return token; + }), + ); + // The URL a sender was given still works after a restart. + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + assert.isTrue((yield* workflows.hooks)[0]?.path.endsWith(`/${token}`)); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a step finds runs by their key, wakes everyone at a key, and cancels another run", () => + Effect.gen(function* () { + const { boot } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + const visit = (key: string, at: string) => + workflows.start("gate", { gate: at }, { idempotencyKey: key }); + const keeper = Effect.fn(function* (act: "look" | "open" | "dismiss" | "leave") { + const run = yield* workflows.start("keeper", { act }, { idempotencyKey: act }); + return yield* workflows.waitFor(run.runId, status("completed", "paused")); + }); + const [one, two, three] = yield* Effect.all([ + visit("visit/1", "north"), + visit("visit/2", "north"), + visit("visit/3", "south"), + ]); + // Not at a gate, and not started as a visit: none of the keeper's business. + yield* workflows.start("review", { change: "north" }, { idempotencyKey: "other" }); + for (const run of [one, two, three]) yield* workflows.waitFor(run.runId, status("waiting")); + + assert.deepStrictEqual((yield* keeper("look")).result, [ + "visit/1 waiting", + "visit/2 waiting", + "visit/3 waiting", + ]); + // Both at the north gate go through on one signal; the one at the south gate stays. + assert.equal((yield* keeper("open")).result, 2); + for (const run of [one, two]) { + assert.equal((yield* workflows.waitFor(run.runId, status("completed"))).result, "go on"); + } + assert.equal((yield* workflows.get(three.runId)).run.status, "waiting"); + + yield* keeper("dismiss"); + const dismissed = (yield* workflows.get(three.runId)).run; + assert.deepStrictEqual( + [dismissed.status, dismissed.detail], + ["cancelled", "the gate is closed"], + ); + // A run ends itself with `stop`; cancelling itself would cut the cancel short. + const left = yield* keeper("leave"); + assert.equal(left.status, "paused"); + assert.include(left.detail ?? "", "cannot cancel itself"); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + +it.effect("a workflow can take an agent's failure as an answer and go on", () => + Effect.gen(function* () { + const { boot, agents } = yield* harness(); + yield* boot( + Effect.gen(function* () { + const workflows = yield* Workflows.Workflows; + // The first agent's turn dies, and so does the one more try it gets. + const died = yield* workflows.start("fallback", { project: "p1" }, { idempotencyKey: "d" }); + yield* agents.started(died.runId, "first/0"); + yield* agents.end(died.runId, "first/0", { ending: "failed", detail: "failed" }); + yield* agents.started(died.runId, "first/1"); + yield* agents.end(died.runId, "first/1", { ending: "failed", detail: "failed" }); + yield* agents.started(died.runId, "second/0"); + yield* agents.end(died.runId, "second/0", { output: { head: "abc" } }); + const done = yield* workflows.waitFor(died.runId, status("completed", "paused")); + assert.deepStrictEqual( + [done.status, done.pauses, done.result], + ["completed", 0, "abc after: the agent's turn was cut short: failed"], + ); + const { steps } = yield* workflows.get(died.runId); + assert.deepStrictEqual( + steps.map((step) => [step.name, step.status]), + [ + ["first", "failed"], + ["second", "completed"], + ], + ); + + // An agent that cannot be started at all is an answer too. + const lost = yield* workflows.start( + "fallback", + { project: "nowhere" }, + { idempotencyKey: "n" }, + ); + yield* agents.started(lost.runId, "second/0"); + yield* agents.end(lost.runId, "second/0", { output: { head: "def" } }); + const found = yield* workflows.waitFor(lost.runId, status("completed", "paused")); + assert.equal( + found.result, + "def after: the agent could not be started: No project is registered there.", + ); + + // A result that cannot be read leaves the turn maybe running: a stop that fails gives up + // the step, and no second turn starts beside it. + const stopsBefore = agents.interrupted.length; + agents.refuseStops(3); + agents.unreadableResult("first/0"); + const unread = yield* workflows.start( + "fallback", + { project: "p1" }, + { idempotencyKey: "u" }, + ); + yield* agents.started(unread.runId, "second/0"); + assert.equal(agents.interrupted.length, stopsBefore); + yield* agents.end(unread.runId, "second/0", { output: { head: "jkl" } }); + const gaveUp = yield* workflows.waitFor(unread.runId, status("completed", "paused")); + assert.include(gaveUp.result as string, "its turn could not be stopped"); + + // One past its time whose turn cannot be stopped says so, for the workflow to weigh. + agents.refuseStops(3); + const stuck = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "s" }, + ); + yield* agents.started(stuck.runId, "second/0"); + yield* agents.end(stuck.runId, "second/0", { output: { head: "ghi" } }); + const weighed = yield* workflows.waitFor(stuck.runId, status("completed", "paused")); + assert.include(weighed.result as string, "its turn could not be stopped"); + + // A stop turned down once gets through on its retry, and the step says it was stopped. + const before = agents.interrupted.length; + agents.refuseStops(1); + const late = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "l" }, + ); + yield* agents.started(late.runId, "second/0"); + assert.equal(agents.interrupted.length, before + 1); + yield* agents.end(late.runId, "second/0", { output: { head: "mno" } }); + const retried = yield* workflows.waitFor(late.runId, status("completed", "paused")); + assert.equal(retried.status, "completed"); + assert.notInclude(retried.result as string, "could not be stopped"); + + // A result that arrived as its time ran out, before it was read, is still the answer. + agents.unansweredResult("first/0"); + const lastMinute = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "m" }, + ); + yield* agents.started(lastMinute.runId, "first/0"); + yield* agents.end(lastMinute.runId, "first/0", { output: { head: "pqr" } }); + yield* agents.end(lastMinute.runId, "second/0", { output: { head: "not needed" } }); + const answered = yield* workflows.waitFor(lastMinute.runId, status("completed", "paused")); + assert.equal(answered.result, "pqr"); + + // One whose turn had ended without its result is not said to be stopped: the agent may + // answer from a later turn nobody stopped. + agents.unansweredResult("first/0"); + const owing = yield* workflows.start( + "fallback", + { project: "p1", timeout: "1 minute" }, + { idempotencyKey: "o" }, + ); + yield* agents.started(owing.runId, "first/0"); + yield* agents.end(owing.runId, "first/0", {}); + yield* agents.started(owing.runId, "second/0"); + yield* agents.end(owing.runId, "second/0", { output: { head: "stu" } }); + const owed = yield* workflows.waitFor(owing.runId, status("completed", "paused")); + assert.include(owed.result as string, "may still be at work"); + + // One that did the work and never gave its result is not given the job again: it may + // have acted on it already. + const silent = yield* workflows.start( + "fallback", + { project: "p1", thread: true }, + { idempotencyKey: "q" }, + ); + for (const key of ["first/0", "first/0/correct/0", "first/0/correct/1"]) { + yield* agents.started(silent.runId, key); + yield* agents.end(silent.runId, key, {}); + } + yield* agents.end(silent.runId, "first/1", { output: { head: "twice" } }); + yield* agents.end(silent.runId, "second/0", { output: { head: "vwx" } }); + const once = yield* workflows.waitFor(silent.runId, status("completed", "paused")); + assert.match( + once.result as string, + /^vwx after: the agent did not return a result: .* in thread-\d+$/, + ); + + // A correction that cannot be sent leaves the failure with the thread the work is in. + const unasked = yield* workflows.start( + "fallback", + { project: "p1", thread: true }, + { idempotencyKey: "c" }, + ); + agents.unstartable(unasked.runId, "first/0/correct/0"); + yield* agents.started(unasked.runId, "first/0"); + yield* agents.end(unasked.runId, "first/0", {}); + yield* agents.end(unasked.runId, "second/0", { output: { head: "yz" } }); + const kept = yield* workflows.waitFor(unasked.runId, status("completed", "paused")); + assert.match(kept.result as string, /could not be asked again: .* in thread-\d+$/); + }), + ); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); diff --git a/apps/server/src/workflows/Workflows.ts b/apps/server/src/workflows/Workflows.ts new file mode 100644 index 0000000000000..1b26479d6bd7a --- /dev/null +++ b/apps/server/src/workflows/Workflows.ts @@ -0,0 +1,221 @@ +import { + type WorkflowCounts, + type WorkflowHook, + WorkflowQuestion, + type WorkflowRunReference, + type WorkflowRunsSnapshot, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import type * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; + +import type { WebhookRequest } from "./triggers.ts"; +import type * as WorkflowStore from "./WorkflowStore.ts"; + +/** Hook ids of workflows start with this; a scheduled task's hook id never does. */ +export const HOOK_PREFIX = "wf-"; + +// The dot between the two parts is never in either, so no two hooks share an id. +const hookPart = (part: string) => encodeURIComponent(part).replaceAll(".", "%2E"); +/** The id of the hook `name` of `workflow`, which its URL and its secret are kept by. */ +export const hookId = (workflow: string, name: string) => + `${HOOK_PREFIX}${hookPart(workflow)}.${hookPart(name)}`; + +export class WorkflowNotRegisteredError extends Schema.TaggedError()( + "WorkflowNotRegisteredError", + { workflow: Schema.String, version: Schema.optional(Schema.Number) }, +) { + override get message(): string { + return this.version === undefined + ? `No workflow named ${this.workflow} is registered.` + : `Version ${this.version} of workflow ${this.workflow} is not registered.`; + } +} + +export class WorkflowRunNotFoundError extends Schema.TaggedError()( + "WorkflowRunNotFoundError", + { runId: Schema.String }, +) { + override get message(): string { + return `Workflow run ${this.runId} was not found.`; + } +} + +export class WorkflowInputError extends Schema.TaggedError()( + "WorkflowInputError", + { problem: Schema.String }, +) { + override get message(): string { + return this.problem; + } +} + +export { WorkflowQuestion }; + +export type WorkflowError = + | WorkflowNotRegisteredError + | WorkflowRunNotFoundError + | WorkflowInputError; + +export class Workflows extends Context.Service< + Workflows, + { + /** Start a run. A second start with the same key is the same run. */ + readonly start: ( + workflow: string, + input: unknown, + options: { + readonly idempotencyKey: string; + /** The run that waits for this one. A run started with a key has one parent or none. */ + readonly parent?: WorkflowStore.RunParent; + /** The version to run, when the caller holds a definition. Without it, the newest. */ + readonly version?: number; + }, + ) => Effect.Effect<{ readonly runId: string }, WorkflowError>; + /** + * Say that something a run waits on happened. `delivered` woke a wait; `buffered` is kept for + * a wait that has not opened yet, for `ttl` (seven days by default). + */ + readonly signal: ( + address: WorkflowStore.SignalAddress, + value: Schema.Json, + options: { readonly id: string; readonly ttl?: Duration.Input }, + ) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>; + /** + * Answer the question a run asks a person. One answer per time it is asked: a second, a + * double click, wakes nothing and is not kept for later. + */ + readonly answer: ( + runId: string, + name: string, + value: Schema.Json, + ) => Effect.Effect; + /** Run a paused run's failed step again. */ + readonly resume: (runId: string) => Effect.Effect; + readonly cancel: (runId: string, reason?: string) => Effect.Effect; + readonly get: (runId: string) => Effect.Effect< + { + readonly run: WorkflowStore.WorkflowRun; + readonly steps: ReadonlyArray; + readonly references: ReadonlyArray; + }, + WorkflowRunNotFoundError | WorkflowInputError + >; + readonly list: (filter?: { + readonly status?: WorkflowStore.WorkflowRunStatus; + }) => Effect.Effect, WorkflowInputError>; + /** The run once `done` holds for it. Looks now, then on every change to the run. */ + readonly waitFor: ( + runId: string, + done: (run: WorkflowStore.WorkflowRun) => boolean, + ) => Effect.Effect; + /** The questions runs are waiting on a person to answer, oldest first. */ + readonly questions: Effect.Effect, WorkflowInputError>; + /** What each run that has not ended is a run of, however many: no list limit applies. */ + readonly unfinished: Effect.Effect< + ReadonlyArray<{ readonly workflow: string; readonly version: number }> + >; + /** The hook URLs of the registered workflows. */ + readonly hooks: Effect.Effect, WorkflowInputError>; + /** + * Start the run a request to a hook asks for. Nothing, for a hook or token that is not known. + * `deliveryId` names the delivery when its carrier vouches for one, so its retry is one run. + */ + readonly deliver: (delivery: { + readonly hookId: string; + readonly token: string; + readonly request: WebhookRequest; + readonly deliveryId?: string; + }) => Effect.Effect, WorkflowError>; + /** What workflows keep in the store under keys starting with `prefix`, for a person to see. */ + readonly stored: ( + prefix: string, + ) => Effect.Effect< + ReadonlyArray<{ readonly key: string; readonly value: Schema.Json }>, + WorkflowInputError + >; + /** Set a key of the store from outside a run, as a person flipping a switch does. */ + readonly storeSet: (key: string, value: Schema.Json) => Effect.Effect; + readonly storeDelete: (key: string) => Effect.Effect; + /** Recent runs and open questions, now and again after every change. */ + readonly watch: Stream.Stream; + /** How much is going on, now and again whenever a count changes. */ + readonly counts: Stream.Stream; + /** + * Deliver timeouts to waits past their deadline, drop expired mail, and resume paused runs + * whose rest is over. Runs by itself every few seconds. + */ + readonly sweep: Effect.Effect; + } +>()("t3/workflows/Workflows") {} + +const refuse = Effect.fn("Workflows.disabled")(function* () { + return yield* new WorkflowInputError({ + problem: + "This server defines no workflows yet. Add a file to the workflows folder of its T3 home.", + }); +}); + +/** The service with nothing registered and no engine behind it. */ +export const disabled = Workflows.of({ + start: refuse, + signal: refuse, + answer: refuse, + resume: refuse, + cancel: refuse, + get: Effect.fn("Workflows.get")(function* (runId) { + return yield* new WorkflowRunNotFoundError({ runId }); + }), + list: Effect.fn("Workflows.list")(function* () { + return yield* Effect.succeed>([]); + }), + waitFor: Effect.fn("Workflows.waitFor")(function* () { + return yield* Effect.never; + }), + questions: Effect.succeed([]), + unfinished: Effect.succeed([]), + hooks: Effect.succeed([]), + deliver: Effect.fn("Workflows.deliver")(function* () { + return yield* Effect.succeed(Option.none<{ readonly runId: string }>()); + }), + stored: Effect.fn("Workflows.stored")(function* () { + return yield* Effect.succeed>([]); + }), + storeSet: refuse, + storeDelete: refuse, + watch: Stream.concat(Stream.make({ workflows: [], runs: [], questions: [] }), Stream.never), + counts: Stream.concat(Stream.make({ needsYou: 0, active: 0, total: 0 }), Stream.never), + sweep: Effect.void, +}); +export const layerDisabled = Layer.succeed(Workflows, disabled); + +export const OFF = + 'Workflows are off on this server. Turn them on in its Settings → Labs → Workflows, or without a desktop, set "workflowsEnabled": true in userdata/settings.json in its T3 home (~/.t3 by default).'; + +const refuseOff = Effect.fn("Workflows.off")(function* () { + return yield* new WorkflowInputError({ problem: OFF }); +}); + +/** + * The service while workflows are off: every request is refused, and a hook answers as one that + * is not there. + */ +export const off = Workflows.of({ + ...disabled, + start: refuseOff, + signal: refuseOff, + answer: refuseOff, + resume: refuseOff, + cancel: refuseOff, + get: refuseOff, + list: refuseOff, + questions: refuseOff(), + hooks: refuseOff(), + stored: refuseOff, + storeSet: refuseOff, + storeDelete: refuseOff, +}); diff --git a/apps/server/src/workflows/api.ts b/apps/server/src/workflows/api.ts new file mode 100644 index 0000000000000..9f1bfd72b15ca --- /dev/null +++ b/apps/server/src/workflows/api.ts @@ -0,0 +1,15 @@ +// Everything a definitions module is handed. A workflow file imports nothing: an installed server +// is one bundle, with no package for it to import these from, and its own copy of `effect` would +// not be the one the engine runs. +export * as Duration from "effect/Duration"; +export * as Effect from "effect/Effect"; +export * as Option from "effect/Option"; +export * as Schedule from "effect/Schedule"; +export * as Schema from "effect/Schema"; + +export { daily, every, Tick, webhook, WebhookRequest } from "./triggers.ts"; +export { issues, pullRequests } from "./forgeApi.ts"; +export { cancel, runs, signal, signalAll, start, store } from "./stepServices.ts"; +export { Issue, IssueDetail, PullRequest, PullRequestStanding } from "./WorkflowForge.ts"; +export { invoke, skip, sleep, step, stop, title, wait, workflow } from "./workflow.ts"; +export { agent, ask } from "./workflowAgent.ts"; diff --git a/apps/server/src/workflows/forgeApi.ts b/apps/server/src/workflows/forgeApi.ts new file mode 100644 index 0000000000000..a7e0839730201 --- /dev/null +++ b/apps/server/src/workflows/forgeApi.ts @@ -0,0 +1,109 @@ +// Issues and pull requests as a workflow file sees them: triggers, calls for inside a step, and a +// wait on a pull request for the body. +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import type * as Option from "effect/Option"; + +import { checkOptions } from "./options.ts"; +import { issuesOpened, pullRequestsOpened } from "./triggers.ts"; +import type { InRun } from "./workflow.ts"; +import { waitAs } from "./workflow.ts"; +import { + type IssueAddress, + type PullRequestAddress, + PullRequestStanding, + type PullRequestUntil, + type PullRequestWatch, + WorkflowForge, +} from "./WorkflowForge.ts"; + +const forge = (use: (forge: WorkflowForge["Service"]) => Effect.Effect) => + Effect.flatMap(WorkflowForge, use); + +/** + * The project's issues, in whichever tracker it uses. `opened` is a trigger; the rest are for + * inside `step` or `onEnd`. An issue is named by what a trigger or `list` gave, or by + * `{ project, url }`. + */ +export const issues = { + opened: issuesOpened, + list: (query: Parameters[0]) => { + checkOptions("issues.list", query, [ + "project", + "state", + "labels", + "query", + "assignee", + "sort", + "limit", + ]); + return forge((all) => all.issues.list(query)); + }, + read: (issue: IssueAddress) => forge((all) => all.issues.read(issue)), + comment: (issue: IssueAddress, body: string) => forge((all) => all.issues.comment(issue, body)), + /** Move the issue to one of its `states`, as `read` lists them. */ + setState: (issue: IssueAddress, state: string) => + forge((all) => all.issues.setState(issue, state)), + create: (input: Parameters[0]) => { + checkOptions("issues.create", input, ["project", "title", "body", "labels", "assignees"]); + return forge((all) => all.issues.create(input)); + }, +}; + +/** + * The project's pull requests on its git host. `opened` is a trigger; the rest are for inside + * `step` or `onEnd`. A pull request is named by what a trigger or `list` gave, or by + * `{ project, url }`. + */ +export const pullRequests = { + opened: pullRequestsOpened, + list: (query: Parameters[0]) => { + checkOptions("pullRequests.list", query, ["project", "state", "query", "limit"]); + return forge((all) => all.pullRequests.list(query)); + }, + read: (pullRequest: PullRequestAddress) => forge((all) => all.pullRequests.read(pullRequest)), + comment: (pullRequest: PullRequestAddress, body: string) => + forge((all) => all.pullRequests.comment(pullRequest, body)), + /** `merge`, `close`, `ready`, `update-branch` and the host's other actions on a pull request. */ + act: ( + pullRequest: PullRequestAddress, + action: Parameters[1], + options?: Parameters[2], + ) => { + checkOptions("pullRequests.act", options, ["mergeMethod"]); + return forge((all) => all.pullRequests.act(pullRequest, action, options)); + }, + /** + * Wait in the body until the pull request gets somewhere, without holding anything: `checks` + * until none of its checks is still running, `merged` or `closed` until it is no longer open. + * A pull request that is merged or closed ends any of them. Gives where it stands, or nothing + * after `timeout`. The host is asked about once a minute. + */ + wait: ( + name: string, + pullRequest: PullRequestAddress, + options: { readonly until: PullRequestUntil; readonly timeout?: Duration.Input }, + ): Effect.Effect, never, InRun> => { + checkOptions(`pullRequests.wait("${name}")`, options, ["until", "timeout"]); + return Effect.orDie( + waitAs("wait", name, { + returns: PullRequestStanding, + timeout: options.timeout, + watch: { + kind: "pullRequest", + until: options.until, + // Only the address: a listing's row carries far more than a wait needs to keep. + pullRequest: + "url" in pullRequest && "project" in pullRequest + ? { project: pullRequest.project, url: pullRequest.url } + : { + projectId: pullRequest.projectId, + host: pullRequest.host, + repository: pullRequest.repository, + number: pullRequest.number, + }, + } satisfies PullRequestWatch, + }), + ); + }, +}; diff --git a/apps/server/src/workflows/options.ts b/apps/server/src/workflows/options.ts new file mode 100644 index 0000000000000..7ba47abf65f27 --- /dev/null +++ b/apps/server/src/workflows/options.ts @@ -0,0 +1,28 @@ +import * as Duration from "effect/Duration"; +import * as Option from "effect/Option"; + +/** The duration `input` is, or an error that names `what` and shows one that reads. */ +export const durationOf = (what: string, input: Duration.Input): Duration.Duration => + Option.getOrThrowWith( + Duration.fromInput(input), + () => + new Error( + `${what} cannot read ${JSON.stringify(input)} as a duration. Write one such as "5 minutes".`, + ), + ); + +/** + * Refuses an option the call does not take. A workflow file is not type-checked, so a misspelt or + * renamed option would otherwise be dropped without a word. + */ +export const checkOptions = ( + what: string, + options: object | undefined, + allowed: ReadonlyArray, +) => { + if (options === undefined || options === null) return; + const unknown = Object.keys(options).filter((key) => !allowed.includes(key)); + if (unknown.length === 0) return; + const listed = (keys: ReadonlyArray) => keys.map((key) => `\`${key}\``).join(", "); + throw new Error(`${what} does not take ${listed(unknown)}. It takes ${listed(allowed)}.`); +}; diff --git a/apps/server/src/workflows/runReferences.ts b/apps/server/src/workflows/runReferences.ts new file mode 100644 index 0000000000000..8599a3a6cae5b --- /dev/null +++ b/apps/server/src/workflows/runReferences.ts @@ -0,0 +1,90 @@ +// What a run touched, for a person reading the run: the issue that started it, the pull request a +// step merged. Anything that touches something calls `noteReference`; a new kind of thing is a +// new caller, and nothing else changes. +import { + type IssueRef, + type IssueState, + type PullRequestRef, + WorkflowReferenceKind, +} from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import type * as Schema from "effect/Schema"; + +import type { ReferenceInput, WorkflowStore } from "./WorkflowStore.ts"; + +/** Keeps what the step whose code is running touches, against that step. */ +export class StepReferences extends Context.Service< + StepReferences, + { readonly note: (reference: ReferenceInput) => Effect.Effect } +>()("t3/workflows/runReferences/StepReferences") {} + +/** Keep that `runId` touched `reference`, from `step` or, with none, from what started it. */ +export const noteFor = ( + store: WorkflowStore["Service"], + runId: string, + step: string | null, + reference: ReferenceInput, +): Effect.Effect => + store.referenceNoted(runId, step, reference).pipe( + // Only for a person to read: a step must never fail or wait over it. + Effect.catchCause((cause) => + Effect.logWarning("Could not keep what a workflow run touched", { + runId, + step, + kind: reference.kind, + cause: Cause.pretty(cause), + }), + ), + ); + +/** Keep that the running step touched `reference`. Outside a step it does nothing. */ +export const noteReference = (reference: ReferenceInput): Effect.Effect => + Effect.flatMap(Effect.serviceOption(StepReferences), (current) => + current._tag === "None" ? Effect.void : current.value.note(reference), + ); + +export const stepReferences = ( + store: WorkflowStore["Service"], + runId: string, + step: string, +): Context.Context => + Context.make(StepReferences, { note: (reference) => noteFor(store, runId, step, reference) }); + +/** An issue, with its title and where it stands when the toucher read them. */ +export const issueReference = ( + ref: IssueRef, + seen?: { readonly title: string; readonly url: string; readonly state: IssueState }, +): ReferenceInput => ({ + kind: WorkflowReferenceKind.issue, + key: JSON.stringify([ref.tracker, ref.host ?? "", ref.scope.toLowerCase(), ref.key]), + address: { + projectId: ref.projectId, + tracker: ref.tracker, + ...(ref.host === undefined ? {} : { host: ref.host }), + scope: ref.scope, + key: ref.key, + } satisfies Schema.Json, + title: seen?.title ?? "", + url: seen?.url, + state: seen?.state.category, +}); + +/** A pull request by its normalized host and repository, so every way of naming it is one. */ +export const pullRequestReference = ( + ref: Pick & { readonly host: string }, + seen?: { readonly title?: string; readonly url?: string; readonly state?: string }, +): ReferenceInput => ({ + kind: WorkflowReferenceKind.pullRequest, + key: JSON.stringify([ref.host, ref.repository, ref.number]), + address: { + projectId: ref.projectId, + host: ref.host, + repository: ref.repository, + number: ref.number, + }, + title: seen?.title ?? "", + url: seen?.url, + state: seen?.state, +}); diff --git a/apps/server/src/workflows/stepServices.ts b/apps/server/src/workflows/stepServices.ts new file mode 100644 index 0000000000000..53c6773494c3b --- /dev/null +++ b/apps/server/src/workflows/stepServices.ts @@ -0,0 +1,458 @@ +// What a step's own code may use besides plain Effect: state shared between runs, and a way to +// wake a run that waits. Both touch the world, so they are for inside `step` and `onEnd`. +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import type * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { checkOptions } from "./options.ts"; +import { type StepReferences, stepReferences } from "./runReferences.ts"; +import type { WorkflowDefinition } from "./workflow.ts"; +import { WorkflowForge } from "./WorkflowForge.ts"; +import type { WorkflowError, WorkflowInputError } from "./Workflows.ts"; +import type { + RunParent, + SignalAddress, + WorkflowRunStatus, + WorkflowStore, +} from "./WorkflowStore.ts"; + +/** The shared store as rows of JSON text. `store` puts schemas on top. */ +export class KeyValues extends Context.Service< + KeyValues, + { + readonly get: (key: string) => Effect.Effect; + readonly set: (key: string, valueJson: string) => Effect.Effect; + readonly delete: (key: string) => Effect.Effect; + readonly list: ( + prefix: string, + ) => Effect.Effect>; + readonly transaction: (effect: Effect.Effect) => Effect.Effect; + } +>()("t3/workflows/stepServices/KeyValues") {} + +export type SendSignal = ( + address: SignalAddress, + value: Schema.Json, + options: { readonly id: string; readonly ttl?: Duration.Input }, +) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>; + +/** Everyone who waits on a key, in one workflow or in all of them. */ +export interface EveryoneAt { + readonly channel: string; + readonly workflow?: string | undefined; +} +export type SendSignalToAll = (address: EveryoneAt, value: Schema.Json) => Effect.Effect; + +/** A run as a step of another run sees it. `key` is what it was started with. */ +export interface RunSummary { + readonly id: string; + readonly workflow: string; + readonly key: string; + readonly title: string; + readonly status: WorkflowRunStatus; + readonly detail: string | null; + readonly startedAt: string; + readonly endedAt: string | null; +} +export interface RunFilter { + readonly workflow?: string | undefined; + readonly status?: WorkflowRunStatus | undefined; + readonly keyPrefix?: string | undefined; +} + +/** Signals from the step that is running. Its signals are numbered, so a retry sends the same ones. */ +export class Signals extends Context.Service< + Signals, + { + readonly sendAll: SendSignalToAll; + readonly send: ( + address: SignalAddress, + value: Schema.Json, + options?: { readonly id?: string; readonly ttl?: Duration.Input }, + ) => Effect.Effect<"delivered" | "buffered", WorkflowInputError>; + } +>()("t3/workflows/stepServices/Signals") {} + +export type StartRun = ( + workflow: string, + input: unknown, + options: { + readonly idempotencyKey: string; + readonly parent?: RunParent; + /** The version the caller was written against. Without it, the newest registered. */ + readonly version?: number; + }, +) => Effect.Effect<{ readonly runId: string }, WorkflowError>; + +export type CancelRun = (runId: string, reason: string) => Effect.Effect; +export type ListRuns = (filter: RunFilter) => Effect.Effect>; + +/** Other runs, from the step that is running: starting, finding and cancelling them. */ +export class Runs extends Context.Service< + Runs, + { readonly start: StartRun; readonly cancel: CancelRun; readonly list: ListRuns } +>()("t3/workflows/stepServices/Runs") {} + +export type InStep = KeyValues | Signals | Runs | WorkflowForge | StepReferences; + +/** + * What a step needs of the engine, which exists only once the engine does, while the workflows + * that use it are registered before. The engine fills this in when it starts. + */ +export class EngineLink extends Context.Service< + EngineLink, + { + current: + | { + readonly signal: SendSignal; + readonly signalAll: SendSignalToAll; + readonly start: StartRun; + readonly cancel: CancelRun; + readonly list: ListRuns; + /** Tell the run that invoked `runId`, if one did, how it ended. */ + readonly ended: (runId: string) => Effect.Effect; + } + | undefined; + /** The steps of each run that are running in this process right now. */ + readonly inFlight: InFlight; + } +>()("t3/workflows/stepServices/EngineLink") {} +export interface InFlight { + readonly track: ( + runId: string, + effect: Effect.Effect, + ) => Effect.Effect; + /** Whether a step of `runId` is running now. */ + readonly busy: (runId: string) => boolean; + /** Waits until no step of `runId` is running. */ + readonly settled: (runId: string) => Effect.Effect; +} + +// A step cannot be interrupted, so whatever cleans up after a cancelled run waits for it here. +const makeInFlight = (): InFlight => { + const running = new Map }>(); + return { + track: (runId, effect) => + Effect.acquireUseRelease( + Effect.sync(() => { + const entry = running.get(runId) ?? { count: 0, idle: Deferred.makeUnsafe() }; + entry.count++; + running.set(runId, entry); + return entry; + }), + () => effect, + (entry) => + Effect.suspend(() => { + if (--entry.count > 0) return Effect.void; + running.delete(runId); + return Deferred.succeed(entry.idle, undefined); + }), + ), + busy: (runId) => running.has(runId), + settled: (runId) => + Effect.suspend(() => { + const entry = running.get(runId); + return entry === undefined ? Effect.void : Deferred.await(entry.idle); + }), + }; +}; + +export const layerEngineLink = Layer.sync(EngineLink, () => ({ + current: undefined, + inFlight: makeInFlight(), +})); + +const engineOf = (link: EngineLink["Service"]) => + link.current === undefined + ? Effect.die(new Error("The workflow engine is not up.")) + : Effect.succeed(link.current); + +/** + * The services for the step `name` of `runId`. Each signal it sends is the two, where it goes, + * and how many it sent there before, so a retry that sends the same again is not new. What it + * touches through the forge is kept against it. + */ +export const forStep = ( + store: WorkflowStore["Service"], + keyValues: KeyValues["Service"], + link: EngineLink["Service"], + forge: WorkflowForge["Service"], + runId: string, + name: string, +): Context.Context => { + const owner = `${runId}/${name}`; + const sent = new Map(); + return Context.make(KeyValues, keyValues).pipe( + Context.add(WorkflowForge, forge), + Context.merge(stepReferences(store, runId, name)), + Context.add( + Signals, + Signals.of({ + send: Effect.fn("Signals.send")(function* (address, value, options) { + const { signal: send } = yield* engineOf(link); + const to = ( + "runId" in address + ? ["run", address.runId, address.wait] + : ["key", address.workflow, address.channel] + ) + .map(encodeURIComponent) + .join("/"); + const before = sent.get(to) ?? 0; + sent.set(to, before + 1); + return yield* send(address, value, { + id: options?.id ?? `${owner}/signal/${to}/${before}`, + ...(options?.ttl === undefined ? {} : { ttl: options.ttl }), + }); + }), + sendAll: Effect.fn("Signals.sendAll")(function* (address, value) { + const engine = yield* engineOf(link); + return yield* engine.signalAll(address, value); + }), + }), + ), + Context.add( + Runs, + Runs.of({ + start: Effect.fn("Runs.start")(function* (workflow, input, options) { + const engine = yield* engineOf(link); + return yield* engine.start(workflow, input, options); + }), + cancel: Effect.fn("Runs.cancel")(function* (target, reason) { + // Cancelling interrupts the run, and this step is the run: it would cut itself off + // halfway through the cancel. + if (target === runId) { + return yield* Effect.die( + new Error("A run cannot cancel itself. End it from its body with `stop`."), + ); + } + const engine = yield* engineOf(link); + return yield* engine.cancel(target, reason); + }), + list: Effect.fn("Runs.list")(function* (filter) { + const engine = yield* engineOf(link); + return yield* engine.list(filter); + }), + }), + ), + ); +}; + +export const layerKeyValues = Layer.effect( + KeyValues, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + // LIKE would read `%` and `_` in a prefix as patterns; a range does not. + const after = (prefix: string) => `${prefix}\u{10FFFF}`; + return KeyValues.of({ + get: Effect.fn("KeyValues.get")(function* (key) { + const rows = yield* sql<{ value_json: string }>` + SELECT value_json FROM workflow_store WHERE key = ${key} + `.pipe(Effect.orDie); + return rows[0]?.value_json; + }), + set: Effect.fn("KeyValues.set")(function* (key, valueJson) { + const at = DateTime.formatIso(yield* DateTime.now); + yield* sql` + INSERT INTO workflow_store (key, value_json, updated_at) + VALUES (${key}, ${valueJson}, ${at}) + ON CONFLICT (key) DO UPDATE + SET value_json = excluded.value_json, updated_at = excluded.updated_at + `.pipe(Effect.orDie); + }), + delete: Effect.fn("KeyValues.delete")(function* (key) { + yield* sql`DELETE FROM workflow_store WHERE key = ${key}`.pipe(Effect.orDie); + }), + list: Effect.fn("KeyValues.list")(function* (prefix) { + const rows = yield* sql<{ key: string; value_json: string }>` + SELECT key, value_json FROM workflow_store + WHERE key >= ${prefix} AND key < ${after(prefix)} ORDER BY key + `.pipe(Effect.orDie); + return rows.map((row) => ({ key: row.key, valueJson: row.value_json })); + }), + transaction: Effect.fn("KeyValues.transaction")(function* (effect) { + return yield* sql.withTransaction(effect).pipe(Effect.catchTags({ SqlError: Effect.die })); + }), + }); + }), +); + +/** A value that no longer fits its schema, or never did. */ +export class StoreValueError extends Schema.TaggedError()("StoreValueError", { + key: Schema.String, + problem: Schema.String, +}) { + override get message(): string { + return `The stored value at ${this.key} does not fit its schema: ${this.problem}`; + } +} + +/** + * One key of the store, with the schema of what it holds. `update` reads and writes as one + * action, so two runs counting on the same key never lose a count; returning `undefined` from it + * deletes the key. + */ +const entry = (key: string, schema: Schema.Codec) => { + const codec = Schema.fromJsonString(Schema.toCodecJson(schema)); + const decode = Schema.decodeEffect(codec); + const encode = Schema.encodeEffect(codec); + const invalid = (error: unknown) => new StoreValueError({ key, problem: String(error) }); + const read = (store: KeyValues["Service"]) => + Effect.flatMap(store.get(key), (text) => + text === undefined + ? Effect.succeed(Option.none()) + : Effect.mapBoth(decode(text), { onFailure: invalid, onSuccess: Option.some }), + ); + const write = (store: KeyValues["Service"], value: A) => + encode(value).pipe( + Effect.mapError(invalid), + Effect.flatMap((text) => store.set(key, text)), + ); + return { + key, + get: Effect.flatMap(KeyValues, read), + set: (value: A) => Effect.flatMap(KeyValues, (store) => write(store, value)), + delete: Effect.flatMap(KeyValues, (store) => store.delete(key)), + update: (change: (current: Option.Option) => A | undefined) => + Effect.flatMap(KeyValues, (store) => + store.transaction( + Effect.gen(function* () { + const next = change(yield* read(store)); + if (next === undefined) { + yield* store.delete(key); + return Option.none(); + } + yield* write(store, next); + return Option.some(next); + }), + ), + ), + }; +}; + +/** Every key that starts with `prefix`, in key order, with what it holds. */ +const entries = (prefix: string, schema: Schema.Codec) => { + const codec = Schema.fromJsonString(Schema.toCodecJson(schema)); + const decode = Schema.decodeEffect(codec); + return Effect.flatMap(KeyValues, (store) => + Effect.flatMap(store.list(prefix), (rows) => + Effect.forEach(rows, (row) => + Effect.mapBoth(decode(row.valueJson), { + onFailure: (error) => new StoreValueError({ key: row.key, problem: String(error) }), + onSuccess: (value) => ({ key: row.key, value }), + }), + ), + ), + ); +}; + +/** Several reads and writes as one: all of them happen, or none. */ +const transaction = (effect: Effect.Effect) => + Effect.flatMap(KeyValues, (store) => store.transaction(effect)); + +/** + * State that outlives a run and is shared by every workflow on this server. Use it inside `step` + * or `onEnd`: what it returns changes over time, so the body itself must not read it. + */ +export const store = { entry, entries, transaction }; + +/** A workflow by its name or its definition, wherever one is named. */ +export type WorkflowName = string | Pick; +const nameOf = (workflow: WorkflowName) => + typeof workflow === "string" ? workflow : workflow.name; + +/** + * Wake a run that waits: `{ runId, wait }` for one wait of one run, `{ workflow, channel }` for + * whichever run of a workflow waits on a channel. Inside `step` or `onEnd` only. + */ +export const signal = ( + address: + | { readonly runId: string; readonly wait: string } + | { readonly workflow: WorkflowName; readonly channel: string }, + value: Schema.Json, + options?: { readonly id?: string; readonly ttl?: Duration.Input }, +) => + Effect.flatMap(Signals, (signals) => { + checkOptions( + "signal's address", + address, + "runId" in address ? ["runId", "wait"] : ["workflow", "channel"], + ); + checkOptions("signal", options, ["id", "ttl"]); + return signals.send( + "runId" in address + ? address + : { workflow: nameOf(address.workflow), channel: address.channel }, + value, + options, + ); + }); + +/** + * Start a run of another workflow and go on without it. The same `key` is the same run. Inside + * `step` or `onEnd` only; to wait for the run's result, use `invoke` in the body instead. + */ +export const start =

    ( + workflow: WorkflowDefinition

    , + payload: P, + options: { readonly key: string }, +) => + Effect.flatMap(Runs, (runs) => { + checkOptions("start", options, ["key"]); + return runs.start(workflow.name, payload, { + idempotencyKey: options.key, + version: workflow.version, + }); + }); + +/** + * Wake every run that waits on `channel`, in one workflow or, without `workflow`, in all of them. + * Returns how many it woke. Nothing is kept for a wait that opens later, so a run that waits on + * a condition checks the condition in a step first, and gives its wait a timeout to check again. + * Inside `step` or `onEnd` only. + */ +export const signalAll = ( + address: { readonly channel: string; readonly workflow?: WorkflowName }, + value: Schema.Json, +) => + Effect.flatMap(Signals, (signals) => { + checkOptions("signalAll's address", address, ["channel", "workflow"]); + return signals.sendAll( + { + channel: address.channel, + workflow: address.workflow === undefined ? undefined : nameOf(address.workflow), + }, + value, + ); + }); + +/** + * Cancel another run, as a person would: its agents are stopped, its questions withdrawn, what + * it invoked is cancelled, and its `onEnd` runs. A run that has ended is left alone. Inside + * `step` or `onEnd` only. + */ +export const cancel = (runId: string, reason: string) => + Effect.flatMap(Runs, (runs) => runs.cancel(runId, reason)); + +/** + * Find runs: of one workflow, in one status, or started with a key that begins with `keyPrefix`. + * Newest first, 500 at most. Inside `step` or `onEnd` only: the answer changes over time. + */ +export const runs = (filter?: { + readonly workflow?: WorkflowName; + readonly status?: WorkflowRunStatus; + readonly keyPrefix?: string; +}) => + Effect.flatMap(Runs, (all) => { + checkOptions("runs", filter, ["workflow", "status", "keyPrefix"]); + return all.list({ + workflow: filter?.workflow === undefined ? undefined : nameOf(filter.workflow), + status: filter?.status, + keyPrefix: filter?.keyPrefix, + }); + }); diff --git a/apps/server/src/workflows/triggers.ts b/apps/server/src/workflows/triggers.ts new file mode 100644 index 0000000000000..9e90842ab7fda --- /dev/null +++ b/apps/server/src/workflows/triggers.ts @@ -0,0 +1,156 @@ +// What starts a run by itself. A trigger hands its workflow one value, so a workflow that lists +// a trigger takes that value as its payload: `Tick` for a schedule, `WebhookRequest` for a hook. +import * as Duration from "effect/Duration"; +import * as Schema from "effect/Schema"; + +import { parseTimeOfDay } from "../scheduledTasks/Schedule.ts"; +import { checkOptions, durationOf } from "./options.ts"; +import type { Issue, PullRequest } from "./WorkflowForge.ts"; + +/** The time a scheduled run was due, which is not the time it started. */ +export const Tick = Schema.Struct({ scheduledAt: Schema.String }); +export type Tick = typeof Tick.Type; + +/** A request to a workflow's hook URL, as it arrived. Header names are lower case. */ +export const WebhookRequest = Schema.Struct({ + method: Schema.String, + headers: Schema.Record(Schema.String, Schema.String), + query: Schema.String, + body: Schema.String, +}); +export type WebhookRequest = typeof WebhookRequest.Type; + +export interface ScheduleTrigger { + readonly kind: "schedule"; + /** Stable across restarts: where this trigger's next time is kept. */ + readonly id: string; + readonly schedule: + | { readonly type: "interval"; readonly everyMs: number } + | { + readonly type: "fixed_time"; + readonly timeOfDay: string; + readonly weekdays?: ReadonlyArray; + }; +} +export interface WebhookTrigger { + readonly kind: "webhook"; + readonly name: string; + readonly key: ((request: WebhookRequest) => string | undefined) | undefined; +} +/** New issues or pull requests of a project, which the engine looks for by itself. */ +export interface OpenedTrigger { + readonly kind: "issues" | "pullRequests"; + /** Stable across restarts: where this trigger keeps how far it has looked. */ + readonly id: string; + readonly project: string; + readonly labels?: ReadonlyArray | undefined; + readonly query?: string | undefined; +} +/** `Fires` is what the trigger gives the run it starts. */ +export type Trigger = (ScheduleTrigger | WebhookTrigger | OpenedTrigger) & { + readonly fires?: (value: Fires) => void; +}; + +/** A run every so often, counted from when the last one was started. At least a minute. */ +export const every = (interval: Duration.Input): Trigger => { + const everyMs = Duration.toMillis(durationOf(`every(${JSON.stringify(interval)})`, interval)); + // The sweep would quietly stretch a shorter one to a minute. + if (everyMs < 60_000) { + throw new Error(`every(${JSON.stringify(interval)}) is shorter than the shortest, one minute.`); + } + return { kind: "schedule", id: `every:${everyMs}`, schedule: { type: "interval", everyMs } }; +}; + +/** + * A run at a time of day (`"09:00"`) on the server's clock, on every day or on the given weekdays + * (0 is Sunday). A time missed by more than ten minutes, for a server that was down, is skipped. + */ +export const daily = ( + timeOfDay: string, + options?: { readonly weekdays?: ReadonlyArray }, +): Trigger => { + checkOptions(`daily("${timeOfDay}")`, options, ["weekdays"]); + const weekdays = options?.weekdays; + // Read once here: a time the schedule cannot read would otherwise never fire, without a word. + if (parseTimeOfDay(timeOfDay) === null) { + throw new Error(`daily("${timeOfDay}") needs a 24-hour time such as "09:00".`); + } + if (weekdays?.some((day) => !Number.isInteger(day) || day < 0 || day > 6)) { + throw new Error(`daily's weekdays are 0 (Sunday) to 6 (Saturday), not ${weekdays.join(", ")}.`); + } + return { + kind: "schedule", + id: `daily:${timeOfDay}:${weekdays?.toSorted().join(",") ?? "all"}`, + schedule: { type: "fixed_time", timeOfDay, ...(weekdays === undefined ? {} : { weekdays }) }, + }; +}; + +/** + * A run for each request to this workflow's hook URL (`t3 workflow hooks` prints it). The run + * decides what the request means, `stop` included. Two requests for which `key` gives the same + * text are one run, which is how a sender's retries are told from new deliveries. + */ +export const webhook = ( + name: string, + options?: { readonly key?: (request: WebhookRequest) => string | undefined }, +): Trigger => { + checkOptions(`webhook("${name}")`, options, ["key"]); + return { kind: "webhook", name, key: options?.key }; +}; + +/** Refuses two hooks of one name, or two triggers that would fire on the same thing. */ +export const checkTriggers = ( + workflow: string, + triggers: ReadonlyArray, +) => { + const seen = new Set(); + for (const trigger of triggers) { + const id = trigger.kind === "webhook" ? `webhook:${trigger.name}` : trigger.id; + if (seen.has(id)) { + throw new Error( + trigger.kind === "webhook" + ? `workflow("${workflow}") has two hooks named "${trigger.name}". Give each its own name.` + : `workflow("${workflow}") lists the same ${trigger.kind === "schedule" ? "schedule" : "trigger"} twice. List it once.`, + ); + } + seen.add(id); + } +}; + +const openedId = ( + kind: OpenedTrigger["kind"], + options: { + readonly project: string; + readonly labels?: ReadonlyArray; + readonly query?: string; + }, +) => + // A tuple, so no label or query can be read as part of another. + JSON.stringify([kind, options.project, options.labels?.toSorted() ?? [], options.query ?? ""]); + +/** + * A run for each issue opened in the project's tracker from now on, with the issue as its + * payload (`Issue`). Issues that were already there when the workflow was first loaded start + * nothing. `labels` are ones the issue must carry, all of them; `query` is free text for the + * tracker. The tracker is asked about once a minute. + */ +export const issuesOpened = (options: { + readonly project: string; + readonly labels?: ReadonlyArray; + readonly query?: string; +}): Trigger => { + checkOptions("issues.opened", options, ["project", "labels", "query"]); + return { kind: "issues", id: openedId("issues", options), ...options }; +}; + +/** + * A run for each pull request opened against the project's repository from now on, with the pull + * request as its payload (`PullRequest`). `query` is free text for the host. + */ +export const pullRequestsOpened = (options: { + readonly project: string; + readonly query?: string; +}): Trigger => { + checkOptions("pullRequests.opened", options, ["project", "query"]); + return { kind: "pullRequests", id: openedId("pullRequests", options), ...options }; +}; diff --git a/apps/server/src/workflows/workflow.ts b/apps/server/src/workflows/workflow.ts new file mode 100644 index 0000000000000..3359307875999 --- /dev/null +++ b/apps/server/src/workflows/workflow.ts @@ -0,0 +1,897 @@ +// The author-facing primitives. A workflow body is replayed after a restart, so anything that +// touches the world goes through `step`; these are all a body may use. +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as SchemaAST from "effect/SchemaAST"; +import * as SqlClient from "effect/sql/SqlClient"; +import { Activity, DurableClock, DurableDeferred, Workflow, WorkflowEngine } from "effect/workflow"; + +import { checkOptions, durationOf } from "./options.ts"; +import { + EngineLink, + forStep, + type InFlight, + type InStep, + KeyValues, + Runs, +} from "./stepServices.ts"; +import { + checkTriggers, + type OpenedTrigger, + type ScheduleTrigger, + type Trigger, + type WebhookTrigger, +} from "./triggers.ts"; +import type { WorkflowAgents } from "./WorkflowAgents.ts"; +import { unavailable, WorkflowForge } from "./WorkflowForge.ts"; +import * as WorkflowStore from "./WorkflowStore.ts"; + +/** A step that could not be completed. Its run is paused until someone resumes it. */ +export class StepFailed extends Schema.TaggedError()("StepFailed", { + step: Schema.String, + reason: Schema.String, +}) { + override get message(): string { + return `${this.step}: ${this.reason}`; + } +} + +/** The workflow's own decision to end without a result. */ +export class WorkflowStop extends Schema.TaggedError()("WorkflowStop", { + reason: Schema.String, + /** The run was never for this workflow to do, which lists leave out. */ + skipped: Schema.optional(Schema.Boolean), +}) { + override get message(): string { + return this.reason; + } +} + +/** What the primitives need from the run they are called in. */ +export class RunContext extends Context.Service< + RunContext, + { + readonly runId: string; + readonly workflow: string; + readonly store: WorkflowStore.WorkflowStore["Service"]; + /** Names used so far in this pass over the body: two steps with one name would share a result. */ + readonly names: Set; + /** What the code of the step `name` may use. */ + readonly forStep: (name: string) => Context.Context; + /** The steps running now, which a cancelled run's cleanup waits for. */ + readonly inFlight: InFlight; + } +>()("t3/workflows/workflow/RunContext") {} + +/** What a workflow body may require: the run it is in, the engine, and somewhere to run agents. */ +export type InRun = + | RunContext + | WorkflowAgents + | WorkflowEngine.WorkflowEngine + | WorkflowEngine.WorkflowInstance; + +/** Takes `name` for one step of the run. Step results and the step list are both kept by name. */ +export const claim = (name: string, cleanup = false) => + Effect.flatMap(RunContext, (run) => { + // The cleanup step's name is its own, or a body step would take it and cleanup never run. + if (name === END_STEP && !cleanup) { + return Effect.die( + new Error( + `"${END_STEP}" is the name of workflow ${run.workflow}'s cleanup step. Name this step something else.`, + ), + ); + } + if (run.names.has(name)) { + return Effect.die( + new Error( + `Two steps in workflow ${run.workflow} are named "${name}". Names are unique in a run.`, + ), + ); + } + run.names.add(name); + return Effect.succeed(run); + }); + +/** An error as one line for a person, with what caused it when the error only wraps something. */ +export const text = (error: unknown): string => { + if (typeof error === "string") return error.slice(0, 2000); + if (typeof error !== "object" || error === null) return String(error); + // Also an error that came back from the journal, which is its fields and no longer an Error. + const fields = error as { + readonly message?: unknown; + readonly reason?: unknown; + cause?: unknown; + }; + const message = + typeof fields.message === "string" && fields.message !== "" + ? fields.message + : typeof fields.reason === "string" + ? fields.reason + : "Unknown error"; + return (fields.cause === undefined ? message : `${message}: ${text(fields.cause)}`).slice( + 0, + 2000, + ); +}; + +// What a workflow without `returns` returns: any JSON value, or nothing. +const ANY_JSON = Schema.UndefinedOr(Schema.Json); + +/** Where in `value` JSON cannot hold what it finds, with `undefined` counted only when `strict`. */ +const notJson = (value: unknown, at: string, strict: boolean): string | undefined => { + if (value === null || typeof value === "string" || typeof value === "boolean") return undefined; + if (typeof value === "number") return Number.isFinite(value) ? undefined : `${at} is ${value}`; + if (value === undefined) return strict ? `${at} is undefined` : undefined; + if (Array.isArray(value)) { + for (const [index, item] of value.entries()) { + const found = notJson(item, `${at}[${index}]`, strict); + if (found !== undefined) return found; + } + return undefined; + } + const proto = typeof value === "object" ? Object.getPrototypeOf(value) : undefined; + if (proto !== Object.prototype && proto !== null) { + return `${at} is ${typeof value === "object" ? (proto?.constructor?.name ?? "an object") : `a ${typeof value}`}`; + } + for (const [key, field] of Object.entries(value as object)) { + const found = notJson(field, `${at}.${key}`, strict); + if (found !== undefined) return found; + } + return undefined; +}; + +/** A value that did not encode, said with where JSON could not hold it, which `Schema.Json` omits. */ +const encodeFailure = (what: string, error: unknown, value: unknown) => { + const where = notJson(value, what, true); + return where === undefined ? text(error) : `${text(error)}: ${where}`; +}; + +/** A step result the journal cannot store, which fails the step it came from. */ +const unstorable = (error: unknown, value: unknown) => + Effect.die(new Error(encodeFailure("the result", error, value))); + +/** What a run without `returns` returns, read as `JSON.stringify` reads it. */ +const untypedResult = (value: unknown): Effect.Effect => { + const where = notJson(value, "the run's result", false); + if (where !== undefined) return Effect.die(new Error(`The run's result is not JSON: ${where}.`)); + return Effect.succeed( + value === undefined ? null : (JSON.parse(JSON.stringify(value)) as Schema.Json), + ); +}; + +/** + * One journaled action of the step `name`: it happens once, and a replay returns what it stored. + * A failure marks the step failed and pauses the run here; resuming the run executes it again. + */ +export const journaled = ( + run: RunContext["Service"], + name: string, + action: string, + returns: Schema.Codec, + execute: Effect.Effect, + // The run waits for a person after this fails, not for `resumeAfter`. + held = false, +) => { + const codec = Schema.toCodecJson(returns); + const encodable = Schema.encodeEffect(codec); + return Activity.make({ + name: action, + success: returns, + error: StepFailed, + execute: run.inFlight.track(run.runId, execute).pipe( + // A result the journal cannot store is this step's failure, found before it is journaled. + Effect.tap((value) => Effect.catch(encodable(value), (error) => unstorable(error, value))), + // The engine reads its own 64-bit ids as BigInt. What a step calls must not inherit that. + Effect.provideService(SqlClient.SafeIntegers, false), + // Also a step that dies: left as a defect the engine would park the run without a word. + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause as Cause.Cause) + : Effect.fail(new StepFailed({ step: name, reason: text(Cause.squash(cause)) })), + ), + Effect.tapError((error) => + Effect.andThen( + run.store.stepEnded(run.runId, name, "failed", error.reason), + run.store.runPaused(run.runId, error.message, held), + ), + ), + ), + }); +}; + +/** How an invoked run ended, as its parent's wait receives it. */ +export const ChildEnd = Schema.Struct({ + outcome: Schema.Literals(["completed", "stopped", "skipped", "cancelled"]), + value: Schema.Json, + reason: Schema.optional(Schema.String), +}); + +export interface StepRetry { + /** How many more times to try before the run is paused. */ + readonly times: number; + readonly schedule?: Schedule.Schedule; +} +// Once, unless asked: a step that posts or merges must not do it again after a lost reply. +const DEFAULT_RETRY: StepRetry = { times: 0 }; + +const checkStepOptions = (what: string, options: { readonly retry?: StepRetry | undefined }) => { + checkOptions(what, options, ["returns", "retry"]); + checkOptions(`${what}'s retry`, options?.retry, ["times", "schedule"]); +}; + +/** How `step.try` ended: its value, or why it failed once its retries were used up. */ +export type StepAttempt = + | { readonly outcome: "done"; readonly value: A } + | { readonly outcome: "failed"; readonly reason: string }; + +const attemptOf = (returns: Schema.Codec) => + Schema.Union([ + Schema.Struct({ outcome: Schema.Literal("done"), value: returns }), + Schema.Struct({ outcome: Schema.Literal("failed"), reason: Schema.String }), + ]); + +/** + * Do something once per run. The result is stored, and a replay returns the stored result. + * + * A failure is retried by `retry`, then pauses the run at this step: resuming the run runs the step + * again. Nothing in the body can catch that. For a failure the workflow decides about, use + * `step.try`. + */ +export const step = Object.assign( + ( + name: string, + options: { readonly returns: Schema.Codec; readonly retry?: StepRetry }, + code: Effect.Effect, + ): Effect.Effect => { + checkStepOptions(`step("${name}")`, options); + return Effect.orDie(stepAs(claim(name), name, options, code)); + }, + { + /** As `step`, but a failure left after the retries comes back as `failed` with the reason. */ + try: ( + name: string, + options: { readonly returns: Schema.Codec; readonly retry?: StepRetry }, + code: Effect.Effect, + ): Effect.Effect, never, InRun> => { + checkStepOptions(`step.try("${name}")`, options); + return Effect.orDie( + stepAs( + claim(name), + name, + { returns: attemptOf(options.returns), retry: options.retry }, + code, + (tried) => + tried.pipe( + Effect.map((value): StepAttempt => ({ outcome: "done", value })), + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.failCause(cause as Cause.Cause) + : Effect.succeed>({ + outcome: "failed", + reason: text(Cause.squash(cause)), + }), + ), + ), + ), + ); + }, + }, +); + +const stepAs = ( + claimed: Effect.Effect, + name: string, + options: { readonly returns: Schema.Codec; readonly retry?: StepRetry | undefined }, + code: Effect.Effect, + // What the step makes of its tries: by default their value, or their failure. + settle: (tried: Effect.Effect) => Effect.Effect = (tried) => + tried as unknown as Effect.Effect, +): Effect.Effect => + Effect.flatMap(claimed, (run) => { + const retry = options.retry ?? DEFAULT_RETRY; + const resultCodec = Schema.toCodecJson(options.returns); + const encodeResult = Schema.encodeEffect(resultCodec); + // Made per try, so a retry numbers its signals from the start again and counts as an attempt. + const execute = Effect.andThen( + run.store.stepStarted(run.runId, name, "step"), + Effect.suspend(() => Effect.provideContext(code, run.forStep(name))), + ); + return journaled( + run, + name, + `step/${name}`, + options.returns, + settle( + retry.times === 0 + ? execute + : Effect.retry(execute, { + times: retry.times, + ...(retry.schedule === undefined ? {} : { schedule: retry.schedule }), + }), + ).pipe( + // A value that does not encode fails the step, so it is never marked done first. + Effect.tap((value) => + Effect.flatMap( + Effect.catch(encodeResult(value), (error) => unstorable(error, value)), + (json) => + Effect.andThen( + run.store.stepEnded(run.runId, name, "completed", null), + // For a person reading the run. + Effect.ignore(run.store.stepResult(run.runId, name, json as Schema.Json)), + ), + ), + ), + ), + ); + }); + +/** A sleep that survives a restart. */ +export const sleep = Effect.fn("workflow.sleep")(function* ( + name: string, + duration: Duration.Input, +): Effect.fn.Return { + const length = durationOf(`sleep("${name}")`, duration); + const run = yield* claim(name); + // Listed like any step, with when it wakes, so a run that sleeps for days says so. + yield* Activity.make({ + name: `sleep/${name}/open`, + execute: Effect.gen(function* () { + const wakes = DateTime.addDuration(yield* DateTime.now, length); + yield* run.store.stepStarted(run.runId, name, "sleep"); + yield* run.store.stepDetail(run.runId, name, DateTime.formatIso(wakes)); + yield* run.store.runStatus(run.runId, "waiting", `sleep ${name}`); + }), + }); + // Effect keeps a short sleep in memory, where a restart would start it over. + yield* DurableClock.sleep({ + name: `sleep/${name}`, + duration: length, + inMemoryThreshold: Duration.zero, + }); + yield* Activity.make({ + name: `sleep/${name}/close`, + execute: Effect.andThen( + run.store.stepEnded(run.runId, name, "completed", null), + run.store.runResumed(run.runId), + ), + }); +}); + +export const Woke = Schema.Struct({ expired: Schema.Boolean, value: Schema.Json }); +export const wakeOf = (name: string) => DurableDeferred.make(`wait/${name}`, { success: Woke }); +const finite = [Schema.isFinite()] as const; +// JSON carries a bare `Schema.Number` as a number or the text "Infinity", "-Infinity" or "NaN", +// and that form drops the number's own checks. Whoever writes the value is told a finite number +// with its checks instead. Transformations and recursion keep their own form. +const finiteNumbers = (ast: SchemaAST.AST): SchemaAST.AST => { + if (ast.encoding !== undefined) return ast; + if (SchemaAST.isNumber(ast)) { + return new SchemaAST.Number( + ast.annotations, + ast.checks === undefined ? finite : [...ast.checks, ...finite], + undefined, + ast.context, + ); + } + if (SchemaAST.isObjects(ast)) { + return new SchemaAST.Objects( + ast.propertySignatures.map( + (field) => new SchemaAST.PropertySignature(field.name, finiteNumbers(field.type)), + ), + ast.indexSignatures.map( + (index) => new SchemaAST.IndexSignature(index.parameter, finiteNumbers(index.type)), + ), + ast.annotations, + ast.checks, + undefined, + ast.context, + ast.encodingChecks, + ); + } + if (SchemaAST.isArrays(ast)) { + return new SchemaAST.Arrays( + ast.isMutable, + ast.elements.map(finiteNumbers), + ast.rest.map(finiteNumbers), + ast.annotations, + ast.checks, + undefined, + ast.context, + ast.encodingChecks, + ); + } + if (SchemaAST.isUnion(ast)) { + return new SchemaAST.Union( + ast.types.map(finiteNumbers), + ast.options, + ast.annotations, + ast.checks, + undefined, + ast.context, + ast.encodingChecks, + ); + } + return ast; +}; + +/** What a value must look like, as JSON Schema; `closed` objects turn down keys they do not name. */ +export const jsonSchemaOf = (schema: Schema.Top, closed = false): Record => { + const document = Schema.toJsonSchemaDocument( + Schema.make(finiteNumbers(schema.ast)), + closed ? { onExcessProperty: "error" } : undefined, + ); + return { ...document.schema, $defs: document.definitions } as Record; +}; + +/** `wait`, also as the question a person answers: `request` is what an inbox shows them. */ +export const waitAs = Effect.fn("workflow.wait")(function* ( + kind: "wait" | "ask", + name: string, + options: WaitOptions, +): Effect.fn.Return, StepFailed, InRun> { + return yield* waitClaimed(yield* claim(name), kind, name, options); +}); + +interface WaitOptions { + readonly returns: Schema.Codec; + readonly timeout?: Duration.Input | undefined; + readonly channel?: string | undefined; + readonly request?: Schema.Json | undefined; + /** What the engine looks at to end the wait by itself. */ + readonly watch?: Schema.Json | undefined; +} + +const sameAddress = (left: WorkflowStore.SignalAddress, right: WorkflowStore.SignalAddress) => + "runId" in left + ? "runId" in right && left.runId === right.runId && left.wait === right.wait + : "channel" in right && left.workflow === right.workflow && left.channel === right.channel; + +const waitClaimed = Effect.fnUntraced(function* ( + run: RunContext["Service"], + kind: "wait" | "ask", + name: string, + options: WaitOptions, +): Effect.fn.Return, StepFailed, InRun> { + const here: WorkflowStore.SignalAddress = { runId: run.runId, wait: name }; + const schema = jsonSchemaOf(options.returns); + const codec = Schema.toCodecJson(options.returns); + const decode = Schema.decodeEffect(codec); + const fits = (value: Schema.Json) => Effect.result(decode(value)); + const addresses: ReadonlyArray = + options.channel === undefined + ? [here] + : [here, { workflow: run.workflow, channel: options.channel }]; + // Whatever arrived early is delivered now, checked as this wait reads it. The mail goes only + // after the wake: waking twice is harmless, and losing the signal is not. + const deliverEarly = Effect.fnUntraced(function* ( + wake: ReturnType, + token: DurableDeferred.Token, + ) { + const passed = new Set(); + while (true) { + const early = yield* run.store.mailNext(addresses, passed); + if (early === undefined) return; + const value = WorkflowStore.jsonValue(early.valueJson); + if (Result.isFailure(yield* fits(value))) { + // Kept when it went to a channel: another run, or another version, may read it. + if (sameAddress(early.address, here)) yield* run.store.mailDelete(early.signalId); + passed.add(early.signalId); + continue; + } + const woke = { expired: false, value }; + const outcome = yield* run.store.mailDeliver(early.signalId, run.runId, name, woke); + // Another wait on the same key took that one; there may be a next. + if (outcome === "gone") continue; + // Another signal claimed this wait first: its wake, or the sweep, carries what it claimed. + if (outcome === "claimed") return; + yield* DurableDeferred.succeed(wake, { token, value: woke }); + return; + } + }); + const first = wakeOf(name); + const firstToken = yield* DurableDeferred.token(first); + yield* Activity.make({ + name: `wait/${name}/open`, + execute: Effect.gen(function* () { + const deadline = + options.timeout === undefined + ? null + : DateTime.formatIso( + DateTime.addDuration(yield* DateTime.now, Duration.fromInputUnsafe(options.timeout)), + ); + yield* run.store.stepStarted(run.runId, name, kind); + yield* run.store.waitOpened({ + runId: run.runId, + name, + workflow: run.workflow, + key: options.channel, + token: firstToken, + schemaJson: WorkflowStore.jsonText(schema), + requestJson: options.request === undefined ? null : WorkflowStore.jsonText(options.request), + watchJson: options.watch === undefined ? null : WorkflowStore.jsonText(options.watch), + deadline, + }); + yield* run.store.runStatus(run.runId, "waiting", name); + yield* deliverEarly(first, firstToken); + }), + }); + // A value that fit the wait's JSON Schema can still fail its codec. It was not for this wait, + // so the wait opens again under a fresh wake instead of breaking the run on every replay. + let wake = first; + for (let again = 1; ; again++) { + const woke = yield* DurableDeferred.await(wake); + const value = woke.expired ? undefined : yield* fits(woke.value); + if (value !== undefined && Result.isFailure(value)) { + const problem = `It was signalled with a value it cannot read, and waits again: ${text(value.failure)}`; + wake = wakeOf(`${name}/again/${again}`); + const token = yield* DurableDeferred.token(wake); + const next = wake; + yield* Activity.make({ + name: `wait/${name}/again/${again}`, + execute: Effect.gen(function* () { + yield* run.store.waitReopened(run.runId, name, token); + yield* run.store.stepDetail(run.runId, name, problem.slice(0, 2000)); + yield* deliverEarly(next, token); + }), + }); + continue; + } + yield* Activity.make({ + name: `wait/${name}/close`, + execute: Effect.gen(function* () { + yield* run.store.waitClosed(run.runId, name); + yield* run.store.stepEnded(run.runId, name, "completed", woke.expired ? "timed out" : null); + if (!woke.expired) yield* run.store.stepResult(run.runId, name, woke.value); + yield* run.store.runResumed(run.runId); + }), + }); + return value === undefined ? Option.none() : Option.some(value.success); + } +}); + +/** + * Sleep until something outside signals this wait; `None` when the timeout passes first. + * Addressed by run and wait name, or by `channel` (scoped to the workflow's name) when the sender + * cannot know the run. A signal sent before the wait opened is delivered when it opens. + */ +export const wait = ( + name: string, + options: { + readonly returns: Schema.Codec; + readonly timeout?: Duration.Input; + readonly channel?: string; + }, +): Effect.Effect, never, InRun> => { + checkOptions(`wait("${name}")`, options, ["returns", "timeout", "channel"]); + return Effect.orDie(waitAs("wait", name, options)); +}; + +/** End the run by the workflow's own decision. It ends as `stopped`, which is not a failure. */ +export const stop = (reason: string): Effect.Effect => + Effect.fail(new WorkflowStop({ reason })); + +/** + * End the run because it was not this workflow's to do: a webhook delivery it ignores, a pull + * request it opened itself. It ends as `skipped`, which lists leave out unless asked. Use `stop` + * for a run that did something and then decided to end. + */ +export const skip = (reason: string): Effect.Effect => + Effect.fail(new WorkflowStop({ reason, skipped: true })); + +/** Name the run in lists. Defaults to the workflow's name and the run's key. */ +export const title = ( + value: string, + ...rest: ReadonlyArray +): Effect.Effect => { + // Files are not type-checked, so `title("name", text)` would title the run "name". + if (typeof value !== "string" || rest.length > 0) { + throw new Error("title takes only the text, as in title(`Release ${name}`), and no step name."); + } + return Effect.flatMap(RunContext, (current) => { + // Numbered by how many came before in the body, which a replay walks the same way. + let n = 0; + while (current.names.has(`title/${n}`)) n++; + const name = `title/${n}`; + return Effect.flatMap(claim(name), (run) => + Activity.make({ name, execute: run.store.runTitle(run.runId, value) }), + ); + }).pipe(Effect.orDie); +}; + +// The defaults are every workflow: a registry holds workflows of every payload and result type. +export interface WorkflowDefinition

    { + /** Types only: what a run is started with and what it returns, for `start` and `invoke`. */ + readonly "~types"?: { readonly payload: (payload: P) => void; readonly returns: A }; + readonly name: string; + readonly version: number; + readonly payload: Schema.Codec; + readonly returns: Schema.Codec; + /** How long a paused run rests before it is resumed by itself, per pause in a row. */ + readonly resumeAfter: ReadonlyArray; + readonly triggers: ReadonlyArray; + /** Fails with the reason as text: by here nothing reads the error but a person. */ + readonly onEnd: + | ((payload: never, end: RunEnd) => Effect.Effect) + | undefined; + // The registry holds workflows of every payload type; `workflow` is where the types are checked. + readonly body: ( + payload: never, + run: { readonly id: string }, + ) => Effect.Effect; +} + +/** How a run ended, as its `onEnd` is told. A paused run has not ended. */ +export interface RunEnd { + readonly id: string; + readonly outcome: "completed" | "stopped" | "skipped" | "cancelled"; + readonly reason: string | undefined; +} + +/** + * Run another workflow as part of this one and wait for how it ends. The other run is a run of + * its own, listed and resumable by itself; cancelling this run cancels it. A run that paused has + * not ended, so this waits on while someone resumes it. + */ +export const invoke = ( + name: string, + workflow: WorkflowDefinition, + payload: P, + options?: { readonly key?: string }, +): Effect.Effect< + | { readonly outcome: "completed"; readonly value: A } + | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string }, + never, + InRun +> => { + // Files are not type-checked, and a name would start nothing until its first step failed. + if (typeof workflow !== "object" || workflow === null || typeof workflow.name !== "string") { + return Effect.die( + new Error( + `invoke takes the workflow definition, not its name: invoke("${name}", …) was given ${JSON.stringify(workflow)}. Pass what workflow(…) returned.`, + ), + ); + } + checkOptions(`invoke("${name}")`, options, ["key"]); + return Effect.orDie(invokeAs(name, workflow, payload, options)); +}; + +const invokeAs = Effect.fn("workflow.invoke")(function* ( + name: string, + workflow: WorkflowDefinition, + payload: P, + options?: { readonly key?: string }, +): Effect.fn.Return< + | { readonly outcome: "completed"; readonly value: A } + | { readonly outcome: "stopped" | "skipped" | "cancelled"; readonly reason: string }, + StepFailed, + InRun +> { + // Taken before the child starts: a name already used would refuse the wait after the start. + const run = yield* claim(name); + yield* step( + `${name}/start`, + { returns: Schema.String }, + Effect.flatMap(Runs, (runs) => + runs.start(workflow.name, payload, { + version: workflow.version, + idempotencyKey: options?.key ?? `${run.runId}/${name}`, + parent: { runId: run.runId, wait: name }, + }), + ).pipe(Effect.map((started) => started.runId)), + ); + const ended = yield* waitClaimed(run, "wait", name, { returns: ChildEnd }); + if (Option.isNone(ended)) { + return yield* new StepFailed({ step: name, reason: "the wait ended without an outcome" }); + } + if (ended.value.outcome !== "completed") { + return { outcome: ended.value.outcome, reason: ended.value.reason ?? "" }; + } + const returnsCodec = Schema.toCodecJson(workflow.returns); + const decode = Schema.decodeEffect(returnsCodec); + const value = yield* decode(ended.value.value).pipe( + Effect.mapError((error) => new StepFailed({ step: name, reason: text(error) })), + ); + return { outcome: "completed", value: value as A }; +}); + +/** The step `onEnd` runs as. */ +export const END_STEP = "onEnd"; +const END_RETRY: StepRetry = { times: 3, schedule: Schedule.exponential("2 seconds") }; + +const DEFAULT_RESUME_AFTER: ReadonlyArray = [ + "5 minutes", + "20 minutes", + "80 minutes", +]; + +/** + * A workflow: a name, a version, and a body. + * + * A run keeps the version it started with. To change the order of steps or the shape of a stored + * result, register the new body under a higher version and keep the old one registered until its + * runs have ended. + */ +export const workflow = ( + name: string, + options: { + readonly version: number; + readonly payload: Schema.Codec; + readonly returns?: Schema.Codec; + readonly resumeAfter?: ReadonlyArray; + /** What starts a run by itself. Each must give what `payload` takes. */ + readonly triggers?: ReadonlyArray>; + /** + * Runs once when the run ends, however it ends, to give back what the run took: a machine, a + * lock. It gets the payload and the run's id, not the body's values, so name what the run + * takes after its id. It must be safe to run for a run that took nothing. + */ + readonly onEnd?: (payload: P, end: RunEnd) => Effect.Effect; + }, + body: ( + payload: P, + run: { readonly id: string }, + ) => Effect.Effect, +): WorkflowDefinition => { + checkOptions(`workflow("${name}")`, options, [ + "version", + "payload", + "returns", + "resumeAfter", + "triggers", + "onEnd", + ]); + // Read once now, so a duration that does not parse fails the file and not a paused run later. + for (const rest of options.resumeAfter ?? []) + durationOf(`workflow("${name}")'s resumeAfter`, rest); + checkTriggers(name, options.triggers ?? []); + return definitionOf(name, options, body); +}; + +const definitionOf = ( + name: string, + options: Parameters>[1], + body: Parameters>[2], +): WorkflowDefinition => ({ + name, + version: options.version, + // Erased here, once: the registry holds workflows of every payload and result type. + payload: options.payload as Schema.Codec, + // Without a schema the result is whatever JSON the body returned: dropping it would be a + // surprise, and a value that is not JSON pauses the run with the reason. + returns: (options.returns ?? ANY_JSON) as Schema.Codec, + resumeAfter: options.resumeAfter ?? DEFAULT_RESUME_AFTER, + triggers: options.triggers ?? [], + onEnd: + options.onEnd === undefined + ? undefined + : (payload, end) => options.onEnd!(payload, end).pipe(Effect.asVoid, Effect.mapError(text)), + body, +}); + +export const engineTag = (definition: Pick) => + `${definition.name}@${definition.version}`; + +const Outcome = Schema.Struct({ + outcome: Schema.Literals(["completed", "stopped", "skipped"]), + value: Schema.Json, + reason: Schema.optional(Schema.String), +}); + +export const engineWorkflow = (definition: WorkflowDefinition) => + Workflow.make(engineTag(definition), { + payload: { idempotencyKey: Schema.String, input: Schema.Json }, + idempotencyKey: (payload) => payload.idempotencyKey, + success: Outcome, + error: Schema.Union([StepFailed, WorkflowStop]), + // A failure parks the run instead of ending it; only an explicit resume wakes it. + }).annotate(Workflow.SuspendOnFailure, true); +export type EngineWorkflow = ReturnType; + +export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWorkflow) => { + const payloadCodec = Schema.toCodecJson(definition.payload); + const decodePayload = Schema.decodeEffect(payloadCodec); + const returnsCodec = Schema.toCodecJson(definition.returns); + const encodeResult = Schema.encodeUnknownEffect(returnsCodec); + return engine.toLayer((payload, runId) => + Effect.gen(function* () { + const store = yield* WorkflowStore.WorkflowStore; + const keyValues = yield* KeyValues; + const link = yield* EngineLink; + const forge = Option.getOrElse(yield* Effect.serviceOption(WorkflowForge), () => unavailable); + yield* Activity.make({ + name: "run/begin", + execute: store.runStarted({ + runId, + workflow: definition.name, + version: definition.version, + engineTag: engineTag(definition), + idempotencyKey: payload.idempotencyKey, + input: payload.input, + }), + }); + const input = (yield* Effect.orDie(decodePayload(payload.input))) as never; + const outcome = yield* definition.body(input, { id: runId }).pipe( + Effect.flatMap((value) => + definition.returns === ANY_JSON + ? untypedResult(value) + : encodeResult(value).pipe( + Effect.mapError( + (error) => + new Error( + `The run's result does not fit its returns: ${encodeFailure("the run's result", error, value)}`, + ), + ), + Effect.orDie, + ), + ), + Effect.map((value): typeof Outcome.Type => ({ + outcome: "completed", + value: (value ?? null) as Schema.Json, + })), + Effect.catchTags({ + WorkflowStop: (stopped) => + Effect.succeed({ + outcome: stopped.skipped === true ? "skipped" : "stopped", + value: null, + reason: stopped.reason, + }), + }), + // A step like any other: a cleanup that fails pauses the run, and resuming tries it again. + Effect.tap((ended) => + definition.onEnd === undefined + ? Effect.void + : stepAs( + claim(END_STEP, true), + END_STEP, + // A cleanup is safe to run again, and has nobody else to try it. + { returns: Schema.Void, retry: END_RETRY }, + definition.onEnd(input, { + id: runId, + outcome: ended.outcome, + reason: ended.reason, + }), + ), + ), + Effect.provideService( + RunContext, + RunContext.of({ + runId, + workflow: definition.name, + store, + names: new Set(), + forStep: (name) => forStep(store, keyValues, link, forge, runId, name), + inFlight: link.inFlight, + }), + ), + ); + yield* Activity.make({ + name: "run/end", + execute: Effect.asVoid( + store.runEnded(runId, outcome.outcome, outcome.reason ?? null, outcome.value), + ), + }); + yield* Activity.make({ + name: "run/told", + execute: Effect.suspend(() => link.current?.ended(runId) ?? Effect.void), + }); + return outcome; + }).pipe( + // A failing step marked the run paused itself. What reaches here otherwise is the body + // breaking outside a step: a duplicate name, a payload that no longer decodes. + Effect.tapCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.void + : Effect.flatMap(WorkflowStore.WorkflowStore, (store) => + store.runPaused(runId, text(Cause.squash(cause))), + ), + ), + ), + ); +}; diff --git a/apps/server/src/workflows/workflowAgent.ts b/apps/server/src/workflows/workflowAgent.ts new file mode 100644 index 0000000000000..03956086b03c8 --- /dev/null +++ b/apps/server/src/workflows/workflowAgent.ts @@ -0,0 +1,442 @@ +// The steps that involve someone else: an agent that returns data, and a person who answers. +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import { identity } from "effect/Function"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; + +import { checkOptions } from "./options.ts"; +import { stepReferences } from "./runReferences.ts"; +import { + claim, + type InRun, + journaled, + jsonSchemaOf, + type StepFailed, + text, + waitAs, +} from "./workflow.ts"; +import type { IssueAddress } from "./WorkflowForge.ts"; +import { + type AgentLaunch, + type AgentModel, + AgentResult, + AgentTurn, + WorkflowAgents, +} from "./WorkflowAgents.ts"; + +/** A thread an agent step ran in, to hand to a later step that should continue it. */ +export interface AgentThread { + readonly threadId: string; + /** The linked environment it is in. Absent for this one. */ + readonly environment?: string | undefined; +} + +const CORRECTIONS = 2; + +export interface AgentOptions extends AgentLaunch { + readonly brief: string; + /** The new thread's title. `: ` by default. */ + readonly title?: string; + readonly returns?: Schema.Codec; + readonly model?: AgentModel; + readonly project?: string; + readonly environment?: string; + readonly thread?: AgentThread; + /** + * The issue this job is about. Its thread shows the issue, and the issue's page lists the + * thread. Only for a thread on this server, not one in a linked `environment`. + */ + readonly issue?: IssueAddress; + /** How long the agent has. Past it the thread is stopped and the step has failed. */ + readonly timeout?: Duration.Input; + /** + * Let the agent end a turn without its `returns` and answer from a later one, as an agent does + * that waits to be woken: by a pull request it watches, by work it left running. Only when + * its thread has done nothing for this long is it asked for the result. Without it, a turn + * that ends without the result is asked at once. + */ + readonly quiet?: Duration.Input; +} + +type Attempt = + | { readonly outcome: "done"; readonly value: A; readonly thread: AgentThread } + | { readonly outcome: "failed"; readonly reason: string; readonly thread?: AgentThread }; + +const AGENT_OPTIONS = [ + "brief", + "returns", + "model", + "project", + "environment", + "thread", + "issue", + "timeout", + "quiet", + "title", + "workspace", + "runtimeMode", + "interactionMode", +]; + +// What only shapes a new thread: a continued one keeps its project, machine, model and modes. +const NEW_THREAD_OPTIONS = [ + "project", + "environment", + "model", + "title", + "workspace", + "runtimeMode", + "interactionMode", +] as const; + +const attempt = Effect.fn("workflow.agent")(function* ( + name: string, + options: AgentOptions, + /** What a failure does: pause the run at this step, or come back as the step's answer. */ + onFailure: "pause" | "return", +): Effect.fn.Return, StepFailed, InRun> { + checkOptions(`agent("${name}")`, options, AGENT_OPTIONS); + if (options.thread !== undefined) { + const shaping = NEW_THREAD_OPTIONS.filter((key) => options[key] !== undefined); + if (shaping.length > 0) { + return yield* Effect.die( + new Error( + `agent("${name}") continues \`thread\`, which keeps how it started. Drop ${shaping.map((key) => `\`${key}\``).join(", ")}.`, + ), + ); + } + } + const run = yield* claim(name); + const agents = yield* WorkflowAgents; + const outputSchema = + options.returns === undefined ? undefined : jsonSchemaOf(options.returns, true); + // Only a turn asked for a result can owe one from a later turn. + const quiet = + options.quiet === undefined || outputSchema === undefined + ? undefined + : Duration.fromInputUnsafe(options.quiet); + const outputCodec = + options.returns === undefined ? undefined : Schema.toCodecJson(options.returns); + const decodeOutput = outputCodec === undefined ? undefined : Schema.decodeEffect(outputCodec); + const threadOf = (turn: AgentTurn): AgentThread => ({ + threadId: turn.threadId, + ...(turn.environment === undefined ? {} : { environment: turn.environment }), + }); + const launch: AgentLaunch | undefined = + options.workspace === undefined && + options.runtimeMode === undefined && + options.interactionMode === undefined + ? undefined + : { + workspace: options.workspace, + runtimeMode: options.runtimeMode, + interactionMode: options.interactionMode, + }; + // What the agent's thread touches, its issue and the pull requests it links, is this step's. + const touches = stepReferences(run.store, run.runId, name); + const start = (key: string, prompt: string, thread: AgentThread | undefined) => + agents + .start({ + key: `${run.runId}/${name}/${key}`, + origin: { runId: run.runId, workflow: run.workflow, step: name }, + title: options.title ?? `${run.workflow}: ${name}`, + // Only the step's own `thread` is refused them; a correction on the thread it made is not. + launch: thread === undefined || thread === options.thread ? launch : undefined, + prompt, + outputSchema, + model: options.model, + project: options.project, + environment: thread === undefined ? options.environment : thread.environment, + thread: thread?.threadId, + issue: options.issue, + }) + .pipe( + Effect.provideContext(touches), + Effect.tap((turn) => + run.store.stepThread( + run.runId, + name, + turn.threadId, + turn.environment ?? null, + turn.turnId, + ), + ), + Effect.flatMap((turn) => + Effect.map(Clock.currentTimeMillis, (startedAt): AgentTurn => ({ ...turn, startedAt })), + ), + // No machine, no project, no link: for a step that takes failure as an answer, that is one. + onFailure === "pause" + ? identity + : Effect.catch((error) => + Effect.succeed({ threadId: "", turnId: "", failed: text(error) }), + ), + ); + const resultOf = (turn: AgentTurn, wait = { quiet }) => + agents + .result(turn, wait) + .pipe( + Effect.provideContext(touches), + onFailure === "pause" + ? identity + : Effect.catch((error) => + Effect.succeed({ ending: "failed", detail: text(error), reply: "" }), + ), + ); + /** The turn's result, or its thread stopped when the step's time is up. */ + const within = Effect.fn("workflow.agent.within")(function* ( + turn: AgentTurn, + startedAt: number | undefined, + ) { + if (options.timeout === undefined || startedAt === undefined) return yield* resultOf(turn); + const limit = Duration.fromInputUnsafe(options.timeout); + const left = startedAt + Duration.toMillis(limit) - (yield* Clock.currentTimeMillis); + const result = yield* resultOf(turn).pipe( + Effect.timeoutOption(Duration.millis(Math.max(0, left))), + ); + if (Option.isSome(result)) return result.value; + // A stop that still fails pauses the run unrecorded, so resuming tries the stop again. A step + // that returns its failure says the turn may still be running. + const stopping = agents + .interrupt({ ...threadOf(turn), turnId: turn.turnId }) + .pipe(Effect.retry({ times: 2 })); + const stop: "stopped" | "ended" | "failed" = yield* onFailure === "pause" + ? stopping + : stopping.pipe(Effect.orElseSucceed(() => "failed" as const)); + const late = `it was not done after ${Duration.format(limit)}`; + if (stop === "ended") { + // The turn ended before it could be stopped, maybe long ago, as a run that resumes late + // finds it. What it left is the answer when it is one. + const ended = yield* resultOf(turn, { quiet: undefined }); + if ( + ended.ending !== "completed" || + outputSchema === undefined || + ended.output !== undefined + ) { + return ended; + } + // Stopping the later turn it may answer from could stop someone else's. + return { + ending: "stopped" as const, + detail: `${late}: its turn ended without its result, and the agent may still be at work on its thread`, + reply: "", + }; + } + return { + ending: "stopped" as const, + detail: `${late}${stop === "stopped" ? "" : ", and its turn could not be stopped"}`, + reply: "", + }; + }); + const done = (round: number, produced: Schema.Json, said?: string) => + journaled( + run, + name, + `agent/${name}/${round}/done`, + Schema.Void, + Effect.all( + [ + run.store.stepEnded(run.runId, name, "completed", null), + run.store.stepResult(run.runId, name, produced, said), + run.store.runResumed(run.runId), + ], + { discard: true }, + ), + ); + + for (let round = 0; ; round++) { + let turn = yield* journaled( + run, + name, + `agent/${name}/${round}/start`, + AgentTurn, + Effect.andThen( + run.store.stepStarted(run.runId, name, "agent"), + start(`${round}`, options.brief, options.thread), + ), + ); + // Counted from the step's first turn, so corrections do not buy more time. + const startedAt = turn.startedAt; + let problem = turn.failed === undefined ? "" : `the agent could not be started: ${turn.failed}`; + let stopped = false; + let died = false; + for (let correction = 0; turn.failed === undefined; correction++) { + const result = yield* journaled( + run, + name, + `agent/${name}/${round}/result/${correction}`, + AgentResult, + Effect.andThen( + run.store.runStatus(run.runId, "waiting", `agent ${name}`), + within(turn, startedAt), + ), + ); + if (result.ending !== "completed") { + stopped = result.ending === "stopped"; + died = result.ending === "failed"; + problem = `the agent's turn was ${stopped ? "stopped" : "cut short"}: ${result.detail}`; + break; + } + if (decodeOutput === undefined) { + yield* done(round, result.reply); + return { outcome: "done", value: result.reply as A, thread: threadOf(turn) }; + } + // What the submitted result got wrong; undefined when nothing was submitted. + let misfit: string | undefined; + if (result.output !== undefined) { + const decoded = yield* Effect.result(decodeOutput(result.output)); + if (Result.isSuccess(decoded)) { + yield* done(round, result.output, result.reply); + return { outcome: "done", value: decoded.success, thread: threadOf(turn) }; + } + misfit = text(decoded.failure); + } + problem = + misfit === undefined + ? "the agent did not return a result: its turn ended with none accepted" + : `the agent's result did not fit: ${misfit}`; + if (correction >= CORRECTIONS) break; + // Back to the same thread: it has the context and only owes the result. + const corrected = yield* journaled( + run, + name, + `agent/${name}/${round}/correct/${correction}`, + AgentTurn, + start( + `${round}/correct/${correction}`, + misfit === undefined + ? "Your turn ended without an accepted result. Do not redo the work: call `t3_submit_output` now with the result of what you did." + : `The result you submitted does not fit: ${misfit}\nDo not redo the work: call \`t3_submit_output\` again with a corrected result.`, + threadOf(turn), + ), + ); + if (corrected.failed !== undefined) { + problem = `${problem}, and it could not be asked again: ${corrected.failed}`; + break; + } + turn = corrected; + } + // The turn may only be out of sight, not dead: it is stopped before another does its work again. + // A stop that does not get through pauses the run unrecorded, or gives up a step that returns. + let lingers = false; + if (died && turn.failed === undefined) { + const lost = turn; + lingers = !(yield* journaled( + run, + name, + `agent/${name}/${round}/stop`, + Schema.Boolean, + agents + .interrupt({ ...threadOf(lost), turnId: lost.turnId }) + .pipe( + Effect.retry({ times: 2 }), + Effect.as(true), + onFailure === "pause" ? identity : Effect.catch(() => Effect.succeed(false)), + ), + )); + if (lingers) problem = `${problem}; its turn could not be stopped`; + } + // A turn that died is not the job's fault the first time: once more, on a thread of its own, + // or on the same thread for a step that continues one, since only that thread has its project. + // Anything else is not tried again behind a person's back: one they stopped, one that never + // started, or one that did its work and would not give its result, which may have acted. + if (round % 2 === 0 && died && !lingers) continue; + if (onFailure === "return") { + yield* journaled( + run, + name, + `agent/${name}/${round}/failed`, + Schema.Void, + Effect.andThen( + run.store.stepEnded(run.runId, name, "failed", problem), + run.store.runResumed(run.runId), + ), + ); + return { + outcome: "failed", + reason: problem, + ...(turn.failed === undefined ? { thread: threadOf(turn) } : {}), + }; + } + // Fails the first time it is reached, which pauses the run here. Resuming the run reaches it + // again, and the next round starts. + yield* journaled( + run, + name, + `agent/${name}/${round}/pause`, + Schema.Void, + Effect.flatMap(run.store.mark(run.runId, `${name}/pause/${round}`), (arrivals) => + arrivals > 1 ? Effect.void : Effect.fail(problem), + ), + // Resuming starts the agent's job again from the top, which is a person's call. + true, + ); + } +}); + +const orPause = ( + name: string, + options: AgentOptions, +): Effect.Effect<{ readonly value: A; readonly thread: AgentThread }, never, InRun> => + Effect.flatMap(Effect.orDie(attempt(name, options, "pause")), (result) => + result.outcome === "done" + ? Effect.succeed({ value: result.value, thread: result.thread }) + : // `pause` never returns a failure: the step fails first, which pauses the run. + Effect.die(new Error(`Agent step ${name} failed without pausing: ${result.reason}`)), + ); + +/** + * An agent doing one job in a thread a person can open. It returns data checked against `returns`, + * or its last message without one. It starts a thread in `project`, in the linked `environment` + * when one is named, or continues `thread` where that is. Past `timeout` it is stopped. A turn + * that dies is tried once more, then the run pauses at this step. + */ +export const agent = Object.assign(orPause, { + /** + * For a workflow that decides for itself what a failed agent means: another model, another + * machine, or stop. An agent that could not be started, died twice, ran out of time or never + * gave its result comes back as `failed` with the reason, and the run goes on. + */ + try: ( + name: string, + options: AgentOptions, + ): Effect.Effect, never, InRun> => Effect.orDie(attempt(name, options, "return")), +}); + +/** + * A question a person answers with one of `choices`; `None` when the timeout passes first. The run + * holds nothing while it waits. `data` is the same facts as the title, for whatever lays the + * question out. + */ +export const ask = >( + name: string, + options: { + readonly title: string; + readonly choices: Choices; + readonly data?: Schema.Json; + readonly timeout?: Parameters[2]["timeout"]; + }, +): Effect.Effect< + Option.Option<{ readonly choice: Choices[number]; readonly reason?: string | undefined }>, + never, + InRun +> => + Effect.suspend(() => { + checkOptions(`ask("${name}")`, options, ["title", "choices", "data", "timeout"]); + return Effect.orDie( + waitAs("ask", name, { + returns: Schema.Struct({ + choice: Schema.Literals(options.choices), + reason: Schema.optional(Schema.String), + }), + timeout: options.timeout, + request: { + title: options.title, + choices: [...options.choices], + ...(options.data === undefined ? {} : { data: options.data }), + }, + }), + ); + }); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index b0d2fecec2ff4..806a045898ddc 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -8,8 +8,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { AuthAccessReadScope, + type AuthEnvironmentScope, AuthOrchestrationOperateScope, AuthOrchestrationReadScope, + type WorkflowRun, + type WorkflowStep, AuthSessionId, AuthSourceControlWriteScope, ORCHESTRATION_PROTOCOL_VERSION, @@ -130,6 +133,8 @@ import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolve import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; import * as ReviewService from "./review/ReviewService.ts"; import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; +import * as Workflows from "./workflows/Workflows.ts"; +import * as WorkflowRuntime from "./workflows/WorkflowRuntime.ts"; import * as SecretRequests from "./secrets/SecretRequests.ts"; import * as FeedbackStore from "./feedback/FeedbackStore.ts"; import * as GuestShareService from "./guest/GuestShareService.ts"; @@ -883,6 +888,8 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(ResourceTelemetry.ResourceTelemetry)({}), Layer.mock(ReviewService.ReviewService)({}), Layer.mock(ScheduledTasks.ScheduledTaskService)({}), + Workflows.layerDisabled, + Layer.mock(WorkflowRuntime.WorkflowDefinitions)({}), Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(FeedbackStore.FeedbackStore)({}), Layer.mock(SecretResolver.SecretResolver)({}), @@ -2645,3 +2652,161 @@ it.effect("ACP session RPCs list a thread missing its history and repair it on i ), ), ); + +const workflowTags = [ + WS_METHODS.workflowsGet, + WS_METHODS.workflowsAnswer, + WS_METHODS.workflowsResume, + WS_METHODS.workflowsCancel, +] as const; +const workflowRpcs = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RpcAuthorization.RPC_REQUIRED_SCOPES, + (typeof workflowTags)[number] + > => !(workflowTags as ReadonlyArray).includes(tag), + ), +); +const workflowRun: WorkflowRun = { + runId: "run-1", + workflow: "release", + version: 1, + title: "Release 1.2", + status: "paused", + detail: "build failed: exit 1", + result: null, + pauses: 1, + retired: false, + resumesAt: null, + parentRunId: null, + parentStep: null, + startedAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-01T00:01:00.000Z", + endedAt: null, +}; +const workflowStep: WorkflowStep = { + name: "build", + kind: "step", + status: "failed", + attempts: 2, + detail: "exit 1", + threadId: null, + environmentId: null, + result: null, + said: null, + startedAt: "2026-11-01T00:00:10.000Z", + endedAt: "2026-11-01T00:01:00.000Z", +}; + +/** A client for the workflow RPCs whose session holds `scopes`; `calls` records what reached the service. */ +const makeWorkflowClient = Effect.fn("test.makeWorkflowClient")(function* ( + scopes: ReadonlyArray, + calls: Array, +) { + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + Layer.mock(Workflows.Workflows)({ + get: (runId) => + runId === workflowRun.runId + ? Effect.succeed({ run: workflowRun, steps: [workflowStep], references: [] }) + : Effect.fail(new Workflows.WorkflowRunNotFoundError({ runId })), + answer: (runId, name, value) => + Effect.sync(() => calls.push({ answer: [runId, name], value })), + resume: (runId) => Effect.sync(() => calls.push({ resume: runId })), + cancel: (runId, reason) => Effect.sync(() => calls.push({ cancel: runId, reason })), + }), + ); + return yield* RpcTest.makeClient(workflowRpcs).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("workflow-test"), + subject: "workflow-test", + method: "browser-session-cookie", + scopes: [...scopes], + }, + {}, + yield* ServerBrowser.ServerBrowser, + () => Effect.void, + { secretReferences: true }, + ).pipe(Layer.provide(services), Layer.merge(RpcAuthorization.layer(scopes))), + ), + ); +}); +const layerWorkflowRpcTest = Layer.mergeAll( + Layer.fresh(layerConfigSources), + Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), + Layer.mock(ServerBrowser.ServerBrowser)({}), +); + +it.effect("workflow RPCs read a run and pass an answer, a resume and a cancel to the service", () => + Effect.gen(function* () { + const calls: Array = []; + const client = yield* makeWorkflowClient( + [AuthOrchestrationReadScope, AuthOrchestrationOperateScope], + calls, + ); + + assert.deepEqual(yield* client[WS_METHODS.workflowsGet]({ runId: "run-1" }), { + run: workflowRun, + steps: [workflowStep], + references: [], + }); + const missing = yield* client[WS_METHODS.workflowsGet]({ runId: "gone" }).pipe(Effect.flip); + assert.deepEqual( + [missing._tag, missing.message], + ["WorkflowRequestError", "Workflow run gone was not found."], + ); + + yield* client[WS_METHODS.workflowsAnswer]({ + runId: "run-1", + name: "approve", + choice: "yes", + reason: "Looks good", + }); + yield* client[WS_METHODS.workflowsAnswer]({ runId: "run-1", name: "approve", choice: "no" }); + yield* client[WS_METHODS.workflowsResume]({ runId: "run-1" }); + yield* client[WS_METHODS.workflowsCancel]({ runId: "run-1" }); + yield* client[WS_METHODS.workflowsCancel]({ runId: "run-1", reason: "Wrong branch" }); + + assert.deepEqual(calls, [ + { answer: ["run-1", "approve"], value: { choice: "yes", reason: "Looks good" } }, + { answer: ["run-1", "approve"], value: { choice: "no" } }, + { resume: "run-1" }, + { cancel: "run-1", reason: undefined }, + { cancel: "run-1", reason: "Wrong branch" }, + ]); + }).pipe(Effect.provide(layerWorkflowRpcTest), Effect.scoped), +); + +it.effect("a session that can only read sees a workflow run but cannot steer it", () => + Effect.gen(function* () { + const calls: Array = []; + const client = yield* makeWorkflowClient([AuthOrchestrationReadScope], calls); + + assert.equal((yield* client[WS_METHODS.workflowsGet]({ runId: "run-1" })).run.runId, "run-1"); + const refused = yield* Effect.all([ + client[WS_METHODS.workflowsAnswer]({ runId: "run-1", name: "approve", choice: "yes" }).pipe( + Effect.flip, + ), + client[WS_METHODS.workflowsResume]({ runId: "run-1" }).pipe(Effect.flip), + client[WS_METHODS.workflowsCancel]({ runId: "run-1" }).pipe(Effect.flip), + ]); + assert.deepEqual( + refused.map((error) => error._tag), + Array.from({ length: 3 }, () => "EnvironmentAuthorizationError"), + ); + assert.deepEqual(calls, []); + }).pipe(Effect.provide(layerWorkflowRpcTest), Effect.scoped), +); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 051f81c08f70b..ff783eeb57324 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -37,6 +37,7 @@ import { AuthProvidersManageScope, type AuthEnvironmentScope, type ScheduledTaskListResult, + WorkflowRequestError, AuthSessionId, ClientConnectionMethod, ClientDeviceType, @@ -131,6 +132,8 @@ import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts" import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts"; import * as DocumentText from "./provider/DocumentText.ts"; import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; +import * as Workflows from "./workflows/Workflows.ts"; +import * as WorkflowRuntime from "./workflows/WorkflowRuntime.ts"; import * as SecretRequests from "./secrets/SecretRequests.ts"; import * as FeedbackStore from "./feedback/FeedbackStore.ts"; import * as GuestShareService from "./guest/GuestShareService.ts"; @@ -1494,6 +1497,11 @@ export const layerWsRpc = ( const threadViewers = yield* ThreadViewers.ThreadViewers; const providerSessionManager = yield* ProviderSessionManager.ProviderSessionManagerV2; const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService; + const workflows = yield* Workflows.Workflows; + const workflowDefinitions = yield* WorkflowRuntime.WorkflowDefinitions; + // The service's messages are built from its own attributes, so they are safe to send. + const toWorkflowRequestError = (error: Workflows.WorkflowError) => + new WorkflowRequestError({ message: error.message }); const secretRequests = yield* SecretRequests.SecretRequests; const feedbackStore = yield* FeedbackStore.FeedbackStore; const guestShares = yield* GuestShareService.GuestShareService; @@ -2363,6 +2371,25 @@ export const layerWsRpc = ( ), [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: (input) => providerSessionManager.subscribePromptSuggestion(input.threadId), + [WS_METHODS.workflowsSubscribe]: (_input) => workflows.watch, + [WS_METHODS.workflowsCounts]: (_input) => workflows.counts, + [WS_METHODS.workflowsGet]: (input) => + workflows.get(input.runId).pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsAnswer]: (input) => + workflows + .answer(input.runId, input.name, { + choice: input.choice, + ...(input.reason === undefined ? {} : { reason: input.reason }), + }) + .pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsResume]: (input) => + workflows.resume(input.runId).pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsCancel]: (input) => + workflows.cancel(input.runId, input.reason).pipe(Effect.mapError(toWorkflowRequestError)), + [WS_METHODS.workflowsGetDefinition]: (_input) => workflowDefinitions.read, + [WS_METHODS.workflowsSaveDefinition]: (input) => + workflowDefinitions.save(input.name, input.source), + [WS_METHODS.workflowsDeleteDefinition]: (input) => workflowDefinitions.remove(input.name), [WS_METHODS.scheduledTasksSubscribe]: (_input) => scheduledTasks.subscribeList().pipe(Stream.map(withVisibleWebhookUrls)), [WS_METHODS.scheduledTasksUpsert]: (input) => scheduledTasks.upsert(input), diff --git a/docs/internals/workflows.md b/docs/internals/workflows.md new file mode 100644 index 0000000000000..5f9b965c082b5 --- /dev/null +++ b/docs/internals/workflows.md @@ -0,0 +1,178 @@ +# Workflows + +A workflow run is a journaled function: a step's result is stored once it succeeds, a restart +replays the run to where it was, and a run sleeps on a wait until something outside signals it. A +step's body can run more than once, after a failure it retries or a crash mid-step, so what it does +outside the run must be safe to repeat. The code is in +[`apps/server/src/workflows`](../../apps/server/src/workflows). This page holds what is not +obvious from it. + +## Why it is shaped this way + +**The engine is Effect's, in the server's database.** `effect/workflow` on one runner journals +runs in tables it creates itself. Runs, steps, waits and kept signals are rows of ours beside them, +not orchestration events: the event store knows projects and threads, a run is neither, and its +journal is the engine's to read. Clients follow runs the way they follow scheduled tasks, by a +list that is sent again when something changes. + +**Off until turned on, then until something is defined.** Workflows are a Labs setting, +`workflowsEnabled`, and the runtime's lifetime follows it: while it is off no file is loaded, no +engine runs, and every request is refused with how to turn it on; turning it off closes the +runtime the way a restart does, so runs wait in the database for it to come back. Once on, the +server registers what the files in the home's `workflows` folder define. While they define +nothing and no runs are kept, the `Workflows` service is the disabled one and the engine's modules +are never imported ([`WorkflowRuntime.ts`](../../apps/server/src/workflows/WorkflowRuntime.ts)). +Keep it that way: anything a light module imports from `effect/workflow` or `effect/cluster` is +paid for by every server and CLI start. + +**A step failure pauses the run.** The alternative, ending the run, loses everything done so far to +a dependency that is back in a minute. Resuming runs the failed step again and nothing before it. +Effect's engine suspends the body when a step fails, so no handler in the body ever sees the +error: the primitives type their error as `never`, and `step.try` and `agent.try` return a failure +as data instead. A step runs once unless it asks for retries, since a lost reply to a post or a +merge would otherwise do it again. A run paused by an agent that gave up waits for a person rather +than `resumeAfter`: resuming starts the agent's whole job again. `stop` is the workflow's own +decision to end, and is not a failure. + +**An agent step is a thread.** It completes when the agent submits a result the server checked +against the step's schema, not when a turn ends, and a person can open the thread and talk to it. +See [typed results](../orchestration-v2/orchestrator-mcp-server.md#t3_submit_output). + +**A run stays where it started; its agents need not.** An agent step that names a linked +environment runs its thread there through that environment's own thread tools, with the step's key +as the request id, so a replay finds the thread it already started. The run is no agent and has no +modes to pass on, so the link's access is the only ceiling on what it starts there. Making and +linking machines is the workflow author's own code in a `step`; nothing here knows how. + +**An agent step's thread says which run it belongs to.** The thread is created with the run, the +workflow and the step it is, and its lineage marks it as a workflow step, so the default lists +of threads leave it out the way they leave out subagents (a list that asks for subagents gets +them too): a run can have dozens, and they are read +through the run. Only the server may set this, as with a link's origin; over a link the launch +tool carries it and it is kept only for a link session. + +**An invoked run is a run of its own.** `invoke` starts it from a step with this run as its +parent and then waits like any `wait`; the engine signals that wait when the child ends, however +it ends, so a child that finished before the parent got to its wait is not missed. A key names +one run with one parent, so invoking under a key something else started is refused instead of +waiting for a signal that would never come. + +**The store is for inside a step.** Its values change between replays, so the body must not read +it; `step` and `onEnd` hand their code the store, a way to signal, and a way to start, find and +cancel runs, and nothing else may use them. A step's signals are numbered from the step's name +and where each goes, so a retried step that sends the same signal again sends no new one, and +one that sends somewhere new is not taken for what an earlier try sent. + +**A run keeps what it touched.** A reference is a `kind`, a `key` naming the thing within its +kind, and an `address` that only that kind's client reads, so a new kind is a new caller of +[`noteReference`](../../apps/server/src/workflows/runReferences.ts) and nothing more. It is called +from inside a step: by the forge helpers, by an agent step's thread for its `issue` and the pull +requests linked to it while the step ran, and by the engine's look at a pull request a wait is +on. An issue or pull request trigger notes its item with no step. There is one row per run, kind +and key, so a retry or replay that touches the same thing adds nothing. It is only for a person +to read: a failure to keep it is logged and never fails a step. Only a run's detail carries +references, not the list that is sent again on every change. + +**A thread owes its result across turns.** An agent that waits for something ends its turn and is +woken later, in a turn nobody asked a result of. A submission from such a turn goes to the newest +turn that was asked and has not answered, so the result lands on the turn the step started, and a +wait with `untilOutput` holds past that turn's end for it. The `quiet` option of an agent step is +that wait with a limit: quiet is counted from the thread's last turn, and when it passes the +step asks for the result as it would have at once without the option. + +**A failed agent is an answer only when the workflow asks for that.** `agent.try` journals the same +turns as `agent` and differs at the end: it marks the step failed and returns, where `agent` +fails the step and pauses the run. A start that failed is journaled as a turn without ids, so a +replay does not try the start again. + +**`onEnd` gets the payload and the run's id, not the body's values.** A cancelled run's body is +gone, so its cleanup runs outside the engine and has only what the run was started with. Inside +the engine `onEnd` is an ordinary last step. + +**Definitions reload by replacing the engine.** The engine is built from a fixed set of +definitions, so a changed folder closes it and builds a new one on the same database, which is +what a restart does; runs come through it as they come through a restart. The service the rest +of the server holds forwards to whichever engine is current, and callers during the swap wait +for the new one. With nothing defined but runs kept, an engine with nothing registered and no +cluster runner serves their history. + +**Each file keeps its last good version.** A file that stops loading does not take its workflows +down, and does not hold back the other files. A change that fails a check across files, a +workflow defined twice or a version dropped under unfinished runs, is held back the same way: +the changed file keeps its last good version (a new one stays out, and of two new files the +first by name wins), and the rest of the change is taken. A held change is tried again on every +reload, since the runs that held it may have ended. + +**The API is globals, so files load one at a time.** `T3.workflow` registers with the load in +progress, and the globals are the process's. A file is loaded under a new address each time, +because Node keeps a module by its address; modules a file imports keep theirs, so they are not +reloaded, and a workflow one of them defines registers only the first time. That is why shared +code belongs in a subfolder and definitions in the files themselves. Saving from a client +verifies a copy beside the real file first, so its imports resolve the same way. + +## Traps + +**A workflow body is replayed.** After a restart or a wait, the body runs again from the top and +each journaled action returns what it stored. Anything that touches the world goes through +a durable activity: `journaled` for `step` and `agent`, and a pair of open and close activities +around a `DurableDeferred` for `wait`, so a fix to one is not a fix to the other. Code between steps must give the same +answer on every pass: no clock, no randomness, no reads. + +**Names are the journal's keys.** A step's result and its row in the step list are both kept by +name, so two steps with one name would share a result. `claim` rejects that, across kinds. A change +to the order of steps, or to the shape a step returns, is a new `version` of the workflow; keep the +old one registered until its runs have ended. A run whose version is gone shows as `retired`. + +**The engine reads integers as BigInt, and nothing else may.** It stores 64-bit ids, which +`node:sqlite` only reads when asked for BigInts, so the engine's fibers and every call into it run +with `SqlClient.SafeIntegers` on. That setting is inherited by whatever those fibers call. +`journaled` turns it off again around a step's own code, and the sweep turns it off around the +turn stops and the `onEnd` it runs for a cancelled run; without that, a step that reads a project +gets rows it cannot decode. + +**The pause is recorded in two places, a moment apart.** A failing step marks its run paused from +inside the engine, just before the engine records the failure. `resume` waits for the engine's +record, or it would resume a run the engine does not yet consider stopped and do nothing. The sweep +puts back a run that still says it goes on while the engine holds it as failed, held for a person if +it was, and leaves alone one a resume is under way for. + +**A paused run is not woken.** The engine replays a run for any wake, and the replay runs the failed +step again as a resume would, though nobody resumed it. A signal, timeout or child's end for a +paused run's other wait is only claimed; the resume sends the wakes its run has claimed. + +**A step in flight cannot be interrupted.** The engine runs a step's body to its end. `cancel` +therefore ends the run's row first, so nothing the step still does is recorded as the outcome, and +stops the step's own turn, which is what makes a long agent step return. Only that turn: someone +else's turn on the same thread is left alone. The cancelled run's `onEnd` waits for the steps still +running in this process, or a cleanup would take away what a step is still making. A version stays +required while a cancelled run's cleanup still has tries left, since only that version can run it; +one that has used them up stays failed on the run for a person to see. + +**A key is one run whatever the version.** The engine's own run id hashes `name@version` with the +key, so after a version bump the same key would be a new run: a trigger that sees its newest issue +again, or a webhook retry, would start the work twice. The key is unique per workflow, so the row +that takes it is the run; a start that finds a row the engine never got executes it. + +**An ended run's journal is deleted.** The engine keeps every request and reply of a run, which +grew one large deployment's database by gigabytes in two weeks, so the sweep clears a run's engine +messages (its sleeps included) an hour after it ends with no step still going. Our rows stay, and +they are all that shows a run. Nothing may hand an ended run to the engine again: with no journal +it would run the body from the start, so a start for an ended run's key returns that run as it is. + +**One signal wakes one wait.** A wait is taken by the first signal for it; a second signal on the +same channel is for the next run that waits on that channel, and is kept until one does or its `ttl` runs +out (seven days by default), after which it is gone. A signal's id is remembered for seven days +once delivered, or until its `ttl` if that is later, so a sender's retry within that time is not a +second signal. + +**A wait checks a signal twice.** The engine checks a value against the wait's JSON Schema before +it wakes the wait, but only the run has the wait's codec, and a codec can refuse what its JSON +Schema allows (a number read from text). A value the codec refuses was not for the wait: the wait +opens again under a fresh wake and says why, rather than failing on every replay. Kept mail on a +channel that a wait cannot read is left for another wait there; mail addressed to that wait is +dropped. + +**`signalAll` keeps nothing.** It wakes the waits open on a channel now and is not kept for one that +opens later: a kept broadcast would wake whichever single run waited next, days on. A run that +holds for a condition therefore reads the condition in a step and waits with a timeout, so one +that began to wait just after the broadcast looks again. diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 71d8845e74c75..8167049a87817 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -479,6 +479,13 @@ status and does not cancel work. `output` carries what the run submitted against its `outputSchema`; with `untilOutput`, a completed run that has not submitted yet is waited on until it has. +### `t3_workflow` + +Starts, lists, reads, signals, resumes and cancels [workflow runs](../internals/workflows.md), and +lists the questions runs ask a person. It is advertised to clients outside a thread only, such as +the `t3 workflow` CLI, so it costs no thread any context; an agent in a thread drives workflows +through that CLI. `start` is idempotent on `idempotencyKey` and `signal` on `signalId`. + ### `t3_thread_interrupt` Interrupts a selected active run through the normal V2 `run.interrupt` command. diff --git a/docs/user/managed-policy.md b/docs/user/managed-policy.md index 32e6f47da4693..a8583b923f3c1 100644 --- a/docs/user/managed-policy.md +++ b/docs/user/managed-policy.md @@ -249,6 +249,7 @@ so restart T3 Code after that. - `webhookTasks: false`: scheduled tasks cannot use webhook triggers. Existing webhook tasks stay but do not run, and cannot be turned back on. Users can still edit or delete them. + Workflow webhooks are refused too. - `browserCookieImport: false`: users cannot import cookies from another browser into T3 Code's browser. - `previewTunnel: false`: other devices cannot load this machine's `localhost` pages themselves. diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 8bc6b50d24def..8a2f790905f75 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -139,7 +139,11 @@ A bot that supports MCP Events (`io.modelcontextprotocol/events`) can learn when something happens without reading threads over and over: a turn ended, an agent waits on a person, a guest asked something, a watched pull request woke its thread. Each of these is an event type it can poll or stream, narrowed to -projects or threads. The environment keeps its latest 1,000 milestones in +projects or threads. [Workflow runs](workflows.md) have their own event types, +narrowed to workflows or runs: a run started, paused, resumed or ended, and a +question it asks was raised or settled. Runs that another run started are left +out unless asked for, as subagent threads are, and narrowing thread events to a +run also picks out the threads that are its agent steps. The environment keeps its latest 1,000 milestones in memory, so a bot that was away longer, or reconnects after a restart, is told some may be missing and should reread the threads it cares about. diff --git a/evals/README.md b/evals/README.md index 8cfb697373c31..d2ecb73dd71be 100644 --- a/evals/README.md +++ b/evals/README.md @@ -4,13 +4,14 @@ An eval runs a real model against T3 Code's real text or code and scores what th Write or run an eval when a change affects what a model sees or does: agent instructions, MCP tool descriptions and schemas, tool results, generated titles, or the guidance an agent gets for a feature such as Device Manager. -| Eval | Measures | -| ------------------------------- | ---------------------------------------------------------------------------------------------------- | -| [mcp-tool-use](mcp-tool-use/) | Whether agents use T3's MCP tools correctly, including device routing and recovery, in fake threads. | -| [thread-titles](thread-titles/) | Whether generated thread titles name the right subject. | -| [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | -| [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | -| [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | +| Eval | Measures | +| ----------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| [mcp-tool-use](mcp-tool-use/) | Whether agents use T3's MCP tools correctly, including device routing and recovery, in fake threads. | +| [thread-titles](thread-titles/) | Whether generated thread titles name the right subject. | +| [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | +| [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | +| [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | +| [workflow-authoring](workflow-authoring/) | Whether a model writes a working workflow file from the `t3-workflows` skill alone. | ## Run an eval diff --git a/evals/package.json b/evals/package.json index 245448ac4021c..21f022a680466 100644 --- a/evals/package.json +++ b/evals/package.json @@ -11,6 +11,7 @@ "pr-content": "node --env-file-if-exists=../.env pr-content/run.ts", "voice-cleanup": "node --env-file-if-exists=../.env voice-cleanup/run.ts", "test-signal": "node --env-file-if-exists=../.env test-signal/run.ts", + "workflow-authoring": "node --env-file-if-exists=../.env workflow-authoring/run.ts", "typecheck": "effect-tsgo tsrs --noEmit", "test": "vp test run --config ../vite.config.ts --dir ." }, diff --git a/evals/workflow-authoring/README.md b/evals/workflow-authoring/README.md new file mode 100644 index 0000000000000..f93fb582e6933 --- /dev/null +++ b/evals/workflow-authoring/README.md @@ -0,0 +1,36 @@ +# Workflow authoring + +Checks that a model can write a working workflow definitions file from the +[`t3-workflows` skill](../../skills/t3-workflows/SKILL.md) alone. Run it when the skill, the author +API, or the way the server loads a definitions file changes. + +The model gets the skill's body and one task, and replies with a file. The grader loads that file +with the server's loader, registers it in the real engine on a throwaway database, and drives it +with a stand-in for agents: it starts runs, delivers webhooks, answers questions, restarts the +engine, and checks how each run ends. Nothing is judged by reading the code. + +## Run + +```sh +cd evals +pnpm workflow-authoring --out runs/baseline +pnpm workflow-authoring --out runs/shorter --skill /path/to/variant.md --baseline runs/baseline/results.ndjson +``` + +- Models go through the `vibeproxy` CLIProxyAPI provider in `~/.codex/config.toml`. Default models: + `gpt-6.1-terra` and `gpt-6-luna`. Pass `--model` once per model to change them. +- Flags: `--skill ` (a variant of the skill), `--case ` (repeatable), `--samples ` + (default 3), `--reasoning ` (default `low`), `--baseline `. +- Each answer is saved next to the results as `...ts`, and `summary.md` lists + every problem the grader found. +- Cost: proxy quota only, about 5,000 tokens per sample. + +The answers are code the grader runs. They come from a model that saw only the skill and the task, +but run this on a machine where that is acceptable. + +## Add a case + +Add an entry to `cases.ts`: the task as a person would give it, and one or more scenarios. A +scenario says what the stand-in agent answers and returns the problems it finds after driving the +file's workflows; none is a pass. Put a reference answer in `fixtures/.ts`, which +`run.test.ts` requires to pass, and a wrong answer when the case exists to catch one mistake. diff --git a/evals/workflow-authoring/cases.ts b/evals/workflow-authoring/cases.ts new file mode 100644 index 0000000000000..9353dd4d7c12d --- /dev/null +++ b/evals/workflow-authoring/cases.ts @@ -0,0 +1,270 @@ +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type { Case, World } from "./grade.ts"; + +const defined = (world: World, name: string) => + world.definitions.find((definition) => definition.name === name); +const missing = (name: string) => [`No workflow named ${name} is defined.`]; + +const todos = [ + { file: "src/a.ts", line: 3, text: "handle the empty list" }, + { file: "src/b.ts", line: 9, text: "remove after the migration" }, +]; + +const SUCCEEDED = JSON.stringify({ status: "succeeded", service: "billing" }); +const FAILED = JSON.stringify({ status: "failed", service: "checkout-api" }); + +export const cases: ReadonlyArray = [ + { + id: "scheduled-agent-then-approval", + source: + "The dependency report in the skill: a schedule, typed agent data, a question, a continued thread.", + task: [ + "Write a workflow named `todo-sweep` that runs every weekday (Monday to Friday) at 09:00.", + "An agent in the project with id `proj-1` lists the TODO comments in the repository as data shaped `{ todos: [{ file: string, line: number, text: string }] }`, without changing files.", + "If there are none, the run ends there; that is not a failure.", + "Otherwise a person is asked whether to fix them, with the choices `fix` and `skip`, and the run waits at most one day for the answer.", + "On `fix`, the same agent thread fixes them. On `skip` or no answer, the run ends.", + ].join("\n"), + scenarios: [ + { + name: "nothing to do", + agent: () => ({ output: { todos: [] } }), + check: (world) => + world.server( + Effect.fn(function* (workflows) { + const definition = defined(world, "todo-sweep"); + if (definition === undefined) return missing("todo-sweep"); + const problems: Array = []; + const schedule = definition.triggers.flatMap((trigger) => + trigger.kind === "schedule" && trigger.schedule.type === "fixed_time" + ? [trigger.schedule] + : [], + )[0]; + if (schedule === undefined) { + problems.push("It has no time-of-day trigger."); + } else { + if (!/^0?9:00$/.test(schedule.timeOfDay)) { + problems.push(`It runs at ${schedule.timeOfDay}, not 09:00.`); + } + if ([...(schedule.weekdays ?? [])].toSorted().join() !== "1,2,3,4,5") { + problems.push("It does not run on exactly Monday to Friday."); + } + } + const { runId } = yield* workflows.start( + "todo-sweep", + { scheduledAt: "2026-01-05T09:00:00.000Z" }, + { idempotencyKey: "a" }, + ); + const ended = yield* world.reaches( + workflows, + runId, + "stopped", + "completed", + "paused", + ); + if (Option.isNone(ended)) return [...problems, "The run never ended."]; + if (ended.value.status === "paused") { + problems.push(`The run paused: ${ended.value.detail}`); + } + if (world.turns.length !== 1) { + problems.push(`It asked for ${world.turns.length} agent turns, not 1.`); + } + if (world.turns[0]?.project !== "proj-1") { + problems.push("The agent did not start in proj-1."); + } + if ((yield* workflows.questions).length > 0) { + problems.push("It asked a person although there was nothing to fix."); + } + return problems; + }), + ), + }, + { + name: "approved", + agent: (turn) => + turn.outputSchema === undefined ? { reply: "Fixed." } : { output: { todos } }, + check: (world) => + world.server( + Effect.fn(function* (workflows) { + if (defined(world, "todo-sweep") === undefined) return missing("todo-sweep"); + const { runId } = yield* workflows.start( + "todo-sweep", + { scheduledAt: "2026-01-05T09:00:00.000Z" }, + { idempotencyKey: "b" }, + ); + const question = yield* world.asks(workflows, runId); + if (Option.isNone(question)) return ["It did not ask a person whether to fix them."]; + yield* workflows.signal( + { runId, wait: question.value }, + { choice: "fix" }, + { id: "answer-1" }, + ); + const ended = yield* world.reaches( + workflows, + runId, + "completed", + "paused", + "stopped", + ); + if (Option.isNone(ended) || ended.value.status !== "completed") { + return [ + `After "fix" the run did not complete: ${Option.getOrUndefined(ended)?.status ?? "never ended"}`, + ]; + } + const [first, second] = world.turns; + if (world.turns.length !== 2) { + return [`It asked for ${world.turns.length} agent turns, not 2.`]; + } + return second?.thread === `thread-${first?.key}` + ? [] + : ["The fix did not continue the first agent's thread."]; + }), + ), + }, + ], + }, + { + id: "webhook-filter-and-dedupe", + source: + "Scheduled-task webhooks keep filters and replay keys as settings; a workflow has to write both.", + task: [ + "Write a workflow named `deploy-watch` started by a webhook named `deploys`.", + 'The request body is JSON shaped `{ "status": string, "service": string }`.', + "A sender may deliver the same event more than once; the header `x-delivery-id` identifies an event, and one event must be one run.", + "Anything whose status is not `failed` is ignored: the run ends there, which is not a failure.", + "For a failed deploy, an agent in the project with id `proj-1` investigates. Its brief must name the service.", + ].join("\n"), + scenarios: [ + { + name: "deliveries", + agent: () => ({ reply: "The migration timed out." }), + check: (world) => + world.server( + Effect.fn(function* (workflows) { + if (defined(world, "deploy-watch") === undefined) return missing("deploy-watch"); + const hook = (yield* workflows.hooks).find((entry) => entry.name === "deploys"); + if (hook === undefined) return ["It has no webhook named deploys."]; + const [hookId, token] = hook.path.split("/").slice(-2).map(decodeURIComponent); + const deliver = (delivery: string, body: string) => + workflows + .deliver({ + hookId: hookId!, + token: token!, + request: { + method: "POST", + headers: { "content-type": "application/json", "x-delivery-id": delivery }, + query: "", + body, + }, + }) + .pipe(Effect.map(Option.getOrThrow)); + const problems: Array = []; + + const fine = yield* deliver("d1", SUCCEEDED); + const ignored = yield* world.reaches( + workflows, + fine.runId, + "skipped", + "stopped", + "completed", + "paused", + ); + if (Option.isNone(ignored) || ignored.value.status === "paused") { + problems.push("A deploy that did not fail left its run paused or unfinished."); + } + if (world.turns.length > 0) + problems.push("It started an agent for a deploy that did not fail."); + + const failed = yield* deliver("d2", FAILED); + const again = yield* deliver("d2", FAILED); + if (again.runId !== failed.runId) + problems.push("A redelivered event started a second run."); + const done = yield* world.reaches( + workflows, + failed.runId, + "completed", + "paused", + "stopped", + ); + if (Option.isNone(done) || done.value.status !== "completed") { + problems.push( + `A failed deploy's run did not complete: ${Option.getOrUndefined(done)?.detail ?? "never ended"}`, + ); + } + const turn = world.turns[0]; + if (turn === undefined) + return [...problems, "It started no agent for a failed deploy."]; + if (turn.project !== "proj-1") problems.push("The agent did not start in proj-1."); + if (!turn.prompt.includes("checkout-api")) + problems.push("The brief does not name the service."); + return problems; + }), + ), + }, + ], + }, + { + id: "replay-keeps-what-it-read", + source: + "The replay rule: the body runs again after a wait, so a value read from the world outside a step changes under the run.", + task: [ + "Write a workflow named `stamp`, started by hand with the payload `{ label: string }`, that returns a string.", + "It reads the current time in milliseconds since the epoch, then waits for a signal named `go` whose value is a string.", + "When the signal arrives it returns `( + use: (workflows: Workflows.Workflows["Service"]) => Effect.Effect, + ) => Effect.Effect; + /** The run once it is in one of these states, or nothing after ten seconds. */ + readonly reaches: ( + workflows: Workflows.Workflows["Service"], + runId: string, + ...statuses: ReadonlyArray + ) => Effect.Effect>; + /** The name of the question the run asks a person, or nothing after ten seconds. */ + readonly asks: ( + workflows: Workflows.Workflows["Service"], + runId: string, + ) => Effect.Effect>; +} + +export interface Case { + readonly id: string; + readonly source: string; + /** What the model is asked to write. */ + readonly task: string; + /** What a fake agent answers. Each scenario of the case sets its own. */ + readonly scenarios: ReadonlyArray<{ + readonly name: string; + readonly agent: (turn: AgentTurnInput) => Partial; + /** The problems found. None is a pass. */ + readonly check: (world: World) => Effect.Effect, Workflows.WorkflowError>; + }>; +} + +// Across every grade in the process: a load under an address used before would get that module. +let lifetimes = 0; + +const world = Effect.fn("gradeWorkflow.world")(function* ( + file: string, + definitions: ReadonlyArray, + agent: (turn: AgentTurnInput) => Partial, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-eval-" }); + const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") }); + yield* Effect.provide(WorkflowsMigration, database); + const turns: Array = []; + const asked = new Map(); + const agents = WorkflowAgents.of({ + start: Effect.fn("gradeWorkflow.agents.start")(function* (input) { + if (!asked.has(input.key)) { + asked.set(input.key, input); + turns.push(input); + } + return yield* Effect.succeed({ + threadId: input.thread ?? `thread-${input.key}`, + turnId: input.key, + }); + }), + result: Effect.fn("gradeWorkflow.agents.result")(function* (turn) { + return yield* Effect.succeed({ + ending: "completed" as const, + detail: "", + reply: "", + ...agent(asked.get(turn.turnId)!), + }); + }), + // Every turn here has already completed, so there is nothing to stop. + interrupt: Effect.fn("gradeWorkflow.agents.interrupt")(function* () { + return yield* Effect.succeed("ended" as const); + }), + }); + const engine = (loaded: ReadonlyArray) => + WorkflowEngine.layer(loaded).pipe( + Layer.provide(Layer.succeed(WorkflowAgents, agents)), + Layer.provide(database), + Layer.provide(NodeCrypto.layer), + Layer.orDie, + ); + return { + definitions, + turns, + server: (use) => + loadDefinitions(file, ++lifetimes).pipe( + Effect.orDie, + Effect.provideService(Path.Path, path), + Effect.flatMap((loaded) => + Effect.scoped(Effect.provide(Effect.flatMap(Workflows.Workflows, use), engine(loaded))), + ), + ), + reaches: (workflows, runId, ...statuses) => + workflows + .waitFor(runId, (run) => statuses.includes(run.status)) + .pipe(Effect.timeoutOption("10 seconds")), + asks: (workflows, runId) => + workflows.watch.pipe( + Stream.filterMap((snapshot) => { + const question = snapshot.questions.find((asked) => asked.runId === runId); + return question === undefined ? Result.failVoid : Result.succeed(question.name); + }), + Stream.runHead, + Effect.timeoutOption("10 seconds"), + Effect.map(Option.flatten), + ), + } satisfies World; +}); + +const problemsWith = Effect.fn("gradeWorkflow.problemsWith")(function* (file: string, entry: Case) { + const loaded = yield* Effect.result(loadDefinitions(file)); + if (loaded._tag === "Failure") { + return [`The file does not load: ${String(loaded.failure.cause)}`]; + } + const problems: Array = []; + for (const scenario of entry.scenarios) { + const found = yield* world(file, loaded.success, scenario.agent).pipe( + Effect.flatMap(scenario.check), + Effect.scoped, + Effect.catch((error) => Effect.succeed([error.message])), + Effect.catchDefect((defect) => Effect.succeed([`It crashed: ${String(defect)}`])), + ); + problems.push(...found.map((problem) => `${scenario.name}: ${problem}`)); + } + return problems; +}); + +/** The problems with the workflow file at `file` as an answer to `entry`. None is a pass. */ +export const grade = (file: string, entry: Case): Promise> => + Effect.runPromise(Effect.provide(problemsWith(file, entry), NodeServices.layer)); diff --git a/evals/workflow-authoring/run.test.ts b/evals/workflow-authoring/run.test.ts new file mode 100644 index 0000000000000..104d56d38d77b --- /dev/null +++ b/evals/workflow-authoring/run.test.ts @@ -0,0 +1,37 @@ +// A test of an eval script, which works on plain file paths. +// @effect-diagnostics nodeBuiltinImport:off +import * as NodePath from "node:path"; + +import { expect, it } from "vite-plus/test"; + +import { cases } from "./cases.ts"; +import { grade } from "./grade.ts"; + +const fixture = (name: string) => NodePath.join(import.meta.dirname, "fixtures", `${name}.ts`); +const entry = (id: string) => cases.find((candidate) => candidate.id === id)!; + +it.each(cases.map((candidate) => candidate.id))("a correct answer to %s passes", async (id) => { + expect(await grade(fixture(id), entry(id))).toEqual([]); +}); + +it("a body that reads the clock outside a step fails the replay case", async () => { + expect( + await grade(fixture("replay-reads-outside-a-step"), entry("replay-keeps-what-it-read")), + ).toEqual([ + "restart while waiting: The time it returned was read again after the restart, not kept from the start.", + ]); +}); + +it("a body that keeps the time in a module variable fails the replay case", async () => { + expect( + await grade(fixture("replay-keeps-in-a-module"), entry("replay-keeps-what-it-read")), + ).toEqual([ + "restart while waiting: The time it returned was read again after the restart, not kept from the start.", + ]); +}); + +it("an answer to another task fails with the reason", async () => { + expect( + await grade(fixture("webhook-filter-and-dedupe"), entry("replay-keeps-what-it-read")), + ).toEqual(["restart while waiting: No workflow named stamp is defined."]); +}); diff --git a/evals/workflow-authoring/run.ts b/evals/workflow-authoring/run.ts new file mode 100644 index 0000000000000..2e2c66f7a5fff --- /dev/null +++ b/evals/workflow-authoring/run.ts @@ -0,0 +1,179 @@ +#!/usr/bin/env node +// An eval script, not server code: it reads and writes files directly. +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; +import * as NodeUtil from "node:util"; +import * as Effect from "effect/Effect"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; + +import { proxyConfig } from "../shared/proxy.ts"; +import { cases } from "./cases.ts"; +import { type Case, grade } from "./grade.ts"; + +const { values } = NodeUtil.parseArgs({ + options: { + out: { type: "string" }, + model: { type: "string", multiple: true }, + skill: { type: "string" }, + case: { type: "string", multiple: true }, + samples: { type: "string", default: "3" }, + reasoning: { type: "string", default: "low" }, + baseline: { type: "string" }, + }, +}); +if (!values.out) throw new Error("Use --out [--model ] [--skill ]."); +const outDirectory = values.out; +const models = values.model ?? ["gpt-6.1-terra", "gpt-6-luna"]; +const skillFile = + values.skill ?? NodePath.resolve(import.meta.dirname, "../../skills/t3-workflows/SKILL.md"); +// An agent is given the skill's body; the front matter only decides when it loads. +const skill = NodeFS.readFileSync(skillFile, "utf8") + .replace(/^---\n[\s\S]*?\n---\n/, "") + .trim(); +const selected = values.case ? cases.filter((entry) => values.case!.includes(entry.id)) : cases; +const proxy = proxyConfig(); + +const Row = Schema.Struct({ + model: Schema.String, + case: Schema.String, + sample: Schema.Number, + problems: Schema.Array(Schema.String), + tokens: Schema.Number, +}); +const encodeRow = Schema.encodeSync(Schema.fromJsonString(Row)); +const decodeRow = Schema.decodeUnknownSync(Schema.fromJsonString(Row)); +const decodeResponse = Schema.decodeUnknownSync( + Schema.fromJsonString( + Schema.Struct({ + output: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), + usage: Schema.optional(Schema.Struct({ total_tokens: Schema.optional(Schema.Number) })), + }), + ), +); + +const instructions = [ + "You write workflow definitions files for T3 Code. This is everything you know about them:", + "", + "", + skill, + "", + "", + "Reply with the complete definitions file in one ```ts code block and nothing else.", +].join("\n"); + +const sample = Effect.fn("evaluateWorkflowAuthoring.sample")(function* ( + entry: Case, + model: string, + index: number, +) { + const client = (yield* HttpClient.HttpClient).pipe( + HttpClient.retryTransient({ + retryOn: "errors-and-responses", + schedule: Schedule.exponential("2 seconds"), + times: 4, + }), + ); + const response = yield* HttpClientRequest.post(`${proxy.url}/responses`).pipe( + HttpClientRequest.setHeaders(proxy.headers), + HttpClientRequest.bodyJson({ + model, + instructions, + input: [{ role: "user", content: entry.task }], + reasoning: { effort: values.reasoning }, + store: false, + }), + Effect.flatMap(client.execute), + ); + const body = yield* response.text; + if (response.status !== 200) { + return yield* Effect.die(new Error(`Model API ${response.status}: ${body}`)); + } + const decoded = decodeResponse(body); + const reply = decoded.output + .filter((item) => item.type === "message") + .flatMap((item) => (item.content as Array<{ text?: string }>).map((part) => part.text ?? "")) + .join(""); + const code = /```(?:ts|typescript)?\n([\s\S]*?)```/.exec(reply)?.[1] ?? reply; + const file = NodePath.join(outDirectory, `${entry.id}.${model}.${index}.ts`); + NodeFS.writeFileSync(file, code); + const problems = yield* Effect.promise(() => grade(file, entry)); + return { + model, + case: entry.id, + sample: index, + problems, + tokens: decoded.usage?.total_tokens ?? 0, + }; +}); + +/** Half or more of a case's samples failing is the case failing. */ +const passes = (rows: ReadonlyArray, model: string, id: string) => { + const own = rows.filter((row) => row.model === model && row.case === id); + return own.length > 0 && own.filter((row) => row.problems.length > 0).length < own.length / 2; +}; + +NodeFS.mkdirSync(outDirectory, { recursive: true }); +const summary = await Effect.runPromise( + Effect.gen(function* () { + const count = Number(values.samples); + const rows = yield* Effect.forEach( + models.flatMap((model) => + selected.flatMap((entry) => + Array.from({ length: count }, (_, index) => ({ model, entry, index })), + ), + ), + ({ model, entry, index }) => + sample(entry, model, index).pipe( + Effect.catchDefect((defect) => + Effect.succeed({ + model, + case: entry.id, + sample: index, + problems: [`The sample did not run: ${String(defect)}`], + tokens: 0, + }), + ), + ), + // The grader starts an engine per scenario; a few at a time keeps their timings honest. + { concurrency: 3 }, + ); + NodeFS.writeFileSync( + NodePath.join(outDirectory, "results.ndjson"), + rows.map((row) => encodeRow(row)).join("\n") + "\n", + ); + const baseline = values.baseline + ? NodeFS.readFileSync(values.baseline, "utf8") + .trim() + .split("\n") + .map((line) => decodeRow(line)) + : undefined; + const words = skill.split(/\s+/).length; + const lines = [`skill ${skillFile}, ${words} words, ${count} samples per case`, ""]; + lines.push("| model | case | samples passed | verdict | baseline |", "|---|---|---|---|---|"); + for (const model of models) { + for (const entry of selected) { + const own = rows.filter((row) => row.model === model && row.case === entry.id); + const good = own.filter((row) => row.problems.length === 0).length; + const before = + baseline === undefined ? "" : passes(baseline, model, entry.id) ? "pass" : "fail"; + lines.push( + `| ${model} | ${entry.id} | ${good}/${own.length} | ${passes(rows, model, entry.id) ? "pass" : "FAIL"} | ${before} |`, + ); + } + } + const tokens = rows.reduce((sum, row) => sum + row.tokens, 0); + lines.push("", `${tokens} tokens`, "", "## Problems", ""); + for (const row of rows) { + for (const problem of row.problems) { + lines.push(`- ${row.model} ${row.case} #${row.sample}: ${problem}`); + } + } + const report = lines.join("\n") + "\n"; + NodeFS.writeFileSync(NodePath.join(outDirectory, "summary.md"), report); + return report; + }).pipe(Effect.provide(FetchHttpClient.layer)), +); +process.stdout.write(summary); diff --git a/knip.jsonc b/knip.jsonc index 748d6864e2217..bd3228b7ac504 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -17,6 +17,10 @@ "vite": { "entry": [".github/**/*.test.cjs"] }, "vitest": { "entry": [".github/**/*.test.cjs"] }, }, + "evals": { + // The grader loads these answers by path, as the server loads a definitions file. + "entry": ["workflow-authoring/fixtures/*.ts"], + }, "scripts": { // Knip loads its preprocessor through a CLI option; native verification and // worktree setup (from t3.json) run directly. release-desktop.yml bundles the diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index f7825d6364b79..b23b4650b20a9 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -82,6 +82,13 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.scheduledTasksRunNow]: AuthOrchestrationOperateScope, [WS_METHODS.scheduledTasksRotateWebhookToken]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.stopWorkflow]: AuthOrchestrationOperateScope, + // An answer, a resume and a cancel each decide what a run's agents do next. + [WS_METHODS.workflowsAnswer]: AuthOrchestrationOperateScope, + [WS_METHODS.workflowsResume]: AuthOrchestrationOperateScope, + [WS_METHODS.workflowsCancel]: AuthOrchestrationOperateScope, + // The server runs this file: saving it is running code there, as a terminal does. + [WS_METHODS.workflowsSaveDefinition]: AuthTerminalOperateScope, + [WS_METHODS.workflowsDeleteDefinition]: AuthTerminalOperateScope, // Force stop kills agent processes, as Stop on a terminal does. [ORCHESTRATION_V2_WS_METHODS.forceStopThread]: AuthOrchestrationOperateScope, // A guest link hands thread access to someone outside, like a pairing link. diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 7a159c816ef11..58863aaebd5e5 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -68,6 +68,7 @@ export * from "./previewCapture.ts"; export * from "./usage.ts"; export * from "./scheduledTask.ts"; export * from "./milestones.ts"; +export * from "./workflow.ts"; export * from "./worktreeMcp.ts"; export * from "./resourceTelemetry.ts"; export * from "./rpc.ts"; diff --git a/packages/contracts/src/milestones.ts b/packages/contracts/src/milestones.ts index 56e259b2b9fab..5bc08bc403edb 100644 --- a/packages/contracts/src/milestones.ts +++ b/packages/contracts/src/milestones.ts @@ -37,14 +37,25 @@ const MilestoneEnvelope = Schema.Struct({ threadId: Schema.NullOr(ThreadId), parentThreadId: Schema.NullOr(ThreadId), actor: MilestoneActor, - /** A subagent's thread. Muted unless asked for. */ + /** A subagent's thread, or a run another run invoked. Muted unless asked for. */ isSubagentChild: Schema.Boolean, + /** The workflow run a workflow milestone is about, or whose agent step the thread is. */ + workflowRunId: Schema.optional(TrimmedNonEmptyString), }); /** `approval` covers command, file and permission prompts; `user_input` covers questions. */ export const MilestoneInputKind = Schema.Literals(["user_input", "approval"]); export type MilestoneInputKind = typeof MilestoneInputKind.Type; +/** Which workflow run a workflow milestone is about. Its envelope names no project or thread. */ +const WorkflowRunFields = { + workflowRunId: TrimmedNonEmptyString, + workflow: TrimmedNonEmptyString, + runTitle: Schema.String, + /** The run that invoked this one, when one did. */ + parentWorkflowRunId: Schema.NullOr(TrimmedNonEmptyString), +}; + export const MilestoneEvent = Schema.Union([ Schema.Struct({ ...MilestoneEnvelope.fields, @@ -88,6 +99,45 @@ export const MilestoneEvent = Schema.Union([ /** The watch ended with this wake, as a merge, a close or a read failure ends it. */ watchEnded: Schema.Boolean, }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.run_started"), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.needs_input"), + /** The step that asks, which answering names. */ + step: TrimmedNonEmptyString, + question: Schema.String, + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.input_resolved"), + step: TrimmedNonEmptyString, + /** `cancelled` when the run ended with the question still open. */ + resolution: Schema.Literals(["answered", "expired", "cancelled"]), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.run_paused"), + reason: Schema.String, + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.run_resumed"), + }), + Schema.Struct({ + ...MilestoneEnvelope.fields, + ...WorkflowRunFields, + type: Schema.Literal("workflow.run_ended"), + outcome: Schema.Literals(["completed", "stopped", "skipped", "cancelled"]), + detail: Schema.NullOr(Schema.String), + }), ]); export type MilestoneEvent = typeof MilestoneEvent.Type; @@ -98,6 +148,12 @@ export const MilestoneEventType = Schema.Literals([ "thread.guest_request", "thread.guest_request_resolved", "pr.watch_wake", + "workflow.run_started", + "workflow.needs_input", + "workflow.input_resolved", + "workflow.run_paused", + "workflow.run_resumed", + "workflow.run_ended", ]); export type MilestoneEventType = typeof MilestoneEventType.Type; @@ -105,7 +161,11 @@ export const MilestoneFilter = Schema.Struct({ types: Schema.optional(Schema.Array(MilestoneEventType)), projectIds: Schema.optional(Schema.Array(ProjectId)), threadIds: Schema.optional(Schema.Array(ThreadId)), - /** Absent reads as false: subagent threads churn and are rarely news. */ + /** Workflow names. Given, it matches only workflow milestones. */ + workflows: Schema.optional(Schema.Array(TrimmedNonEmptyString)), + /** Workflow runs, with the threads that are their agent steps. */ + workflowRunIds: Schema.optional(Schema.Array(TrimmedNonEmptyString)), + /** Absent reads as false: subagent threads and invoked runs churn and are rarely news. */ includeSubagentChildren: Schema.optional(Schema.Boolean), }); export type MilestoneFilter = typeof MilestoneFilter.Type; @@ -117,4 +177,8 @@ export const milestoneMatches = (event: MilestoneEvent, filter: MilestoneFilter (filter.projectIds === undefined || (event.projectId !== null && filter.projectIds.includes(event.projectId))) && (filter.threadIds === undefined || - (event.threadId !== null && filter.threadIds.includes(event.threadId))); + (event.threadId !== null && filter.threadIds.includes(event.threadId))) && + (filter.workflows === undefined || + ("workflow" in event && filter.workflows.includes(event.workflow))) && + (filter.workflowRunIds === undefined || + (event.workflowRunId !== undefined && filter.workflowRunIds.includes(event.workflowRunId))); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 6eec84b4dc253..33961fcf8b82b 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -160,6 +160,18 @@ export const OrchestrationV2LinkedSender = Schema.Struct({ }); export type OrchestrationV2LinkedSender = typeof OrchestrationV2LinkedSender.Type; +/** + * The workflow run a thread is an agent step of, with the step's name. `environmentId` is where + * the run lives, which is another environment for a step that runs through a link. + */ +export const OrchestrationV2WorkflowOrigin = Schema.Struct({ + environmentId: EnvironmentId, + runId: TrimmedNonEmptyString, + workflow: TrimmedNonEmptyString, + step: TrimmedNonEmptyString, +}); +export type OrchestrationV2WorkflowOrigin = typeof OrchestrationV2WorkflowOrigin.Type; + export const OrchestrationV2NativeRefStrength = Schema.Literals(["strong", "weak", "none"]); export type OrchestrationV2NativeRefStrength = typeof OrchestrationV2NativeRefStrength.Type; @@ -177,12 +189,19 @@ export const OrchestrationV2AppThreadLineage = Schema.Struct({ relationshipToParent: Schema.NullOr(Schema.Literals(["fork", "subagent"])), rootThreadId: ThreadId, sideChat: Schema.optional(Schema.Boolean), + /** An agent step of a workflow run, which the thread's `workflowRun` names. */ + workflowStep: Schema.optional(Schema.Boolean), }); export type OrchestrationV2AppThreadLineage = typeof OrchestrationV2AppThreadLineage.Type; -/** Subagents and side chats live inside their parent's view, never in thread lists. */ +/** + * Subagents and side chats live inside their parent's view, and a workflow run's agent steps + * inside the run's, never in thread lists. + */ export const isListedThreadLineage = (lineage: OrchestrationV2AppThreadLineage): boolean => - lineage.relationshipToParent !== "subagent" && lineage.sideChat !== true; + lineage.relationshipToParent !== "subagent" && + lineage.sideChat !== true && + lineage.workflowStep !== true; export const OrchestrationV2ContextTransferType = Schema.Literals([ "fork", @@ -497,6 +516,7 @@ export const OrchestrationV2AppThread = Schema.Struct({ historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin), linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), + workflowRun: Schema.optional(OrchestrationV2WorkflowOrigin), lineage: OrchestrationV2AppThreadLineage, forkedFrom: Schema.NullOr( Schema.Union([ @@ -2387,6 +2407,7 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin), linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), + workflowRun: Schema.optional(OrchestrationV2WorkflowOrigin), latestRunId: Schema.NullOr(RunId), latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), @@ -3288,6 +3309,8 @@ export const OrchestrationV2Command = Schema.Union([ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), /** Only the server sets this, with `linkOrigin`, for a linked environment's delegated task. */ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), + /** Only the server sets this, for a thread that is a workflow run's agent step. */ + workflowRun: Schema.optional(OrchestrationV2WorkflowOrigin), importedNativeThread: Schema.optional( Schema.Struct({ ref: Schema.Struct({ diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index e56009a98fb4e..c7fe990a4be7e 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -420,6 +420,22 @@ import { ListTextGeneratorModelsResult, TextGeneratorError, } from "./settings.ts"; +import { + WorkflowAnswerInput, + WorkflowRequestError, + WorkflowDefinitionChangeResult, + WorkflowDefinitionDeleteInput, + WorkflowDefinitionFiles, + WorkflowDefinitionGetInput, + WorkflowDefinitionSaveInput, + WorkflowRunCancelInput, + WorkflowRunDetail, + WorkflowRunGetInput, + WorkflowRunResumeInput, + WorkflowCounts, + WorkflowRunsSnapshot, + WorkflowRunsSubscribeInput, +} from "./workflow.ts"; import { ScheduledTaskDeleteInput, ScheduledTaskDeleteResult, @@ -617,6 +633,16 @@ export const WS_METHODS = { serverGetUsageSummary: "server.getUsageSummary", serverRefreshUsageRates: "server.refreshUsageRates", + workflowsSubscribe: "workflows.subscribe", + workflowsCounts: "workflows.counts", + workflowsGet: "workflows.get", + workflowsAnswer: "workflows.answer", + workflowsResume: "workflows.resume", + workflowsCancel: "workflows.cancel", + workflowsGetDefinition: "workflows.getDefinition", + workflowsSaveDefinition: "workflows.saveDefinition", + workflowsDeleteDefinition: "workflows.deleteDefinition", + scheduledTasksSubscribe: "scheduledTasks.subscribe", scheduledTasksUpsert: "scheduledTasks.upsert", scheduledTasksSetEnabled: "scheduledTasks.setEnabled", @@ -2286,6 +2312,59 @@ const WsSubscribeServerLifecycleRpc = Rpc.make(WS_METHODS.subscribeServerLifecyc stream: true, }); +const WsWorkflowsSubscribeRpc = Rpc.make(WS_METHODS.workflowsSubscribe, { + payload: WorkflowRunsSubscribeInput, + success: WorkflowRunsSnapshot, + error: EnvironmentAuthorizationError, + stream: true, +}); + +const WsWorkflowsCountsRpc = Rpc.make(WS_METHODS.workflowsCounts, { + payload: WorkflowRunsSubscribeInput, + success: WorkflowCounts, + error: EnvironmentAuthorizationError, + stream: true, +}); + +const WsWorkflowsGetRpc = Rpc.make(WS_METHODS.workflowsGet, { + payload: WorkflowRunGetInput, + success: WorkflowRunDetail, + error: Schema.Union([WorkflowRequestError, EnvironmentAuthorizationError]), +}); + +const WsWorkflowsAnswerRpc = Rpc.make(WS_METHODS.workflowsAnswer, { + payload: WorkflowAnswerInput, + error: Schema.Union([WorkflowRequestError, EnvironmentAuthorizationError]), +}); + +const WsWorkflowsResumeRpc = Rpc.make(WS_METHODS.workflowsResume, { + payload: WorkflowRunResumeInput, + error: Schema.Union([WorkflowRequestError, EnvironmentAuthorizationError]), +}); + +const WsWorkflowsCancelRpc = Rpc.make(WS_METHODS.workflowsCancel, { + payload: WorkflowRunCancelInput, + error: Schema.Union([WorkflowRequestError, EnvironmentAuthorizationError]), +}); + +const WsWorkflowsGetDefinitionRpc = Rpc.make(WS_METHODS.workflowsGetDefinition, { + payload: WorkflowDefinitionGetInput, + success: WorkflowDefinitionFiles, + error: EnvironmentAuthorizationError, +}); + +const WsWorkflowsSaveDefinitionRpc = Rpc.make(WS_METHODS.workflowsSaveDefinition, { + payload: WorkflowDefinitionSaveInput, + success: WorkflowDefinitionChangeResult, + error: EnvironmentAuthorizationError, +}); + +const WsWorkflowsDeleteDefinitionRpc = Rpc.make(WS_METHODS.workflowsDeleteDefinition, { + payload: WorkflowDefinitionDeleteInput, + success: WorkflowDefinitionChangeResult, + error: EnvironmentAuthorizationError, +}); + const WsScheduledTasksSubscribeRpc = Rpc.make(WS_METHODS.scheduledTasksSubscribe, { payload: ScheduledTaskListInput, success: ScheduledTaskListResult, @@ -2461,6 +2540,15 @@ export const WsRpcGroup = RpcGroup.make( WsServerGetUsageSummaryRpc, WsServerRefreshUsageRatesRpc, WsServerSignalProcessRpc, + WsWorkflowsSubscribeRpc, + WsWorkflowsCountsRpc, + WsWorkflowsGetRpc, + WsWorkflowsAnswerRpc, + WsWorkflowsResumeRpc, + WsWorkflowsCancelRpc, + WsWorkflowsGetDefinitionRpc, + WsWorkflowsSaveDefinitionRpc, + WsWorkflowsDeleteDefinitionRpc, WsScheduledTasksSubscribeRpc, WsScheduledTasksUpsertRpc, WsScheduledTasksSetEnabledRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 4538065ee5c50..e7887f88f0369 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1501,6 +1501,8 @@ export const ServerSettings = Schema.Struct({ * and tasks on another machine; tasks already running there finish. */ linkedEnvironmentsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + /** Beta: durable workflows from the workflows folder of the T3 home. Off runs none of them. */ + workflowsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), /** Beta: Claude and Codex predict the next prompt after completed turns. Codex follows a change at once; open Claude threads after they restart. */ promptSuggestionsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), sidebarAutoSettleKeepPullRequests: Schema.Boolean.pipe( @@ -1938,6 +1940,7 @@ export const ServerSettingsPatch = Schema.Struct({ hideTaggedThreads: Schema.optionalKey(Schema.Boolean), guestSharingEnabled: Schema.optionalKey(Schema.Boolean), linkedEnvironmentsEnabled: Schema.optionalKey(Schema.Boolean), + workflowsEnabled: Schema.optionalKey(Schema.Boolean), promptSuggestionsEnabled: Schema.optionalKey(Schema.Boolean), backgroundActivity: Schema.optionalKey( Schema.Struct({ diff --git a/packages/contracts/src/workflow.ts b/packages/contracts/src/workflow.ts new file mode 100644 index 0000000000000..cc0d958d1f9ee --- /dev/null +++ b/packages/contracts/src/workflow.ts @@ -0,0 +1,223 @@ +import * as Schema from "effect/Schema"; + +import { IssueRef } from "./issue.ts"; +import { PullRequestRef } from "./pullRequest.ts"; + +export const WorkflowRunStatus = Schema.Literals([ + "running", + "waiting", + "paused", + "completed", + "stopped", + /** Ended by the workflow as not its to do. Lists leave these out unless asked. */ + "skipped", + "cancelled", +]); +export type WorkflowRunStatus = typeof WorkflowRunStatus.Type; + +export const WorkflowRun = Schema.Struct({ + runId: Schema.String, + workflow: Schema.String, + version: Schema.Number, + title: Schema.String, + status: WorkflowRunStatus, + /** Why it is paused, what it waits on, or how it ended. */ + detail: Schema.NullOr(Schema.String), + result: Schema.NullOr(Schema.Json), + /** How many times in a row it has been paused by a failing step. */ + pauses: Schema.Number, + /** Its version is no longer registered, so it cannot go on until that version is back. */ + retired: Schema.Boolean, + /** When a paused run is resumed without anyone asking; null when it waits for a person. */ + resumesAt: Schema.NullOr(Schema.String), + /** The run that invoked this one and waits for it; null for a run started by itself. */ + parentRunId: Schema.NullOr(Schema.String), + /** The step of that run this one was invoked as. */ + parentStep: Schema.NullOr(Schema.String), + startedAt: Schema.String, + updatedAt: Schema.String, + endedAt: Schema.NullOr(Schema.String), +}); +export type WorkflowRun = typeof WorkflowRun.Type; + +export const WorkflowStep = Schema.Struct({ + name: Schema.String, + // A sleep's `detail` is when it wakes, as an ISO time. + kind: Schema.Literals(["step", "wait", "agent", "ask", "sleep"]), + status: Schema.Literals(["running", "completed", "failed"]), + attempts: Schema.Number, + detail: Schema.NullOr(Schema.String), + /** The thread an agent step ran in. */ + threadId: Schema.NullOr(Schema.String), + /** The linked environment that thread is in; null when it is this one. */ + environmentId: Schema.NullOr(Schema.String), + /** What it produced: a step's value, an agent's data or reply, the answer to a question. */ + result: Schema.NullOr(Schema.Json), + /** What an agent said in closing, when its result is data and not that reply. */ + said: Schema.NullOr(Schema.String), + startedAt: Schema.String, + endedAt: Schema.NullOr(Schema.String), +}); +export type WorkflowStep = typeof WorkflowStep.Type; + +/** A question a run asked. Answer it with a signal to its run and name. */ +export const WorkflowQuestion = Schema.Struct({ + runId: Schema.String, + name: Schema.String, + /** What `ask` was given: a title, the choices, and data to lay out. */ + request: Schema.Json, + askedAt: Schema.String, + /** The run's latest agent thread, for talking it through before answering. */ + thread: Schema.NullOr( + Schema.Struct({ threadId: Schema.String, environmentId: Schema.NullOr(Schema.String) }), + ), +}); +export type WorkflowQuestion = typeof WorkflowQuestion.Type; + +/** Where a workflow takes requests. `path` holds the hook's secret. */ +export const WorkflowHook = Schema.Struct({ + workflow: Schema.String, + name: Schema.String, + path: Schema.String, +}); +export type WorkflowHook = typeof WorkflowHook.Type; + +/** What a client shows of workflows: recent runs, newest first, and the questions still open. */ +/** A workflow this server has registered, at its newest version, and what starts it. */ +export const WorkflowSummary = Schema.Struct({ + name: Schema.String, + version: Schema.Number, + /** In words: "every 1h", "daily at 09:00", "webhook issues". Empty when only started by hand. */ + triggers: Schema.Array(Schema.String), +}); +export type WorkflowSummary = typeof WorkflowSummary.Type; + +/** Something wrong with the definitions: in `file` when it is one file's, at `line` when it names one. */ +export const WorkflowDefinitionProblem = Schema.Struct({ + message: Schema.String, + file: Schema.optional(Schema.String), + line: Schema.optional(Schema.Number), +}); +export type WorkflowDefinitionProblem = typeof WorkflowDefinitionProblem.Type; + +/** Which loading of the definitions file is running, and what is wrong with the file now. */ +export const WorkflowDefinitionState = Schema.Struct({ + /** Goes up whenever the file is loaded or found wrong, so a client knows to read it again. */ + revision: Schema.Number, + /** Why the file on disk is not what runs. The last version that loaded keeps running. */ + problem: Schema.NullOr(Schema.String), +}); + +export const WorkflowDefinitionFile = Schema.Struct({ + name: Schema.String, + /** The file as it is on disk, which is not what runs while it has problems. */ + source: Schema.String, + /** The workflows its last good version defines, each as `name@version`. */ + workflows: Schema.Array(Schema.String), + problems: Schema.Array(WorkflowDefinitionProblem), +}); +export type WorkflowDefinitionFile = typeof WorkflowDefinitionFile.Type; + +/** The files that define this server's workflows. */ +export const WorkflowDefinitionFiles = Schema.Struct({ + /** The folder the files are in. */ + directory: Schema.String, + /** The server was pointed at one file: no file can be added beside it or taken away. */ + single: Schema.Boolean, + files: Schema.Array(WorkflowDefinitionFile), + /** What is wrong between files, such as one workflow defined in two of them. */ + problems: Schema.Array(WorkflowDefinitionProblem), + ...WorkflowDefinitionState.fields, +}); +export type WorkflowDefinitionFiles = typeof WorkflowDefinitionFiles.Type; + +export const WorkflowDefinitionGetInput = Schema.Struct({}); +/** A file by its name in the folder. Saving a name that is not there yet makes the file. */ +export const WorkflowDefinitionSaveInput = Schema.Struct({ + name: Schema.String, + source: Schema.String, +}); +export const WorkflowDefinitionDeleteInput = Schema.Struct({ name: Schema.String }); +export const WorkflowDefinitionChangeResult = Schema.Struct({ + /** The file was written or deleted. */ + changed: Schema.Boolean, + /** Empty when the change is what runs now. With `changed`, why it does not run yet. */ + problems: Schema.Array(WorkflowDefinitionProblem), +}); +export type WorkflowDefinitionChangeResult = typeof WorkflowDefinitionChangeResult.Type; + +export const WorkflowRunsSnapshot = Schema.Struct({ + workflows: Schema.Array(WorkflowSummary), + runs: Schema.Array(WorkflowRun), + questions: Schema.Array(WorkflowQuestion), + definition: Schema.optional(WorkflowDefinitionState), +}); + +/** How much is going on, for a badge that must not cost a list of runs to keep current. */ +export const WorkflowCounts = Schema.Struct({ + /** Open questions and paused runs: what waits on a person. */ + needsYou: Schema.Number, + /** Runs that have not ended. */ + active: Schema.Number, + /** Runs there have ever been, so a client knows whether workflows are in use at all. */ + total: Schema.Number, +}); +export type WorkflowCounts = typeof WorkflowCounts.Type; +export type WorkflowRunsSnapshot = typeof WorkflowRunsSnapshot.Type; + +export const WorkflowRunsSubscribeInput = Schema.Struct({}); + +export const WorkflowRunGetInput = Schema.Struct({ runId: Schema.String }); + +/** + * Something a run touched: an issue, a pull request, or a kind added later. `kind` is open, so a + * client shows a kind it does not know by its title and `url`. `key` is the thing's identity in + * its kind; `address` is whatever that kind needs to open it. + */ +export const WorkflowRunReference = Schema.Struct({ + kind: Schema.String, + key: Schema.String, + address: Schema.Json, + /** Empty until something that touched it knew its title. */ + title: Schema.String, + url: Schema.NullOr(Schema.String), + /** A word for where it stands, such as `open`, `merged` or `closed`. */ + state: Schema.NullOr(Schema.String), + /** The steps that touched it, in the order they first did. */ + steps: Schema.Array(Schema.String), + origin: Schema.Literals(["trigger", "step"]), +}); +export type WorkflowRunReference = typeof WorkflowRunReference.Type; + +/** The kinds of reference runs record today; `address` is an `IssueRef` or a `PullRequestRef`. */ +export const WorkflowReferenceKind = { issue: "issue", pullRequest: "pullRequest" } as const; +export const WorkflowIssueAddress = IssueRef; +export const WorkflowPullRequestAddress = PullRequestRef; + +/** One run with its steps, in the order they started, and what it touched. */ +export const WorkflowRunDetail = Schema.Struct({ + run: WorkflowRun, + steps: Schema.Array(WorkflowStep), + references: Schema.Array(WorkflowRunReference), +}); +export type WorkflowRunDetail = typeof WorkflowRunDetail.Type; + +/** A person's answer to a `WorkflowQuestion`: one of its choices and, if they gave one, why. */ +export const WorkflowAnswerInput = Schema.Struct({ + runId: Schema.String, + name: Schema.String, + choice: Schema.String, + reason: Schema.optional(Schema.String), +}); + +export const WorkflowRunResumeInput = Schema.Struct({ runId: Schema.String }); + +export const WorkflowRunCancelInput = Schema.Struct({ + runId: Schema.String, + reason: Schema.optional(Schema.String), +}); + +export class WorkflowRequestError extends Schema.TaggedError()( + "WorkflowRequestError", + { message: Schema.String }, +) {} diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index 24910bc0bf9cf..71a9897b841f3 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -148,6 +148,23 @@ layer("NodeSqliteClient", (it) => { const largeText = "x".repeat(64 * 1024 + 1); +it.effect("a rowid above 2^53 does not leave a transaction open", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE big (id INTEGER PRIMARY KEY, name TEXT)`; + yield* sql`INSERT INTO big (id, name) VALUES (246166233861328896, 'first')`; + // BEGIN reports the connection's last insert rowid; a failure to convert it must not + // read as a failed BEGIN, or the open transaction is never rolled back. + yield* sql.withTransaction(sql`INSERT INTO big (name) VALUES ('second')`); + yield* sql.withTransaction(sql`UPDATE big SET name = 'third' WHERE name = 'second'`); + const rows = yield* sql<{ name: string }>`SELECT name FROM big ORDER BY id`; + assert.deepStrictEqual( + rows.map((row) => row.name), + ["first", "third"], + ); + }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))), +); + it.effect("reads integers on the values path as the caller asked, cached or not", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index da521a7c6036d..bb00de7459816 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -286,6 +286,8 @@ parentPort.on("message", (request) => { if (pendingBatch) Atomics.wait(received, 0, 0); parentPort.postMessage({ id, rows }); } else { + // A discarded result is read as BigInt: see the same line in the in-process client. + if (!raw) statement.setReadBigInts(true); const result = statement.run(...params); parentPort.postMessage({ id, rows: raw ? result : [] }); } @@ -854,6 +856,10 @@ const make = Effect.fn("makeWithDatabase")(function* ( if (arrays) statement.setReturnArrays(true); result = Exit.succeed(statement.all(...(params as any))); } else { + // `run` reports the connection's last insert rowid even for BEGIN. One above 2^53 + // throws on conversion after the statement already took effect, so a discarded + // result is read as BigInt. + if (mode !== "raw") statement.setReadBigInts(true); const value = statement.run(...(params as any)); result = Exit.succeed( mode === "raw" ? (value as unknown as ReadonlyArray) : [], diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index fc2af2e05cc37..860f28c44f0a1 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -359,6 +359,7 @@ const T3_MCP_TOOLS: Readonly> = { ["Handle", "Handling", "Handled", "pending questions"], "question-respond", ), + t3_workflow: tool(["Use", "Using", "Used", "workflow runs"], "thread-send"), t3_submit_output: tool(["Submit", "Submitting", "Submitted", "the result"], "thread-send"), t3_queue_list: tool(["List", "Listing", "Listed", "queued messages"], "queue-list"), t3_queue_read: tool(["Read", "Reading", "Read", "a queued message"], "queue-read"), diff --git a/skills/t3-workflows/SKILL.md b/skills/t3-workflows/SKILL.md new file mode 100644 index 0000000000000..7f600e0b4cee5 --- /dev/null +++ b/skills/t3-workflows/SKILL.md @@ -0,0 +1,353 @@ +--- +name: t3-workflows +description: Author, edit, run, and debug durable T3 Code workflows (`~/.t3/workflows/*.ts`). Use when asked to build or change a multi-step T3 Code automation tying together agent threads, code steps, schedules, webhooks, issue/PR trackers, or human approvals, or to inspect, resume, signal, or cancel workflow runs. +--- + +# T3 Code workflows + +A workflow is a TypeScript function the T3 Code server runs durably on Effect v4 (`effect/workflow`). Every step's result is stored, so restarts replay to where the run left off and a failing step pauses the run instead of losing it. Runs can sleep for days, wait on signals or pull requests, ask a person a question, and launch agents in ordinary threads. + +Use a workflow for multi-stage work that must not be lost or repeated (triage → fix → verify, nightly reports, webhook reactions). For a single prompt on a timer, use a scheduled task instead. + +## Quick start + +Workflows are a Labs feature, off by default. If `t3 workflow` says workflows are off, ask the user to turn them on in Settings → Labs → Workflows; do not edit their settings yourself. + +Put a `.ts` file in `~/.t3/workflows/` (the `workflows` folder of T3 home, or the path in `T3CODE_WORKFLOWS`). Once workflows are on, the server watches the folder and reloads files automatically—nothing to restart. A file name with a space or other unusual character (`fix issue.ts`) is skipped with a warning in the server log: use letters, digits, `-`, `_` and `.`. Files run with Node's type stripping, so only erasable TypeScript works: no `enum`, `namespace` or parameter properties. + +Workflow files import nothing from T3 or Effect. `T3`, `Effect`, `Schema`, `Option`, `Duration`, and `Schedule` are injected as globals. Never `import` from `effect` (that loads a second runtime copy the engine cannot run). Node built-ins (`node:fs`, `node:crypto`) can be imported normally. + +```ts +const { workflow, agent, ask, stop, title, every, Tick } = T3; + +workflow( + "dependency-report", + { version: 1, payload: Tick, triggers: [every("1 day")] }, + Effect.fn(function* (tick) { + yield* title(`Dependencies ${tick.scheduledAt.slice(0, 10)}`); + + const audit = yield* agent("audit", { + project: "/home/me/app", // the project's folder, or its id + brief: "List this repository's outdated dependencies. Do not change any file.", + returns: Schema.Struct({ + outdated: Schema.Array(Schema.Struct({ name: Schema.String, latest: Schema.String })), + }), + }); + if (audit.value.outdated.length === 0) return yield* stop("nothing is outdated"); + + const answer = yield* ask("approve-upgrade", { + title: `Upgrade ${audit.value.outdated.length} dependencies?`, + choices: ["upgrade", "skip"], + data: audit.value, + timeout: "2 days", + }); + if (Option.isNone(answer) || answer.value.choice === "skip") { + return yield* stop("not approved"); + } + + yield* agent("upgrade", { + thread: audit.thread, + brief: "Upgrade the dependencies you listed, run the tests, and say what changed.", + }); + }), +); +``` + +### What `T3` holds + +Only `T3`, `Effect`, `Schema`, `Option`, `Duration` and `Schedule` are globals. Everything below is a +property of `T3`: take what you use at the top of the file, as the quick start does +(`const { workflow, step, daily } = T3;`), or write `T3.step(…)` in full. A bare `daily(…)` or +`step(…)` without that line is a `ReferenceError`. + +- **Definitions & body**: `workflow`, `step`, `agent`, `ask`, `wait`, `sleep`, `title`, `stop`, `skip`, `invoke` +- **Inside `step` / `onEnd` only**: `store`, `signal`, `signalAll`, `start`, `runs`, `cancel` +- **Trackers & hosts**: `issues`, `pullRequests` (triggers, step calls, and `pullRequests.wait` in the body) +- **Triggers**: `every`, `daily`, `webhook` +- **Schemas**: `Tick`, `WebhookRequest`, `Issue`, `IssueDetail`, `PullRequest`, `PullRequestStanding` + +### Effect v4 `Schema` cheatsheet + +```ts +Schema.String; +Schema.Number; +Schema.Boolean; +Schema.Void; +Schema.Null; +Schema.Struct({ name: Schema.String, count: Schema.optional(Schema.Number) }); +Schema.Array(Schema.String); +Schema.Literals(["open", "closed"]); +Schema.NullOr(Schema.String); +Schema.Record(Schema.String, Schema.Number); // two arguments, not an object +``` + +## Defining a workflow + +`workflow(name, options, body)` registers a workflow and returns a handle you can pass to `invoke`, `start`, `runs`, or `signal`. Each `(name, version)` pair must be unique across all files. + +| Option | Required | Meaning | +| ------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `version` | Yes | Integer version. Raise it whenever the body changes (see rules below). | +| `payload` | Yes | `Schema` of the run's input. | +| `returns` | No | `Schema` of the body's return value. If omitted, any JSON value (or `undefined`) is accepted. | +| `triggers` | No | Array of triggers that start runs automatically. | +| `resumeAfter` | No | Durations to wait before auto-resuming a paused run. Defaults to `["5 minutes", "20 minutes", "80 minutes"]`. The server checks about every 15 seconds, so shorter waits act as 15 seconds. | +| `onEnd` | No | `(payload, { id, outcome, reason }) => Effect`: cleanup hook run once when the run ends. | + +The body is `Effect.fn(function* (payload, run) { … })`, where `run.id` is the run's id. Use `yield*` on every primitive. + +### Cleanup with `onEnd` + +`onEnd` runs once when a run completes, stops, is skipped, or is cancelled—not when it pauses. It runs with step services (`store`, `signal`, `issues`, etc.), receives `(payload, { id, outcome, reason })`, and cannot see local variables from the body. Name external resources after `run.id`, and make `onEnd` safe if the run was cancelled before acquiring anything. + +```ts +const { workflow, step, agent, Issue } = T3; + +workflow( + "fix", + { + version: 1, + payload: Issue, + onEnd: (issue, end) => exec("machines.sh", ["delete", `fix-${end.id}`]), + }, + Effect.fn(function* (issue, run) { + const environment = yield* step( + "machine", + { returns: Schema.String }, + exec("machines.sh", ["create-and-link", `fix-${run.id}`]), + ); + yield* agent("fix", { environment, project: "/home/user/app", brief: issue.title }); + }), +); +``` + +(`exec` above is your own Effect helper, not part of `T3`.) On normal end, `onEnd` retries 3 times before pausing at the `onEnd` step; on cancel, it waits for any in-flight step to finish, then tries up to 5 times, 5 minutes, 20 minutes, 80 minutes and 5 hours apart. The workflow version stays required until one try succeeds; after the last failed try the `onEnd` step stays `failed` on the run and nothing retries it, so make cleanup something a person can redo by hand. + +## Body primitives + +Call these directly in the workflow body with `yield*`. Every named primitive stores its result under `name`, which must be unique across all primitives in the run (an `ask("fix", …)` and `agent("fix", …)` collide). + +| Call | Behavior | Returns | +| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- | +| `step(name, { returns, retry? }, effect)` | Runs code once per run and journals the result. Failure pauses the run. | `A` | +| `step.try(name, { returns, retry? }, effect)` | Same as `step`, but returns failure as data instead of pausing. | `{ outcome: "done", value }` or `{ outcome: "failed", reason }` | +| `agent(name, { brief, project? \| thread?, returns?, … })` | Runs an agent in a thread. Failure pauses the run for a person. | `{ value, thread }` (`value` matches `returns`, or last reply string) | +| `agent.try(name, { brief, project? \| thread?, returns?, … })` | Same as `agent`, but returns failure as data instead of pausing. | `{ outcome: "done", value, thread }` or `{ outcome: "failed", reason, thread? }` | +| `ask(name, { title, choices, data?, timeout? })` | Puts a multiple-choice question to a person. | `Option<{ choice, reason? }>` (`None` on timeout) | +| `wait(name, { returns, timeout?, channel? })` | Sleeps until signalled by `{ runId, wait }` or `{ workflow, channel }`. | `Option` (`None` on timeout) | +| `pullRequests.wait(name, pr, { until, timeout? })` | Sleeps until PR checks settle, or the PR merges or closes. | `Option` (`None` on timeout) | +| `sleep(name, duration)` | Durable sleep across restarts (e.g. `"1 hour"`, `"2 days"`). | `void` | +| `invoke(name, workflow, payload, { key? })` | Runs another workflow as a child run and waits for it to end. | `{ outcome: "completed", value }` or `{ outcome: "stopped" \| "skipped" \| "cancelled", reason }` | +| `title(text)` | Sets the run's display title in lists (cut to 200 characters). Takes no step name. | `void` | +| `stop(reason)` | Ends the run on purpose as `stopped` (not a failure). Body only: inside a `step` it fails the step and pauses the run, and so does `skip`. | `never` | +| `skip(reason)` | Ends the run as `skipped`, which run lists leave out unless asked (`runs()` includes them). | `never` | + +- **Retries and failures:** A `step` runs once by default. For idempotent work, pass `retry: { times: 3, schedule: Schedule.exponential("2 seconds") }`. Nothing in the body can catch a failed `step` or `agent` because the engine pauses the run—use `step.try` or `agent.try` whenever the workflow should branch on failure. +- **Timeouts are checked about every 15 seconds:** a `wait` or `ask` timeout can end up to 15 seconds late, and a signal that arrives before the check still wins. +- **`Option` results:** `wait`, `ask` and `pullRequests.wait` always give an `Option`, with or without a `timeout`. Check `Option.isNone(result)` first, then read `result.value`. Never put the `Option` itself into a string or a return value. +- **Concurrency:** Run steps or agents in parallel with `Effect.all([agent("a", …), agent("b", …)], { concurrency: 2 })`. +- **Strict options:** Every call refuses an option it does not take, naming the ones it does, since workflow files are not type-checked. So does `every` under a minute and a `daily` time it cannot read. + +## Agents (`agent` and `agent.try`) + +| Option | Applies to | Meaning | +| ----------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `brief` | All | Full task instructions. The agent sees only this brief and its project. | +| `project` | New thread | Project id (from `t3_project_list`) or absolute folder path. | +| `thread` | Continue | `thread` returned by an earlier `agent` step. Continues it as it started, so the New thread options are refused alongside it. | +| `returns` | All | Optional `Schema`. Completes only when the agent submits valid data (up to 2 correction prompts). | +| `model` | New thread | `{ instanceId, model, options? }`; `options` is `[{ id, value }]` (e.g. `[{ id: "reasoningEffort", value: "high" }]`). Defaults to project default. | +| `workspace` | New thread | `{ type: "root" }` (default) or `{ type: "worktree", baseRef: "origin/main", startFromOrigin: true }`. | +| `runtimeMode` | New thread | `"full-access" \| "auto" \| "auto-accept-edits" \| "approval-required"` (waits on thread approvals). Project default if omitted. | +| `interactionMode` | New thread | `"default" \| "plan"`. | +| `title` | New thread | Thread title. Defaults to `: `. | +| `environment` | New thread | Linked environment id (`t3 environment list`). Folder paths not yet registered there are registered automatically. | +| `issue` | Local only | `Issue` or `{ project, url }`. Links the thread to that issue (not applied in linked environments). | +| `timeout` | All | Time limit for each attempt (e.g. `"2 hours"`); an automatic retry or a resume starts a new one. Past it, the turn is stopped and the step fails. | +| `quiet` | All | Idle grace period (e.g. `"45 minutes"`) for agents that wait across turns before submitting `returns`. | + +- **Worktrees:** Use a `worktree` workspace whenever two agents can edit the same repo at once (concurrent runs or parallel `agent` calls). +- **Waiting across turns (`quiet`):** If an agent watches PR checks or background work and ends its turn while waiting to be woken, set `quiet: "45 minutes"` and tell it in `brief` to end waiting turns without submitting. The step prompts for the result only after the thread has been idle for `quiet`. Without `quiet`, it prompts as soon as a turn ends without output. Always set a `timeout` alongside `quiet`. +- **Retries and pauses:** If a turn dies (crashes or is cut off), `agent` automatically tries once more (on a fresh thread, or the same thread if continuing `thread`). An agent that finishes its turn without valid `returns` is asked to correct it twice in the same thread, and then gives up without starting the job again. A timeout or manual stop does not auto-retry. A run paused by an agent that ran and gave up or timed out waits for a person—`resumeAfter` does not auto-resume it (`t3 workflow resume` starts a fresh attempt). An agent that could not be started at all (no project at that folder, linked environment unreachable) pauses like a failed `step` and resumes on its own; `agent.try` returns that failure as data instead. +- **Fallback with `agent.try`:** + +```ts +Effect.fn(function* () { + let fix = yield* agent.try("fix", { project, brief, returns: Fix, timeout: "2 hours" }); + if (fix.outcome === "failed") { + fix = yield* agent.try("fix-again", { project, brief, returns: Fix, model: stronger }); + } + if (fix.outcome === "failed") return yield* stop(`no fix: ${fix.reason}`); +}); +``` + +- **Linked environments:** Enable Settings → Labs → Linked environments. The run stays on this server; only the thread runs remotely, bounded by the link's paired access. For a machine per run, create and link it in a `step` (`t3 auth pairing create --json` on the remote, `t3 environment link --pairing-code --access ` here), return its id, and delete it in `onEnd`. + +## Other workflows + +Define caller and callee in the same file and keep the callee in a variable so its payload and return type flow through: + +```ts +const { workflow, invoke, stop } = T3; + +const review = workflow("review", { version: 1, payload: Change, returns: Verdict }, reviewBody); + +workflow( + "fix", + { version: 1, payload: Issue }, + Effect.fn(function* (issue) { + const ended = yield* invoke("review", review, { branch: `fix/${issue.key}` }); + if (ended.outcome !== "completed") { + return yield* stop(`review ${ended.outcome}: ${ended.reason}`); + } + return ended.value; // Verdict + }), +); +``` + +| Call | Where | Behavior | +| ------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `invoke(name, workflow, payload, { key? })` | Body | Starts a child run and waits for it (including while it is paused). Listed and resumed independently; cancelling the parent cancels the child. Pass the definition `workflow(…)` returned, not its name. `key` names the child run; one already started under that key by something else is refused. | +| `start(workflow, payload, { key })` | `step` / `onEnd` | Fire-and-forget. Returns `{ runId }`. Same `key` returns the same run. Use for fan-out. | +| `runs({ workflow?, status?, keyPrefix? })` | `step` / `onEnd` | Lists up to 500 matching runs (skipped runs included), newest first: `{ id, workflow, key, title, status, detail, startedAt, endedAt }`. `workflow` is a definition or its name. | +| `cancel(runId, reason)` | `step` / `onEnd` | Cancels another run (stops agents, withdraws questions, cancels invoked children, runs `onEnd`). Cannot cancel self—use `stop`. | + +End subject keys with a separator (e.g. `issue/412/`), so `runs({ workflow: fix, keyPrefix: "issue/412/" })` does not match `issue/4120`. + +## Store and signals + +`store` holds durable key-value state shared across all workflows on the server (cursors, switches, counters, queues). Call `store`, `signal`, and `signalAll` **only inside `step` or `onEnd`**—never directly in the body. + +| Call | Behavior | +| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `store.entry(key, Schema)` | Handle for one key: `.get` (`Option`), `.set(value)`, `.delete`. | +| `entry.update((current) => next)` | Atomic read-modify-write; `current` is `Option`. Return `undefined` to delete. Returns `Option`. | +| `store.entries(prefix, Schema)` | Every `{ key, value }` starting with `prefix`, in key order. Fails if any matching row does not fit `Schema`. | +| `store.transaction(effect)` | Runs all store reads and writes in `effect` atomically (all or nothing). | +| `signal(address, value, { id?, ttl? })` | Wakes one `wait` at `{ runId, wait }` or `{ workflow, channel }`. Buffered until a wait opens or `ttl` (default 7 days) expires. Returns `"delivered" \| "buffered"`. `"buffered"` checks neither the address nor the shape: a wrong workflow or wait name, or a run that has ended, also buffers. A value that does not fit an open wait fails the sending step. | +| `signalAll({ channel, workflow? }, value)` | Wakes every run currently waiting on `channel` (one workflow or all). Returns count woken. Buffers nothing. | + +```ts +const { step, store, Issue } = T3; +const seen = store.entry("issues/seen", Schema.String); + +Effect.fn(function* () { + const fresh = yield* step( + "fetch", + { returns: Schema.Array(Issue) }, + Effect.gen(function* () { + const since = yield* seen.get; + const batch = yield* fetchIssuesAfter(Option.getOrUndefined(since)); + if (batch[0]) yield* seen.set(batch[0].createdAt); + return batch; + }), + ); +}); +``` + +- **Shared gate pattern (`signalAll`):** Because `signalAll` keeps nothing for late arrivals, check the switch in a `step`, then while it is on call `wait` with `{ channel: "main-green", timeout: "10 minutes", returns: Schema.Null }` and re-check in a loop. Number step names per iteration (`switch/1`, `released/1`, `switch/2`, `released/2`). Whoever clears the switch calls `signalAll({ channel: "main-green" }, null)`. +- **Transactions:** Use `entry.update` or `store.transaction` whenever a write depends on a read, or when a step might fail after writing. +- **CLI access:** Inspect or flip keys with `t3 workflow store list [prefix]`, `store set ''`, and `store delete `. + +## Issues and pull requests + +Reads and writes the project's configured tracker (GitHub, GitLab, Linear, etc.) and git host using the project's credentials. Pass an issue/PR object from a trigger or `list`, or `{ project, url }` (useful when an agent returns a URL). + +| Call | Where | Returns | +| ----------------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------- | +| `issues.list({ project, state?, labels?, query?, assignee?, sort?, limit? })` | `step` / `onEnd` | `Issue[]` (`state` defaults to `"open"`) | +| `issues.read(issue)` | `step` / `onEnd` | `IssueDetail` (body, comments, valid `states`) | +| `issues.comment(issue, body)` | `step` / `onEnd` | `void` | +| `issues.setState(issue, name)` | `step` / `onEnd` | `void` (`name` from `issues.read(issue).states`) | +| `issues.create({ project, title, body?, labels?, assignees? })` | `step` / `onEnd` | `{ key, displayKey, url }` | +| `pullRequests.list({ project, state?, query?, limit? })` | `step` / `onEnd` | `PullRequest[]` (`state` defaults to `"open"`) | +| `pullRequests.read(pr)` | `step` / `onEnd` | State, checks, reviews, mergeability | +| `pullRequests.comment(pr, body)` | `step` / `onEnd` | `void` | +| `pullRequests.act(pr, action, { mergeMethod? })` | `step` / `onEnd` | `void` (`merge`, `close`, `ready`, `update-branch`, etc.) | +| `pullRequests.wait(name, pr, { until, timeout? })` | **Body** | `Option` (`{ state, checks, mergeability, url }`) | + +Keep one comment or mutation per `step` so a retry does not post twice. + +```ts +const { workflow, title, agent, step, issues, Issue } = T3; + +workflow( + "triage", + { version: 1, payload: Issue, triggers: [issues.opened({ project: "/home/me/app" })] }, + Effect.fn(function* (issue) { + yield* title(`${issue.displayKey} ${issue.title}`); + const found = yield* agent("reproduce", { + project: "/home/me/app", + issue, + brief: `Reproduce this on main. Change nothing.\n\n${issue.url}`, + returns: Schema.Struct({ reproduced: Schema.Boolean, summary: Schema.String }), + }); + yield* step("report", { returns: Schema.Void }, issues.comment(issue, found.value.summary)); + }), +); +``` + +`pullRequests.wait` polls about once a minute. `until` is `"checks"` (no checks still pending), `"merged"`, or `"closed"`. Merging or closing ends any wait, so always check `state` before `checks` (`"passing" | "failing" | "pending" | "none"`): + +```ts +Effect.fn(function* () { + const at = yield* pullRequests.wait( + "checks", + { project, url }, + { until: "checks", timeout: "2 hours" }, + ); + if (Option.isNone(at) || at.value.state !== "open" || at.value.checks !== "passing") { + return yield* stop("not ready to merge"); + } + yield* step("merge", { returns: Schema.Void }, pullRequests.act({ project, url }, "merge")); +}); +``` + +## Triggers + +A workflow's `payload` schema must match what its `triggers` emit. + +| Trigger | Payload | Notes | +| ------------------------------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `every("1 hour")` | `Tick` | `{ scheduledAt }`. Minimum 1 minute. The first run comes one interval after the file loads, not at load. Downtime collapses into one run, not one per missed interval. | +| `daily("09:00", { weekdays?: [1, 2, 3, 4, 5] })` | `Tick` | Server local time; `0` is Sunday. Missed by more than 10 minutes is skipped. | +| `webhook("name", { key? })` | `WebhookRequest` | `{ method, headers, query, body }` (lowercase header names, text `query`/`body`). Set `payload: WebhookRequest`, taken from `T3`; never write its shape out yourself. `t3 workflow hooks` prints URL paths (includes secret). A retry that repeats a delivery header (`X-GitHub-Delivery`, `Idempotency-Key`, `webhook-id`, and the Gitea, GitLab and Linear ones) starts no second run; for other senders, `key: (r) => …` names the run from the request. Bodies over 1 MiB are refused. | +| `issues.opened({ project, labels?, query? })` | `Issue` | Polls ~once a minute. Only issues opened after the workflow first loaded. Issue must carry all `labels`. | +| `pullRequests.opened({ project, query? })` | `PullRequest` | Polls ~once a minute. Only pull requests opened after the workflow first loaded. | + +Filter unwanted deliveries in the body with `skip("not a push to main")` so they stay out of run lists. Verify webhook signatures inside a `step`. + +Start any workflow manually with `t3 workflow start --input '' --key `. A `key` identifies one run of that workflow across all versions. + +## Rules you must not break + +1. **The body is replayed from the top.** After every wait or restart, the body runs again and completed primitives return their stored values. Put all side effects, I/O, clock reads, randomness, and `store`/API reads inside `step` or `agent`. Code between calls must be deterministic given `payload` and earlier results. +2. **Names are journal keys.** Every named primitive (`step`, `agent`, `ask`, `wait`, `sleep`, `invoke`, `pullRequests.wait`) must have a unique name within the run, across all kinds. Loops need distinct names (``step(`check-${i}`, …)``). Never name a body step `"onEnd"` (reserved for cleanup). `invoke("x", …)` also takes `x/start`, and `title(…)` takes `title/0`, `title/1`, …. +3. **Bump `version` when changing a live workflow.** Do not reorder, rename, or change the stored schema of steps in a version that still has unfinished runs. Register the updated body under a higher `version` and keep the old version in the file until its runs finish. Runs started by the CLI, a trigger or a webhook use the highest version; `start` and `invoke` run the version of the definition you pass them, so point callers at the new definition when you bump. Keys still deduplicate across versions. +4. **Never import `effect`, and take every `T3` name you use.** The globals are `T3`, `Effect`, `Schema`, `Option`, `Duration` and `Schedule`; `step`, `daily`, `WebhookRequest` and the rest come from `const { … } = T3;` at the top of the file, and one left out of that line is a `ReferenceError`. Shared helpers go in a subfolder (dotfiles and folders are ignored by the loader), and changing an imported helper requires a server restart. +5. **Payloads and step results must fit their `Schema`.** Everything journaled is serialized as JSON; a value that fails encoding fails the step. +6. **Steps can run more than once.** A crash mid-step, a retry, or a manual resume re-runs the step. Make external side effects idempotent (derive idempotency keys from `payload` or `run.id`, keep one comment/post per step, wrap dependent store writes in `store.transaction`). + +## Files, reloading, and CLI + +If an edited file fails to load, its last good version keeps running and the server logs `A workflow definitions file was not loaded` with the reason. A change that defines the same `(name, version)` twice or removes a version with unfinished runs is rejected. The Workflows page shows these errors, and its Definitions view validates files on save. + +```sh +t3 workflow start --input '' --key +t3 workflow list [--status paused] +t3 workflow show [--json] +t3 workflow resume +t3 workflow cancel [--reason ''] +t3 workflow questions +t3 workflow signal '{"choice":"upgrade"}' --run --wait approve-upgrade +t3 workflow signal '' --workflow --channel +t3 workflow hooks +t3 workflow store list [prefix] +t3 workflow store set '' +t3 workflow store delete +``` + +- **Run states:** `running`, `waiting` (agent, signal, question, PR wait, or sleep), `paused` (step failed), `completed`, `stopped`, `skipped`, `cancelled`. +- **Resuming:** Check the failing step and error with `show`, fix the cause, then `resume` (only the failed step re-runs). A paused run also resumes by itself on `resumeAfter` (default 5, 20, 80 minutes), unless it paused because its agent gave up. +- **Retired runs:** A run whose version was removed shows `"retired": true` in `show --json` and cannot continue until that version is restored. +- **Stuck agents:** An agent step's thread is an ordinary thread—open it to inspect or steer the agent. The step finishes as soon as the agent submits its result. From 65d2b4f081694d76a5d335c58132abf28fe6d8c7 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:28:57 +0530 Subject: [PATCH 139/162] fix(web): center the Connections map zoom controls (#41081) --- apps/web/src/components/settings/EnvironmentsMap.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/settings/EnvironmentsMap.tsx b/apps/web/src/components/settings/EnvironmentsMap.tsx index befa3c5e19b68..5d4b2f96754c8 100644 --- a/apps/web/src/components/settings/EnvironmentsMap.tsx +++ b/apps/web/src/components/settings/EnvironmentsMap.tsx @@ -1044,7 +1044,7 @@ function FleetCanvas({ )} {/* Below the canvas, not over it: nothing on the map can end up under the controls. */} -

    +
    0} />
    diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index dbb7f6ec0a33a..2ef4d67095e55 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -26,9 +26,7 @@ import { import { useAtomMount, useAtomValue } from "@effect/atom-react"; import { Atom } from "effect/reactivity"; import { - DEFAULT_TOKENIZE_MAX_LENGTH, VirtualizedFile, - getFiletypeFromFileName, type File as FileInstance, type FileContents, type PostRenderPhase, @@ -40,9 +38,9 @@ import { type EditorFactory, type EditorOptions, } from "@pierre/diffs/edit"; -import type { WorkerPoolManager } from "@pierre/diffs/worker"; -import { EditProvider, File, Virtualizer, useWorkerPool } from "@pierre/diffs/react"; +import { EditProvider, File, Virtualizer } from "@pierre/diffs/react"; import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider"; +import { useEditableAfterHighlight } from "./useEditableAfterHighlight"; import { useFilesystemReadAccess } from "~/state/filesystem"; import { isAtomCommandInterrupted, @@ -846,43 +844,6 @@ function editableFileContents( }; } -function needsWorkerHighlight(workerPool: WorkerPoolManager | undefined, file: FileContents) { - if (workerPool?.isWorkingPool() !== true) return false; - if ((file.lang ?? getFiletypeFromFileName(file.name)) === "text") return false; - let lines = 1; - for ( - let index = file.contents.indexOf("\n"); - index !== -1; - index = file.contents.indexOf("\n", index + 1) - ) { - lines += 1; - } - return lines <= DEFAULT_TOKENIZE_MAX_LENGTH; -} - -/** Enable editing only after worker highlighting renders; active edit sessions highlight on the main - * thread. */ -function useEditableAfterHighlight(file: FileContents) { - const workerPool = useWorkerPool(); - const [highlightedFile, setHighlightedFile] = useState(null); - const needsHighlight = needsWorkerHighlight(workerPool, file); - const ready = !needsHighlight || highlightedFile === file; - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- primes the worker pool's highlight cache for this file and falls back to plain text if it fails - useEffect(() => { - if (ready || workerPool === undefined) return; - workerPool.primeFileHighlightCache(file).catch(() => setHighlightedFile(file)); - }, [file, ready, workerPool]); - - const onPostRender = (renderedFile: FileContents | undefined, phase: PostRenderPhase) => { - if (ready || phase === "unmount" || renderedFile?.cacheKey !== file.cacheKey) return; - // Cache results arrive just before instance rendering; seeing the cache during render means rows are - // highlighted. - if (workerPool?.getFileResultCache(file) !== undefined) setHighlightedFile(file); - }; - return { ready, onPostRender }; -} - interface EditableFileSurfaceProps { environmentId: EnvironmentId; projectId?: ProjectId | undefined; diff --git a/apps/web/src/components/files/useEditableAfterHighlight.ts b/apps/web/src/components/files/useEditableAfterHighlight.ts new file mode 100644 index 0000000000000..f91ef979de5c3 --- /dev/null +++ b/apps/web/src/components/files/useEditableAfterHighlight.ts @@ -0,0 +1,46 @@ +import { + DEFAULT_TOKENIZE_MAX_LENGTH, + getFiletypeFromFileName, + type FileContents, + type PostRenderPhase, +} from "@pierre/diffs"; +import { useWorkerPool } from "@pierre/diffs/react"; +import type { WorkerPoolManager } from "@pierre/diffs/worker"; +import { useEffect, useState } from "react"; + +function needsWorkerHighlight(workerPool: WorkerPoolManager | undefined, file: FileContents) { + if (workerPool?.isWorkingPool() !== true) return false; + if ((file.lang ?? getFiletypeFromFileName(file.name)) === "text") return false; + let lines = 1; + for ( + let index = file.contents.indexOf("\n"); + index !== -1; + index = file.contents.indexOf("\n", index + 1) + ) { + lines += 1; + } + return lines <= DEFAULT_TOKENIZE_MAX_LENGTH; +} + +/** Enable editing only after worker highlighting renders; active edit sessions highlight on the main + * thread. */ +export function useEditableAfterHighlight(file: FileContents) { + const workerPool = useWorkerPool(); + const [highlightedFile, setHighlightedFile] = useState(null); + const needsHighlight = needsWorkerHighlight(workerPool, file); + const ready = !needsHighlight || highlightedFile === file; + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- primes the worker pool's highlight cache for this file and falls back to plain text if it fails + useEffect(() => { + if (ready || workerPool === undefined) return; + workerPool.primeFileHighlightCache(file).catch(() => setHighlightedFile(file)); + }, [file, ready, workerPool]); + + const onPostRender = (renderedFile: FileContents | undefined, phase: PostRenderPhase) => { + if (ready || phase === "unmount" || renderedFile?.cacheKey !== file.cacheKey) return; + // Cache results arrive just before instance rendering; seeing the cache during render means rows are + // highlighted. + if (workerPool?.getFileResultCache(file) !== undefined) setHighlightedFile(file); + }; + return { ready, onPostRender }; +} diff --git a/apps/web/src/components/settings/LabsSettingsPanel.tsx b/apps/web/src/components/settings/LabsSettingsPanel.tsx index e2e33fec8fd75..f6354fb880ea0 100644 --- a/apps/web/src/components/settings/LabsSettingsPanel.tsx +++ b/apps/web/src/components/settings/LabsSettingsPanel.tsx @@ -31,6 +31,7 @@ export function LabsSettingsPanel() { {/* Clerk is only mounted when this build has T3 Connect. */} {hasCloudPublicConfig() ? : } + @@ -194,6 +195,31 @@ function LinkedEnvironmentsRow() { ); } +function WorkflowsRow() { + const searchableSetting = useSearchableSetting(); + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + const gt = useGT(); + return ( + updateSettings({ workflowsEnabled: Boolean(checked) })} + aria-label={gt("Workflows")} + /> + } + /> + ); +} + function PromptSuggestionsRow() { const searchableSetting = useSearchableSetting(); const settings = useScopedSettings(); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 4f57b8d730842..1f38ed958d368 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -559,6 +559,13 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "environment", searchTerms: [msg("beta link another machine vps peer agents work there delegate")], }, + { + id: "workflows-beta", + title: msg("Workflows"), + to: "/settings/labs", + scope: "environment", + searchTerms: [msg("beta workflow durable runs automation steps schedule webhook folder")], + }, { id: "prompt-suggestions-beta", title: msg("Suggest next prompt"), diff --git a/apps/web/src/components/sidebar/mainAppLocation.ts b/apps/web/src/components/sidebar/mainAppLocation.ts index daa18b618a41a..0ef545f76b772 100644 --- a/apps/web/src/components/sidebar/mainAppLocation.ts +++ b/apps/web/src/components/sidebar/mainAppLocation.ts @@ -11,7 +11,10 @@ export function isAppModalPage(pathname: string) { export function isSidebarUtilityPage(pathname: string) { return ( - pathname.startsWith("/projects/") || pathname === "/pull-requests" || pathname === "/issues" + pathname.startsWith("/projects/") || + pathname === "/pull-requests" || + pathname === "/issues" || + pathname === "/workflows" ); } diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts new file mode 100644 index 0000000000000..736aa4648aaf9 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { diskChange, staleAfterSave } from "./WorkflowDefinitionEditor.logic"; + +describe("diskChange", () => { + it.each([ + [ + "a clean editor follows the file", + { source: "B", baseline: "A", dirty: false, saving: null }, + "follow", + ], + [ + "edits over a change are stale", + { source: "B", baseline: "A", dirty: true, saving: null }, + "stale", + ], + [ + "the file it already holds is nothing", + { source: "A", baseline: "A", dirty: true, saving: null }, + "ignore", + ], + [ + "the save's own text is nothing", + { source: "C", baseline: "A", dirty: true, saving: "C" }, + "ignore", + ], + // The disk went A → B → A while C was being saved: back at the baseline, but not what was saved. + [ + "a change back to the baseline during a save is stale", + { source: "A", baseline: "A", dirty: true, saving: "C" }, + "stale", + ], + ] as const)("%s", (_, input, expected) => { + expect(diskChange(input)).toBe(expected); + }); +}); + +describe("staleAfterSave", () => { + it("settles the change the person saved over and keeps a newer one", () => { + const b = { source: "B" }; + expect(staleAfterSave(b, b)).toBeNull(); + const a = { source: "A" }; + expect(staleAfterSave(a, b)).toBe(a); + expect(staleAfterSave(a, null)).toBe(a); + // The disk went B → A → B while the save was out: back at the same text, but a change of its own. + const bAgain = { source: "B" }; + expect(staleAfterSave(bAgain, b)).toBe(bAgain); + }); +}); diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts new file mode 100644 index 0000000000000..c056c6576f061 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts @@ -0,0 +1,23 @@ +/** + * What a new version of the file on disk means for an editor holding `baseline`. A change that + * lands while a save is out is never the save's own unless it is the saved text itself. + */ +export function diskChange(input: { + readonly source: string; + readonly baseline: string; + readonly dirty: boolean; + readonly saving: string | null; +}): "follow" | "stale" | "ignore" { + if (input.saving !== null) return input.source === input.saving ? "ignore" : "stale"; + if (input.source === input.baseline) return "ignore"; + return input.dirty ? "stale" : "follow"; +} + +/** One change on disk the person has not settled. Each change is its own, even with the same text. */ +export interface DiskChange { + readonly source: string; +} + +/** The warning after a save: the change the person saved over is settled, any later one stays. */ +export const staleAfterSave = (now: DiskChange | null, overwrote: DiskChange | null) => + now === overwrote ? null : now; diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx b/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx new file mode 100644 index 0000000000000..da810dd5c93ac --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx @@ -0,0 +1,575 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { FileContents } from "@pierre/diffs"; +import { Editor, type EditorFactory, type EditorOptions, type Marker } from "@pierre/diffs/edit"; +import { EditProvider, File, Virtualizer } from "@pierre/diffs/react"; +import { type EnvironmentId, type WorkflowDefinitionProblem } from "@t3tools/contracts"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { useBlocker } from "@tanstack/react-router"; +import { T, useGT, Var } from "gt-react"; +import { FileCode2Icon, PlusIcon } from "lucide-react"; +import { useEffect, useRef, useState, type KeyboardEvent } from "react"; +import { createPortal } from "react-dom"; + +import { requestConfirmDialog } from "../../confirmDialog"; +import { useTheme } from "../../hooks/useTheme"; +import { resolveDiffThemeName } from "../../lib/diffRendering"; +import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting"; +import { isMacPlatform } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider"; +import { useEditableAfterHighlight } from "../files/useEditableAfterHighlight"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { type DiskChange, diskChange, staleAfterSave } from "./WorkflowDefinitionEditor.logic"; +import { WorkflowsEmpty } from "./WorkflowRunsView"; + +type DefinitionEditor = Editor<"file", undefined, undefined>; +const createEditor: EditorFactory = (editorType, options, editStateKey) => + new Editor(editorType, options, editStateKey); + +const fileOf = (path: string, contents: string, revision: number): FileContents => ({ + name: path, + contents, + cacheKey: `workflow-definition:${path}:${revision}:${contents.length}`, +}); + +/** A problem that names a line, as a squiggle under that line. */ +const markersOf = (problems: ReadonlyArray): Array => + problems.flatMap((problem) => + problem.line === undefined + ? [] + : [ + { + start: { line: problem.line - 1, character: 0 }, + end: { line: problem.line - 1, character: Number.MAX_SAFE_INTEGER }, + severity: "error" as const, + message: problem.message, + source: "workflows", + }, + ], + ); + +function ProblemList({ + title, + problems, +}: { + readonly title: string; + readonly problems: ReadonlyArray; +}) { + return ( +
    +

    {title}

    +
      + {problems.map((problem) => ( +
    • + {problem.line === undefined ? null : ( + + + Line {problem.line}: + {" "} + + )} + {problem.message} +
    • + ))} +
    +
    + ); +} + +function Surface({ + environmentId, + name, + path, + source, + revision, + onDisk, + draft, + offline, + onDelete, + onClose, + actions, +}: { + readonly environmentId: EnvironmentId; + readonly name: string; + readonly path: string; + readonly source: string; + readonly revision: number; + /** Why the file on disk is not what runs, when it is not. */ + readonly onDisk: ReadonlyArray; + /** What a file that is not on disk yet starts as. */ + readonly draft?: string; + /** The environment is away: the draft stays, and nothing is sent until it is back. */ + readonly offline: boolean; + /** Take the file away, saying whether it went. Absent where that cannot be done. */ + readonly onDelete?: (() => Promise) | undefined; + /** Leave the file for the list. */ + readonly onClose: () => void; + /** Where in the page's header the file's status and its actions go. */ + readonly actions: HTMLElement | null; +}) { + const { resolvedTheme } = useTheme(); + const gt = useGT(); + const canSave = useAtomValue( + serverEnvironment.saveWorkflowDefinition.permissionAtom(environmentId), + ); + const save = useAtomCommand(serverEnvironment.saveWorkflowDefinition, { + label: "workflow definition save", + }); + // What the draft started from. The file on disk moving past it is someone else's edit. + const [baseline, setBaseline] = useState(source); + // The file as this editor last took note of it, so only a real change on disk is acted on: after + // a save, `source` is still the old text until the server's answer is read again. + const [seen, setSeen] = useState(source); + // The disk text that changed under the person's edits, until they settle it. + const [staleAt, setStaleAt] = useState(null); + const stale = staleAt !== null; + const [shown, setShown] = useState(() => fileOf(path, draft ?? source, revision)); + const [edited, setEdited] = useState(draft ?? null); + const [problems, setProblems] = useState>([]); + // The last save wrote the file, so its problems are why it does not run, not why it was refused. + const [written, setWritten] = useState(false); + const [failure, setFailure] = useState(null); + // The text a save in flight is writing, so its own echo from disk is told from a real change. + const [savingText, setSavingText] = useState(null); + const saving = savingText !== null; + const [savedOnce, setSavedOnce] = useState(false); + const [deleting, setDeleting] = useState(false); + // Set once the file is deleted, so leaving it does not ask about a draft of a file that is gone. + const released = useRef(false); + const [seenRevision, setSeenRevision] = useState(revision); + const editorRef = useRef(null); + const dirty = edited !== null && edited !== baseline; + const adopt = () => { + setBaseline(source); + setShown(fileOf(path, source, revision)); + setEdited(null); + setProblems([]); + setStaleAt(null); + }; + if (source !== seen) { + setSeen(source); + // With nothing of the person's own in the editor, it follows the file. + const change = diskChange({ source, baseline, dirty, saving: savingText }); + if (change === "stale") setStaleAt({ source }); + else if (change === "follow") adopt(); + } + // Why a saved file did not run is old news once the server loads it cleanly. + if (revision !== seenRevision) { + setSeenRevision(revision); + if (written && onDisk.length === 0) setProblems([]); + } + const { ready: editable, onPostRender } = useEditableAfterHighlight(shown); + + const saveNow = async () => { + if (!dirty || saving || deleting || offline || !canSave || edited === null) return; + // Saving over a change on disk that was already shown is a choice. One that lands while this + // save is out is not, and stays shown. + const overwrote = staleAt; + setSavingText(edited); + setFailure(null); + const result = await save({ environmentId, input: { name, source: edited } }); + setSavingText(null); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) setFailure(String(squashAtomCommandFailure(result))); + return; + } + setProblems(result.value.problems); + setWritten(result.value.changed); + if (!result.value.changed) return; + setBaseline(edited); + setStaleAt((now) => staleAfterSave(now, overwrote)); + setSavedOnce(true); + }; + const onKeyDown = (event: KeyboardEvent) => { + const mac = isMacPlatform(navigator.platform); + if (event.key.toLowerCase() !== "s" || !(mac ? event.metaKey : event.ctrlKey)) return; + event.preventDefault(); + void saveNow(); + }; + const deleteNow = async () => { + if (onDelete === undefined || deleting || saving) return; + // Busy from the dialog on, so a save cannot slip in while it asks. + setDeleting(true); + const gone = await onDelete(); + setDeleting(false); + if (!gone) return; + released.current = true; + onClose(); + }; + // Leaving with an unsaved draft, by a link in the app or by closing the tab, asks first. + useBlocker({ + shouldBlockFn: async () => + dirty && + !released.current && + !(await (requestConfirmDialog( + gt("Leave without saving? Your changes to this file are lost."), + { + variant: "destructive", + }, + ) ?? Promise.resolve(false))), + enableBeforeUnload: () => dirty && !released.current, + }); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the editor draws markers itself and takes them only through its own method + useEffect(() => { + editorRef.current?.setMarkers(markersOf(problems)); + }, [problems]); + + const editorOptions: EditorOptions<"file", undefined, undefined> = { + onAttach: (editor) => { + editorRef.current = editor; + editor.setMarkers(markersOf(problems)); + }, + onComplete: () => { + editorRef.current = null; + }, + }; + const status = offline + ? gt("Not connected") + : saving + ? gt("Checking…") + : dirty + ? gt("Unsaved changes") + : savedOnce && problems.length === 0 + ? gt("Saved and running") + : null; + + return ( +
    + {actions === null + ? null + : createPortal( + <> + + {canSave || offline ? status : gt("Read-only")} + + {canSave && onDelete !== undefined ? ( + + ) : null} + {canSave ? ( + + ) : null} + , + actions, + )} + {stale ? ( +
    + + The file changed on disk while you were editing. Saving replaces that change. + + +
    + ) : null} + {onDisk.length > 0 && problems.length === 0 ? ( + + ) : null} + {problems.length > 0 ? ( + + ) : null} + {failure === null ? null : ( + + )} + + + setEdited(file.contents)} + options={{ + disableFileHeader: true, + overflow: "scroll", + theme: resolveDiffThemeName(resolvedTheme), + preferredHighlighter: PREFERRED_HIGHLIGHTER, + themeType: resolvedTheme, + onPostRender: (_container, instance, phase) => onPostRender(instance.file, phase), + }} + className="min-h-full" + /> + + +
    + ); +} + +const NEW_FILE = `const { workflow, step, agent, ask, stop } = T3; + +workflow( + "my-workflow", + { version: 1, payload: Schema.Struct({}) }, + Effect.fn(function* () { + // yield* agent("first", { project: "/path/to/project", brief: "What to do." }); + }), +); +`; + +/** + * The files that define this server's workflows: the list of them, or `file` in an editor. A + * `file` the folder does not have yet is a new one, which exists once it is saved. + */ +export default function WorkflowDefinitionEditor({ + environmentId, + file, + away, + onOpen, + actions, +}: { + readonly environmentId: EnvironmentId; + readonly file: string | null; + /** The environment's name while it is not connected. */ + readonly away: string | null; + readonly onOpen: (file: string | null) => void; + readonly actions: HTMLElement | null; +}) { + const query = useEnvironmentQuery( + serverEnvironment.workflowDefinition({ environmentId, input: {} }), + ); + const canChange = useAtomValue( + serverEnvironment.saveWorkflowDefinition.permissionAtom(environmentId), + ); + const remove = useAtomCommand(serverEnvironment.deleteWorkflowDefinition, { + label: "workflow definition delete", + }); + const gt = useGT(); + const [naming, setNaming] = useState(null); + // What the last delete said, on the page it belongs to: the file, or the list once it is gone. + const [refusal, setRefusal] = useState<{ + readonly at: string | null; + readonly problems: ReadonlyArray; + readonly deleted: boolean; + } | null>(null); + // Data already read stays on screen through a failed refresh or a dropped connection. + if (!query.data) { + if (away !== null) { + return ( + + ); + } + if (query.error) { + return ( + + ); + } + return ( +

    + Loading the workflow files… +

    + ); + } + const { directory, single, files, problems, revision } = query.data; + const open = (next: string | null) => { + setRefusal(null); + onOpen(next); + }; + const begin = () => { + const wanted = (naming ?? "").trim(); + if (wanted === "") return; + setNaming(null); + open(/\.(ts|mts|js|mjs)$/.test(wanted) ? wanted : `${wanted}.ts`); + }; + const removeFile = async (target: string) => { + const confirmed = await (requestConfirmDialog( + gt("Delete {file}? The workflows it defines can no longer be started.", { file: target }), + { variant: "destructive" }, + ) ?? Promise.resolve(false)); + if (!confirmed) return false; + const result = await remove({ environmentId, input: { name: target } }); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) { + setRefusal({ + at: target, + problems: [{ message: String(squashAtomCommandFailure(result)) }], + deleted: false, + }); + } + return false; + } + const { changed } = result.value; + setRefusal( + result.value.problems.length === 0 + ? null + : { at: changed ? null : target, problems: result.value.problems, deleted: changed }, + ); + return changed; + }; + const refused = refusal !== null && refusal.at === file ? refusal : null; + const between = ( + <> + {away === null ? null : ( +
    + {gt("{name} is not connected. What you write here stays, and saves once it is back.", { + name: away, + })} +
    + )} + {query.error === null || away !== null ? null : ( + + )} + {problems.length === 0 && refused === null ? null : ( + + )} + + ); + + if (file !== null) { + const shown = files.find((candidate) => candidate.name === file) ?? null; + return ( +
    + {between} + + removeFile(file)} + onClose={() => onOpen(null)} + actions={actions} + /> + +
    + ); + } + + return ( +
    + {between} +
    +
    +
    +

    + + Every file in{" "} + + {directory} + {" "} + defines workflows. A change to one is picked up without a restart. + +

    + {single || !canChange ? null : naming === null ? ( + + ) : ( + { + event.preventDefault(); + begin(); + }} + > + setNaming(event.target.value)} + onKeyDown={(event) => { + if (event.key === "Escape") setNaming(null); + }} + /> + + + )} +
    + {files.length === 0 ? ( +

    + + No workflows yet. Make the first file here, or ask an agent to write one in that + folder. + +

    + ) : ( +
      + {files.map((candidate) => ( +
    • + +
    • + ))} +
    + )} +
    +
    +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowPane.tsx b/apps/web/src/components/workflows/WorkflowPane.tsx new file mode 100644 index 0000000000000..e23d5de8a50c7 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowPane.tsx @@ -0,0 +1,179 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { workflowReferenceLabel } from "@t3tools/client-runtime/workflows"; +import { EnvironmentId, ThreadId, type WorkflowRunReference } from "@t3tools/contracts"; +import { useGT } from "gt-react"; +import { BotIcon, Maximize2Icon, XIcon } from "lucide-react"; + +import { cn } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { Button } from "../ui/button"; +import { + activeWorkflowPaneIndex, + closeWorkflowPaneTab, + openWorkflowPaneTab, + type WorkflowPaneState, + type WorkflowPaneTab, +} from "./workflowPane.logic"; +import { + useOpenReferencePage, + WorkflowReferenceMark, + WorkflowReferencePanel, +} from "./WorkflowReferences"; +import WorkflowThreadPane, { + useOpenThreadPage, + WorkflowThreadTabLabel, +} from "./WorkflowThreadPane"; + +/** + * The pane beside a run: a tab per transcript or reference opened from it. Only the tab that + * shows is mounted, so a pane with a chat and two pull requests renders one of them. + */ +export default function WorkflowPane({ + environmentId, + runId, + state, + onChange, +}: { + readonly environmentId: EnvironmentId; + readonly runId: string | null; + readonly state: WorkflowPaneState; + readonly onChange: (next: WorkflowPaneState) => void; +}) { + const gt = useGT(); + const detail = useEnvironmentQuery( + runId === null ? null : serverEnvironment.workflowRun({ environmentId, input: { runId } }), + ); + const openThreadPage = useOpenThreadPage(); + const openReferencePage = useOpenReferencePage(environmentId); + const tabs = state.pane ?? []; + const activeIndex = activeWorkflowPaneIndex(state); + const active = tabs[activeIndex]; + const threadOf = (tab: Extract) => + scopeThreadRef( + tab.env === undefined ? environmentId : EnvironmentId.make(tab.env), + ThreadId.make(tab.thread), + ); + const referenceOf = (tab: Extract) => + detail.data?.references.find( + (reference) => reference.kind === tab.kind && reference.key === tab.key, + ) ?? null; + const activeReference = active === undefined || "thread" in active ? null : referenceOf(active); + const openFull = + active === undefined + ? null + : "thread" in active + ? () => openThreadPage(threadOf(active)) + : activeReference === null + ? null + : openReferencePage(activeReference); + + return ( +
    +
    +
    + {tabs.map((tab, index) => ( +
    + + +
    + ))} +
    + {openFull === null ? null : ( + + )} + +
    +
    + {active === undefined ? null : "thread" in active ? ( + + ) : activeReference !== null ? ( + + ) : ( +

    + {detail.data === null ? gt("Loading…") : gt("This run no longer lists it.")} +

    + )} +
    +
    + ); +} + +function ReferenceTabLabel({ + reference, + fallback, +}: { + readonly reference: WorkflowRunReference | null; + readonly fallback: string; +}) { + if (reference === null) return {fallback}; + return ( + <> + + {workflowReferenceLabel(reference)} + + ); +} diff --git a/apps/web/src/components/workflows/WorkflowReferences.tsx b/apps/web/src/components/workflows/WorkflowReferences.tsx new file mode 100644 index 0000000000000..df89ecc7086cf --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowReferences.tsx @@ -0,0 +1,193 @@ +import { + workflowReferenceIssue, + workflowReferenceLabel, + workflowReferencePullRequest, +} from "@t3tools/client-runtime/workflows"; +import type { EnvironmentId, WorkflowRunReference } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { T } from "gt-react"; +import { CircleCheckIcon, CircleDotIcon, ExternalLinkIcon, LinkIcon } from "lucide-react"; + +import { isElectron } from "~/env"; +import { isTerminalFocused } from "../../lib/terminalFocus"; +import { cn } from "../../lib/utils"; +import { ISSUES_PANEL_REF, useRightPanelStore } from "../../rightPanelStore"; +import { IssueDetailPanel } from "../issue/IssueDetailPanel"; +import { readIssueListPreferences } from "../issue/issueListPreferences"; +import { PullRequestDetailPanel } from "../pullRequest/PullRequestDetailPanel"; +import { PULL_REQUEST_STATE_PRESENTATION } from "../pullRequest/pullRequestIcons"; +import { Button } from "../ui/button"; + +/** The mark a reference wears: its kind's icon, in the ink its state has on its own page. */ +function referenceGlyph(reference: WorkflowRunReference) { + if (workflowReferencePullRequest(reference) !== null) { + const state = + reference.state === "closed" || reference.state === "merged" ? reference.state : "open"; + return PULL_REQUEST_STATE_PRESENTATION[state]; + } + if (workflowReferenceIssue(reference) !== null) { + return reference.state === "closed" + ? { + Icon: CircleCheckIcon, + toneClassName: PULL_REQUEST_STATE_PRESENTATION.merged.toneClassName, + } + : { Icon: CircleDotIcon, toneClassName: PULL_REQUEST_STATE_PRESENTATION.open.toneClassName }; + } + return { Icon: LinkIcon, toneClassName: "text-muted-foreground" }; +} + +export function WorkflowReferenceMark({ reference }: { readonly reference: WorkflowRunReference }) { + const glyph = referenceGlyph(reference); + return ; +} + +/** A thing the run touched, as a chip that opens it beside the run. */ +export function WorkflowReferenceChip({ + reference, + open, + small = false, + onOpen, +}: { + readonly reference: WorkflowRunReference; + /** It shows in the pane now, so another click closes it. */ + readonly open: boolean; + /** On a step, where the label is enough. */ + readonly small?: boolean; + readonly onOpen: () => void; +}) { + const label = workflowReferenceLabel(reference); + const title = reference.title === label ? "" : reference.title; + const name = title === "" ? label : `${label} ${title}`; + return ( + + ); +} + +const shortcutContext = () => ({ + terminalFocus: isTerminalFocused(), + terminalOpen: false, + previewFocus: false, + previewOpen: false, + isWeb: !isElectron, + isDesktop: isElectron, +}); + +/** Opens the reference on its own page, where it has the whole window. Null for a kind with none. */ +export function useOpenReferencePage( + environmentId: EnvironmentId, +): (reference: WorkflowRunReference) => (() => void) | null { + const navigate = useNavigate(); + return (reference) => { + const issue = workflowReferenceIssue(reference); + if (issue !== null) { + return () => { + // The Issues page shows the issue its panel has open; the address keeps the list's place. + useRightPanelStore.getState().openIssue(ISSUES_PANEL_REF, { + environmentId, + projectId: issue.projectId, + tracker: issue.tracker, + ...(issue.host === undefined ? {} : { host: issue.host }), + scope: issue.scope, + key: issue.key, + ...(reference.url === null ? {} : { url: reference.url }), + }); + void navigate({ + to: "/issues", + search: { + ...readIssueListPreferences(), + selectedEnvironmentId: environmentId, + selectedProjectId: issue.projectId, + ...(issue.host === undefined ? {} : { selectedHost: issue.host }), + tracker: issue.tracker, + scope: issue.scope, + key: issue.key, + }, + }); + }; + } + const pullRequest = workflowReferencePullRequest(reference); + if (pullRequest !== null) { + return () => + void navigate({ + to: "/pull-requests", + search: { + involvement: "all", + state: "all", + repository: pullRequest.repository, + number: pullRequest.number, + ...(pullRequest.host === undefined ? {} : { selectedHost: pullRequest.host }), + selectedProjectId: pullRequest.projectId, + selectedEnvironmentId: environmentId, + }, + }); + } + return null; + }; +} + +/** A reference opened beside its run: the Issues or Pull requests page's own view of it. */ +export function WorkflowReferencePanel({ + environmentId, + reference, +}: { + readonly environmentId: EnvironmentId; + readonly reference: WorkflowRunReference; +}) { + const issue = workflowReferenceIssue(reference); + if (issue !== null) { + return ; + } + const pullRequest = workflowReferencePullRequest(reference); + if (pullRequest !== null) { + return ( + + ); + } + // A kind this client does not know yet: what the run knows of it, and where it lives. + return ( +
    +

    + {reference.title === "" ? workflowReferenceLabel(reference) : reference.title} +

    +

    + + {reference.kind} + {reference.state === null ? null : ( + <> + · + {reference.state} + + )} +

    + {reference.url === null ? null : ( + + )} +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowRunFeed.tsx b/apps/web/src/components/workflows/WorkflowRunFeed.tsx new file mode 100644 index 0000000000000..d77b54d8dcc11 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunFeed.tsx @@ -0,0 +1,1924 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, + type AtomCommandResult, +} from "@t3tools/client-runtime/state/runtime"; +import { + EnvironmentId, + ThreadId, + type WorkflowQuestion, + type WorkflowRun, + type WorkflowRunReference, +} from "@t3tools/contracts"; +import { formatModelSlugName } from "@t3tools/shared/model"; +import { formatDuration } from "@t3tools/shared/orchestrationTiming"; +import { msg, T, useGT, useMessages, Var } from "gt-react"; +import { + ArrowLeftIcon, + ArrowUpRightIcon, + ChevronRightIcon, + BotIcon, + CheckIcon, + CircleAlertIcon, + HourglassIcon, + MoonIcon, + SquareIcon, +} from "lucide-react"; +import { secondTick } from "@t3tools/client-runtime/clock"; +import { + createContext, + useContext, + useRef, + useState, + useSyncExternalStore, + type ReactNode, +} from "react"; + +import { requestConfirmDialog } from "../../confirmDialog"; +import { useNowMinute } from "../../hooks/useNowMinute"; +import { cn } from "../../lib/utils"; +import { useQuietThreadShell } from "../../state/entities"; +import { useEnvironment, useEnvironmentProviders } from "../../state/environments"; +import { type MessageResolver } from "../../i18n/messages"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { formatRelativeTimeLabel } from "../../timestampFormat"; +import ChatMarkdown from "../ChatMarkdown"; +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { stackedThreadToast, toastManager } from "../ui/toast"; +import { + buildWorkflowFeed, + buildWorkflowTimeline, + readWorkflowQuestion, + workflowAgentSummary, + workflowAnswer, + workflowChip, + workflowFlowFocus, + workflowPausedBeat, + workflowResultLines, + workflowRunNow, + workflowRunState, + workflowSaidStart, + workflowStepReferences, + workflowStepTime, + workflowOneLine, + type WorkflowBeat, + type WorkflowFeedRow, + type WorkflowQuickSteps, + type WorkflowRunNode, + type WorkflowRunTone, +} from "@t3tools/client-runtime/workflows"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { WorkflowReferenceChip } from "./WorkflowReferences"; + +/** An agent's thread, as a step names it: the linked environment it is in, or null for this one. */ +export interface WorkflowThreadTarget { + readonly threadId: string; + readonly environmentId: string | null; +} + +// An agent that wrote a page gets a few lines of it; the rest is a click away. +const SAID_SHOWN = 320; + +// What waits on a person is what they came for, so it is in view when the run opens. +const revealOnMount = (element: HTMLElement | null) => { + element?.scrollIntoView({ block: "nearest" }); +}; + +function reportFailure(title: string, result: AtomCommandResult) { + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + toastManager.add( + stackedThreadToast({ + type: "error", + title, + description: String(squashAtomCommandFailure(result)), + }), + ); +} + +// Reads the minute tick because the compiler caches a render-time Date.now() on the timestamp. +function useNowMs(): number { + return Date.parse(`${useNowMinute()}:00.000Z`); +} + +// A time still counting is told to the second: its tenths would only flicker. +const wholeSeconds = (ms: number) => Math.max(1000, Math.round(ms / 1000) * 1000); +const elapsedOf = (beat: WorkflowBeat) => + beat.status === "running" ? wholeSeconds(beat.endMs - beat.startMs) : beat.endMs - beat.startMs; + +const never = () => () => {}; +const noTick = () => 0; + +/** The clock a run is told by: to the second while it is under way, to the minute after. */ +function useRunNowMs(live: boolean): number { + const minute = useNowMs(); + const second = useSyncExternalStore( + live ? secondTick.subscribe : never, + live ? secondTick.getSnapshot : noTick, + live ? secondTick.getSnapshot : noTick, + ); + return live ? second : minute; +} + +export function RelativeLabel({ value }: { readonly value: string }) { + return formatRelativeTimeLabel(value, useNowMs()); +} + +const CHIP_TONES = [ + "bg-sky-500/15 text-sky-700 dark:text-sky-300", + "bg-violet-500/15 text-violet-700 dark:text-violet-300", + "bg-amber-500/15 text-amber-700 dark:text-amber-300", + "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300", + "bg-rose-500/15 text-rose-700 dark:text-rose-300", +] as const; + +/** Which workflow a run is of, at a glance: the same letters and colour wherever it shows. */ +export function WorkflowChip({ name }: { readonly name: string }) { + const chip = workflowChip(name); + return ( + + {chip.letters} + + ); +} + +// The thread list's own colours for the same states, so a run reads like a thread does. +const WORKFLOW_TONE_CLASS: Record = { + input: "text-warning-foreground", + failed: "text-destructive", + working: "text-info-foreground", + quiet: "text-muted-foreground", + done: "text-success-foreground", +}; + +export function WorkflowStateWord({ node }: { readonly node: WorkflowRunNode }) { + const m = useMessages(); + const state = workflowRunState(node, m); + return ( + + {state.tone === "working" ? ( + + ) : state.tone === "done" ? ( + + ) : null} + {state.word} + + ); +} + +const nthTry = (count: number, resolve: MessageResolver) => + resolve( + msg("{count, plural, =1 {1st try} =2 {2nd try} =3 {3rd try} other {{count}th try}}", { + count, + }), + ); + +// The loading view and the timeline each draw a question's card, so a reason typed while the +// steps load is kept here rather than in the card that is about to be replaced. +const AnswerDrafts = createContext<{ + readonly get: (key: string) => string | null; + readonly set: (key: string, reason: string | null) => void; +} | null>(null); + +export function WorkflowRunFeed({ + environmentId, + node, + parent, + shownTab, + onSelect, + onOpenThread, + onOpenReference, +}: { + readonly environmentId: EnvironmentId; + readonly node: WorkflowRunNode; + readonly parent: WorkflowRun | null; + /** What shows beside the run, so the card or chip that opened it can say so. */ + readonly shownTab: WorkflowPaneTab | null; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + readonly onOpenReference: (reference: WorkflowRunReference) => void; +}) { + const { run } = node; + const gt = useGT(); + const clockMs = useRunNowMs(node.run.endedAt === null); + // An ended run's last step can still read as running for a moment; it ran until the run ended. + const nowMs = node.run.endedAt === null ? clockMs : Date.parse(node.run.endedAt); + const panel = useRef(null); + const [picked, setPicked] = useState(null); + // Steps already there when the run opens are simply shown; only later ones arrive with motion. + const [openedAtMs] = useState(() => Date.now()); + const detail = useEnvironmentQuery( + serverEnvironment.workflowRun({ environmentId, input: { runId: run.runId } }), + ); + const canResume = useAtomValue(serverEnvironment.resumeWorkflowRun.permissionAtom(environmentId)); + const canCancel = useAtomValue(serverEnvironment.cancelWorkflowRun.permissionAtom(environmentId)); + const resume = useAtomCommand(serverEnvironment.resumeWorkflowRun, { label: "workflow resume" }); + const cancel = useAtomCommand(serverEnvironment.cancelWorkflowRun, { label: "workflow cancel" }); + const [busy, setBusy] = useState(false); + const target = { environmentId, input: { runId: run.runId } }; + const [drafts, setDrafts] = useState>(() => new Map()); + const answerDrafts = { + get: (key: string) => drafts.get(key) ?? null, + set: (key: string, reason: string | null) => + setDrafts((current) => { + const next = new Map(current); + if (reason === null) next.delete(key); + else next.set(key, reason); + return next; + }), + }; + const resumeRun = async () => { + if (busy) return; + setBusy(true); + const result = await resume(target); + setBusy(false); + reportFailure(gt("Could not resume the run"), result); + }; + const cancelRun = async () => { + if (busy) return; + // Busy while the dialog is up, so a second click does not open a second one. + setBusy(true); + const confirmed = await (requestConfirmDialog( + gt("Cancel {title}? Its agents stop and the run cannot be resumed.", { title: run.title }), + { variant: "destructive" }, + ) ?? Promise.resolve(false)); + if (!confirmed) return setBusy(false); + const result = await cancel(target); + setBusy(false); + reportFailure(gt("Could not cancel the run"), result); + }; + const ended = run.endedAt !== null; + const ranMs = ended + ? Date.parse(run.endedAt) - Date.parse(run.startedAt) + : wholeSeconds(nowMs - Date.parse(run.startedAt)); + const steps = detail.data?.steps; + const references = detail.data?.references ?? []; + // An open transcript is one thread in one environment; `env` is absent for the run's own. + const openThread = shownTab !== null && "thread" in shownTab ? shownTab : null; + const chip = (reference: WorkflowRunReference, small = false) => ( + onOpenReference(reference)} + /> + ); + const feed = + steps === undefined + ? null + : buildWorkflowFeed( + buildWorkflowTimeline({ + run, + steps, + children: node.children.map((child) => child.run), + nowMs, + }), + ); + const beats = (feed ?? []).flatMap((row) => + row.kind === "quick" ? [] : row.kind === "together" ? row.beats : [row], + ); + // A question is told where it was asked. One whose step is not in the list yet still shows. + const questionOf = (beat: WorkflowBeat) => + beat.kind === "ask" && beat.status === "running" + ? (node.questions.find((question) => question.name === beat.name) ?? null) + : null; + const loose = node.questions.filter( + (question) => !beats.some((beat) => questionOf(beat) === question), + ); + const pausedAt = feed === null ? null : workflowPausedBeat(feed, run.status); + const pause = (name: string | null, attempts: number, reason: string | null) => ( + void resumeRun()} + kept={(steps ?? []).some((step) => step.status === "completed")} + /> + ); + const beatCard = (beat: WorkflowBeat) => { + if (beat === pausedAt) { + // The step's own card stays, so its transcript can be read before resuming. + return ( +
    + {pause(beat.name, beat.attempts, beat.detail ?? run.detail)} + {stepCard(beat)} +
    + ); + } + return stepCard(beat); + }; + const stepCard = (beat: WorkflowBeat) => ( + child.run.runId === beat.childRun?.runId) ?? null} + nowMs={nowMs} + open={ + beat.thread !== null && + openThread !== null && + beat.thread.threadId === openThread.thread && + (beat.thread.environmentId ?? undefined) === openThread.env + } + onSelect={onSelect} + onOpenThread={onOpenThread} + /> + ); + const resultLines = workflowResultLines(run.result); + const pausedApart = run.status === "paused" && pausedAt === null; + const keys = new Set([ + ...(feed ?? []).flatMap((row) => (row.kind === "quick" ? [`quick:${row.steps[0]?.name}`] : [])), + ...beats.map((beat) => `step:${beat.name}`), + ...loose.map((question) => `question:${question.name}`), + ...(pausedApart ? ["pause"] : []), + ...(ended ? ["end"] : []), + ]); + // A run that finished opens on what it came to: its result when that says more than the last + // answer, else the last agent's reply. The header already says it is done. + const lastAnswer = beats.findLast((beat) => beat.kind === "ask" && beat.status === "completed"); + const answered = lastAnswer === undefined ? null : workflowAnswer(lastAnswer.result); + const resultSaysMore = + resultLines.length > 0 && + !(resultLines.length === 1 && answered !== null && resultLines[0]?.value === answered.choice); + const latest = (found: ReadonlyArray) => + found.reduce( + (best, beat) => (best === undefined || beat.endMs >= best.endMs ? beat : best), + undefined, + ); + const lastAgent = latest( + beats.filter((beat) => beat.kind === "agent" && beat.status === "completed"), + ); + const finishedFocus = + run.status !== "completed" || resultSaysMore || lastAgent === undefined + ? "end" + : `step:${lastAgent.name}`; + const focus = + picked !== null && keys.has(picked) + ? picked + : feed === null + ? null + : ended + ? finishedFocus + : workflowFlowFocus({ + rows: feed, + status: run.status, + ended, + questions: node.questions.map((question) => question.name), + }); + const pick = (key: string) => { + const asks = + key.startsWith("question:") || + beats.some((beat) => `step:${beat.name}` === key && questionOf(beat) !== null); + setPicked(asks ? null : key); + // Below the flow on a narrow page, so picking a step brings what it shows into view; a + // question is answered where it is, so the page stays put. + if (!asks) panel.current?.scrollIntoView({ block: "nearest" }); + }; + const endWord = + run.status === "completed" + ? gt("Finished", { $context: "how a workflow run ended" }) + : run.status === "stopped" + ? gt("Stopped", { $context: "how a workflow run ended" }) + : run.status === "skipped" + ? gt("Skipped", { $context: "how a workflow run ended" }) + : gt("Cancelled", { $context: "how a workflow run ended" }); + // A question is answered where it was asked, so beside it is what led up to it. + const asking = + focus !== null && + (focus.startsWith("question:") || + beats.some( + (beat) => + `step:${beat.name}` === focus && + // Answered, its question is gone a moment before the step itself says it is done. + (questionOf(beat) !== null || (beat.kind === "ask" && beat.status === "running")), + )); + // The latest agent's reply is what a person weighs before answering; failing that, the last + // step that left something behind. A sleep or a wait has nothing to say. + const before = asking + ? (latest(beats.filter((beat) => beat.kind === "agent" && beat.status !== "running")) ?? + beats.findLast( + (beat) => + beat.status !== "running" && + beat.kind !== "ask" && + beat.kind !== "sleep" && + beat.kind !== "wait", + ) ?? + null) + : null; + const shown = asking ? (before === null ? null : `step:${before.name}`) : focus; + const shownBeat = beats.find((beat) => `step:${beat.name}` === shown); + const shownQuick = (feed ?? []).find( + (row) => row.kind === "quick" && `quick:${row.steps[0]?.name}` === shown, + ); + + return ( + +
    +
    + + {parent === null ? null : ( + + )} +
    +

    {run.title}

    + + {ended ? null : ( + + )} +
    +

    + + {run.workflow} + · + + + started{" "} + + + + + + {run.status === "paused" ? null : ( + <> + · + + {ended + ? gt("took {duration}", { duration: formatDuration(ranMs) }) + : gt("{duration} so far", { duration: formatDuration(ranMs) })} + + + )} + {run.retired ? ( + <> + · + + its version is no longer registered + + + ) : null} +

    + {references.length === 0 ? null : ( +
      + {references.map((reference) => ( +
    • + {chip(reference, reference.title !== "" && run.title.includes(reference.title))} +
    • + ))} +
    + )} +
    + + {detail.error || + feed === null || + (feed.length === 0 && run.status === "paused" && loose.length === 0) ? ( + <> + {detail.error ? ( +

    {detail.error}

    + ) : feed === null ? ( +

    + Loading steps… +

    + ) : null} + {/* A question the run already asks is answerable without its step history. */} + {run.status === "paused" ? ( +
    +
    {pause(null, run.pauses, run.detail)}
    +
    + ) : null} + {node.questions.map((question) => ( +
    + +
    + ))} + + ) : ( +
    + +
    + {shownBeat !== undefined ? ( + // Keyed by the step: a reason typed for one question must not follow to the next. +
    + {beatCard(shownBeat)} + {(() => { + // With one reference, the header already says it. + const touched = + references.length > 1 + ? workflowStepReferences(references, shownBeat.name) + : []; + return touched.length === 0 ? null : ( +
    + {touched.map((reference) => chip(reference, true))} +
    + ); + })()} +
    + ) : shownQuick !== undefined && shownQuick.kind === "quick" ? ( + + ) : asking ? null : focus === "pause" ? ( + pause(null, run.pauses, run.detail) + ) : focus === "end" ? ( + + + ) : null + } + name={endWord} + sub={} + /> + {run.status !== "completed" && run.detail ? ( +

    {run.detail}

    + ) : null} + +
    + ) : ( +

    + Nothing yet. +

    + )} +
    +
    + )} +
    +
    + ); +} + +type StepTone = "working" | "input" | "quiet" | "done" | "failed" | "ended"; + +// Colour says what is live: blue for work under way, amber for a person's turn. Done is quiet. +const RING: Record = { + working: "stroke-info", + input: "stroke-warning", + quiet: "stroke-muted-foreground/60", + done: "stroke-muted-foreground/45", + failed: "stroke-destructive", + ended: "stroke-muted-foreground/60", +}; + +const VERB_TONE = { + working: "text-info-foreground", + input: "text-warning-foreground", + quiet: "text-muted-foreground", + failed: "text-destructive", +} as const; + +/** + * A step's place on the rail: a ring, filled while it works, ticked when it is done. `pulse` and + * `draw` never change for a step, so each plays once, when its part of the mark first appears. + */ +function StepMark({ + tone, + pulse, + draw, +}: { + readonly tone: StepTone; + /** It started while the run was open here. */ + readonly pulse: boolean; + /** It ended while the run was open here. */ + readonly draw: boolean; +}) { + const live = tone === "working" || tone === "input"; + return ( + + {live && pulse ? ( + + ) : null} + + + {live || tone === "quiet" ? ( + + ) : tone === "done" ? ( + + ) : tone === "failed" ? ( + + ) : ( + + )} + + + ); +} + +/** One line of the run: its mark on the rail, name, what it is doing, a word on how it went, its time. */ +function TimelineRow({ + tone, + enters, + draw, + lead, + name, + note, + verb, + verbTone = "working", + aside, + asideTone, + duration, + selected, + current = false, + onPick, + sub = false, +}: { + readonly tone: StepTone; + /** It started while the run was open here, so it arrives instead of just being there. */ + readonly enters: boolean; + /** It ended while the run was open here. */ + readonly draw: boolean; + /** A small mark before the name, such as the agent's provider. */ + readonly lead?: ReactNode; + readonly name: string; + /** A quieter word after the name, such as the agent's model. */ + readonly note?: string | null; + readonly verb?: string | null; + readonly verbTone?: keyof typeof VERB_TONE; + readonly aside?: string | null; + readonly asideTone?: "failed"; + readonly duration?: string | null; + readonly selected: boolean; + /** The pane beside the timeline shows it. */ + readonly current?: boolean; + readonly onPick: () => void; + /** A step of a fork, hanging off the branch rather than the rail. */ + readonly sub?: boolean; +}) { + const live = tone === "working" || tone === "input"; + return ( + + ); +} + +/** The rail beside a row: from the row above to this mark, and on to the next unless it is last. */ +function Rail({ first, last }: { readonly first: boolean; readonly last: boolean }) { + return ( + + ); +} + +// A fork leaves the rail under its mark, runs through each step's dot, and rejoins the rail. +// The rail's centre is 10px in and a step's dot 39px in; the mark ends 26px down, the first dot +// sits 46px down, and each dot is 14px below its own row's top. +function BranchOut() { + return ( + + + + ); +} + +function BranchBack() { + return ( + <> + + + + + + ); +} + +/** + * The run as it went, one line per step that took time or involved someone. Steps that ran at once + * hang off a branch. It never draws what comes next: a run can branch, so the rail just goes on. + */ +function WorkflowTimeline({ + environmentId, + rows, + node, + nowMs, + focus, + onPick, + loose, + paused, + end, + question, + onOpenThread, + openedAtMs, + current, +}: { + readonly environmentId: EnvironmentId; + readonly rows: ReadonlyArray; + readonly node: WorkflowRunNode; + readonly nowMs: number; + readonly focus: string | null; + readonly onPick: (key: string) => void; + /** Questions whose step is not in the list yet. */ + readonly loose: ReadonlyArray; + /** The run is paused, and not at a step that failed. */ + readonly paused: boolean; + /** How the run ended, once it has. */ + readonly end: string | null; + /** What it ended with, in a few words. */ + /** The question a step waits on a person for, answered right under it. */ + readonly question: (beat: WorkflowBeat) => WorkflowQuestion | null; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + /** When this run was opened here: only what changes after that arrives with motion. */ + readonly openedAtMs: number; + /** What the pane beside the timeline shows. */ + readonly current: string | null; +}) { + const gt = useGT(); + const completed = node.run.status === "completed"; + const ask = (asked: WorkflowQuestion) => ( +
    + +
    + ); + const beatRow = (beat: WorkflowBeat, sub = false) => ( + child.run.runId === beat.childRun?.runId) ?? null} + asks={node.questions.some((asked) => asked.name === beat.name)} + nowMs={nowMs} + selected={focus === `step:${beat.name}`} + current={current === `step:${beat.name}`} + onPick={() => onPick(`step:${beat.name}`)} + sub={sub} + openedAtMs={openedAtMs} + /> + ); + const items: Array<{ + readonly key: string; + readonly body: ReactNode; + /** Its steps hang off a branch, which carries the rail past them. */ + readonly branch?: boolean; + }> = []; + for (const row of rows) { + if (row.kind === "quick") { + const key = `quick:${row.steps[0]?.name}`; + // Keyed by its first step, as that step's own row was, so regrouping does not remount it. + const itemKey = row.steps[0]?.name ?? key; + const names = row.steps.map((step) => step.name); + items.push({ + key: itemKey, + body: ( + openedAtMs} + name={ + names.length <= 2 + ? names.join(" · ") + : gt("{names} and {count} more", { + names: names.slice(0, 2).join(" · "), + count: names.length - 2, + }) + } + duration={workflowStepTime(Math.max(0, row.endMs - row.startMs))} + selected={focus === key} + current={current === key} + onPick={() => onPick(key)} + /> + ), + }); + continue; + } + if (row.kind === "together") { + const running = row.beats.filter((beat) => beat.status === "running").length; + // Steps that only sleep or wait are under way without working. + const working = row.beats.some( + (beat) => beat.status === "running" && beat.kind !== "sleep" && beat.kind !== "wait", + ); + const failed = row.beats.some((beat) => beat.status === "failed"); + const asks = row.beats.some( + (beat) => beat.status === "running" && node.questions.some((q) => q.name === beat.name), + ); + const startMs = Math.min(...row.beats.map((beat) => beat.startMs)); + const endMs = Math.max(...row.beats.map((beat) => beat.endMs)); + const first = row.beats[0]; + items.push({ + key: first?.name ?? "together", + branch: true, + body: ( + <> +
    + 0 + ? "quiet" + : failed + ? "failed" + : "done" + } + pulse={startMs > openedAtMs} + draw={running === 0 && endMs > openedAtMs} + /> + 0 ? "font-medium" : "text-muted-foreground", + )} + > + {gt("{count} in parallel", { count: row.beats.length })} + + {working ? ( + + {gt("{count} running", { count: running })} + + ) : null} + + {workflowStepTime(running > 0 ? wholeSeconds(endMs - startMs) : endMs - startMs)} + + +
    + +
      + {row.beats.map((beat, index) => { + const firstBeat = index === 0; + const lastBeat = index === row.beats.length - 1; + const asked = question(beat); + return ( +
    1. + + {lastBeat ? : null} + {beatRow(beat, true)} + {asked === null ? null : ask(asked)} +
    2. + ); + })} +
    + + ), + }); + continue; + } + const asked = question(row); + items.push({ + key: row.name, + body: ( + <> + {beatRow(row)} + {asked === null ? null : ask(asked)} + + ), + }); + } + for (const asked of loose) { + // Keyed like its step's row, which replaces it once the step arrives, so it does not arrive twice. + items.push({ + key: asked.name, + body: ( + <> + openedAtMs} + draw={false} + name={asked.name} + verb={gt("Asks you", { $context: "a workflow step waits on a person's answer" })} + verbTone="input" + selected={focus === `question:${asked.name}`} + current={current === `question:${asked.name}`} + onPick={() => onPick(`question:${asked.name}`)} + /> + {ask(asked)} + + ), + }); + } + if (paused) { + items.push({ + key: "pause", + body: ( + onPick("pause")} + /> + ), + }); + } + // A finished run needs no closing row: the header says so, and the last step is the end. + if (end !== null && !completed) { + const endedMs = Date.parse(node.run.endedAt ?? node.run.updatedAt); + items.push({ + key: "end", + body: ( + openedAtMs} + draw={false} + name={end} + aside={node.run.detail} + selected={focus === "end"} + current={current === "end"} + onPick={() => onPick("end")} + /> + ), + }); + } + const live = end === null; + return ( + + ); +} + +function WorkflowBeatRow({ + environmentId, + beat, + child, + asks, + nowMs, + selected, + onPick, + sub, + openedAtMs, + current, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly child: WorkflowRunNode | null; + /** A person's answer is what it waits for. */ + readonly asks: boolean; + readonly nowMs: number; + readonly selected: boolean; + readonly onPick: () => void; + readonly sub: boolean; + readonly openedAtMs: number; + readonly current: boolean; +}) { + const gt = useGT(); + const m = useMessages(); + const threadEnvironmentId = + beat.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(beat.thread.environmentId); + const shell = useQuietThreadShell( + beat.thread === null + ? null + : scopeThreadRef(threadEnvironmentId, ThreadId.make(beat.thread.threadId)), + ); + const provider = useEnvironmentProviders() + .get(threadEnvironmentId) + ?.find((candidate) => candidate.instanceId === shell?.modelSelection.instanceId); + const under = beat.status === "running"; + const failed = beat.status === "failed"; + const said = workflowAgentSummary(beat).said; + const answer = beat.kind === "ask" ? workflowAnswer(beat.result) : null; + const wakes = beat.detail === null ? Number.NaN : Date.parse(beat.detail); + // An agent's own approval or question needs a person as much as the workflow's does. + const agentAsks = + beat.kind === "agent" && under && shell !== null + ? shell.hasPendingUserInput + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : shell.hasPendingApprovals + ? gt("waits for your approval") + : null + : null; + // A question waits on a person until its step ends, answered or not; the list of open + // questions drops it a moment before the step reports done. + const needsYou = (under && (asks || beat.kind === "ask")) || agentAsks !== null; + const model = shell === null ? null : formatModelSlugName(shell.modelSelection.model); + const verb = (() => { + if (!under) return null; + if (agentAsks !== null) return agentAsks; + switch (beat.kind) { + case "agent": + return shell?.runtime?.status === "preparing" || shell?.runtime?.status === "starting" + ? gt("starting") + : gt("working"); + case "ask": + // Without its question it was just answered, and the step is about to say so. + return asks + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : null; + case "sleep": + return Number.isFinite(wakes) && wakes > nowMs + ? gt("wakes in {duration}", { duration: formatDuration(wholeSeconds(wakes - nowMs)) }) + : gt("about to wake"); + case "wait": + return gt("waiting"); + case "run": + return child === null ? gt("running") : workflowRunNow(child, m); + case "step": + return gt("running"); + } + })(); + const aside = (() => { + if (failed) return workflowOneLine(beat.detail ?? gt("failed")); + if (under) return null; + switch (beat.kind) { + case "agent": + return said === null ? null : workflowOneLine(said); + case "ask": + return answer === null + ? gt("nobody answered") + : gt("You said {choice}", { choice: answer.choice }); + case "sleep": + case "wait": + return null; + case "run": + return child === null ? null : workflowRunNow(child, m); + case "step": { + const first = workflowResultLines(beat.result)[0]; + return first === undefined + ? null + : first.label === null + ? first.value + : `${first.label}: ${first.value}`; + } + } + })(); + + return ( + openedAtMs} + draw={!under && beat.endMs > openedAtMs} + lead={ + beat.kind === "agent" && provider !== undefined ? ( + + ) : beat.kind === "run" ? ( + + ) : undefined + } + name={beat.childRun?.title ?? beat.name} + note={beat.kind === "agent" && (under || said === null) ? model : null} + verb={verb} + verbTone={ + needsYou ? "input" : beat.kind === "sleep" || beat.kind === "wait" ? "quiet" : "working" + } + aside={aside} + {...(failed ? { asideTone: "failed" as const } : {})} + duration={workflowStepTime(elapsedOf(beat))} + selected={selected} + current={current} + onPick={onPick} + sub={sub} + /> + ); +} + +// What happened reads as part of the page. A question, answered in the timeline, is the one box; +// a pause says so in its heading and its button. +const CARD_TONE = { + plain: "", + quiet: "", + ask: "rounded-xl border border-warning/30 bg-warning-surface px-3 py-2.5", + failed: "", + done: "", +} as const; + +function FeedCard({ + tone = "plain", + label, + reveal = false, + children, +}: { + readonly tone?: keyof typeof CARD_TONE; + readonly label?: string; + /** Scroll it into view when it first shows. */ + readonly reveal?: boolean; + readonly children: ReactNode; +}) { + return ( +
    + {children} +
    + ); +} + +function CardHead({ + mark, + name, + sub, + action, +}: { + readonly mark: ReactNode; + readonly name: ReactNode; + readonly sub?: ReactNode; + readonly action?: ReactNode; +}) { + return ( +
    +
    + {mark === null || mark === undefined ? null : ( + {mark} + )} +
    {name}
    + {action === undefined || action === null ? null :
    {action}
    } +
    + {sub === undefined || sub === null || sub === "" ? null : ( +
    {sub}
    + )} +
    + ); +} + +function ResultLines({ + lines, +}: { + readonly lines: ReadonlyArray<{ readonly label: string | null; readonly value: string }>; +}) { + if (lines.length === 0) return null; + if (lines.every((line) => line.label === null)) { + return ( +
    + {lines.map((line) => ( +

    + {line.value} +

    + ))} +
    + ); + } + return ({ label: line.label ?? "", value: line.value }))} />; +} + +/** What a step left behind, as a list of names and values. */ +function Facts({ + facts, +}: { + readonly facts: ReadonlyArray<{ readonly label: string; readonly value: string }>; +}) { + return ( +
    + {facts.map((fact) => ( +
    +
    {fact.label}
    +
    {fact.value}
    +
    + ))} +
    + ); +} + +/** A step with nothing to show but that it happened, and what it left behind. */ +function Note({ + label, + children, + detail, +}: { + readonly label: string; + readonly children: ReactNode; + readonly detail?: ReactNode; +}) { + return ( + + + {detail} + + ); +} + +function WorkflowQuickStepsCard({ row }: { readonly row: WorkflowQuickSteps }) { + const gt = useGT(); + return ( + +
      + {row.steps.map((step) => ( +
    • + {step.name} + +
    • + ))} +
    +
    + ); +} + +function WorkflowBeatCard({ + environmentId, + beat, + child, + nowMs, + open, + onSelect, + onOpenThread, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly child: WorkflowRunNode | null; + readonly nowMs: number; + readonly open: boolean; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; +}) { + const gt = useGT(); + const m = useMessages(); + const under = beat.status === "running"; + const length = formatDuration(elapsedOf(beat)); + const tries = beat.attempts > 1 ? ` · ${nthTry(beat.attempts, m)}` : ""; + switch (beat.kind) { + case "agent": + return ( + + ); + case "ask": { + const answer = workflowAnswer(beat.result); + if (answer === null) + return {`${gt("nobody answered")} · ${length}`}; + return ( + + +

    + {answer.reason === null ? ( + + You said{" "} + + {answer.choice} + + . + + ) : ( + + You said{" "} + + {answer.choice} + + : {answer.reason} + + )} +

    +
    + ); + } + case "sleep": { + if (!under) return {`${gt("slept")} · ${length}`}; + const wakes = beat.detail === null ? Number.NaN : Date.parse(beat.detail); + return ( + + } + name={beat.name} + sub={ + Number.isFinite(wakes) && wakes > nowMs + ? gt("wakes in {duration}", { + duration: formatDuration(wholeSeconds(wakes - nowMs)), + }) + : gt("about to wake") + } + /> + + ); + } + case "wait": + if (!under) return {`${gt("waited")} · ${length}`}; + return ( + + } + name={beat.name} + sub={gt("{duration} so far", { duration: length })} + /> + + ); + case "run": { + const title = beat.childRun?.title ?? beat.name; + return ( + + } + name={title} + sub={ + child === null + ? `${beat.childRun?.workflow ?? ""} · ${length}` + : `${child.run.workflow} · ${workflowRunNow(child, m)}` + } + action={ + <> + {child === null ? null : } + + + } + /> + + ); + } + case "step": { + if (under) { + return ( + + } + name={beat.name} + sub={`${gt("running for {duration}", { duration: length })}${tries}`} + /> + + ); + } + const lines = workflowResultLines(beat.result); + return ( + }> + {beat.status === "failed" ? `${gt("failed")} · ${length}` : length} + {tries} + + ); + } + } +} + +function WorkflowAgentCard({ + environmentId, + beat, + open, + onOpenThread, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly open: boolean; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; +}) { + const gt = useGT(); + const m = useMessages(); + const [all, setAll] = useState(false); + const elsewhere = beat.thread !== null && beat.thread.environmentId !== null; + const threadEnvironmentId = + beat.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(beat.thread.environmentId); + // This client can only show a thread on an environment it is itself connected to. + const threadEnvironment = useEnvironment(threadEnvironmentId); + const shell = useQuietThreadShell( + beat.thread === null + ? null + : scopeThreadRef(threadEnvironmentId, ThreadId.make(beat.thread.threadId)), + ); + const provider = useEnvironmentProviders() + .get(threadEnvironmentId) + ?.find((candidate) => candidate.instanceId === shell?.modelSelection.instanceId); + const under = beat.status === "running"; + const length = formatDuration(elapsedOf(beat)); + const summary = workflowAgentSummary(beat); + const start = summary.said === null ? null : workflowSaidStart(summary.said, SAID_SHOWN); + const liveWord = !under + ? null + : shell?.hasPendingUserInput === true + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : shell?.hasPendingApprovals === true + ? gt("waits for your approval") + : shell?.runtime?.status === "preparing" || shell?.runtime?.status === "starting" + ? gt("starting") + : gt("working"); + const sub = [ + shell === null ? null : formatModelSlugName(shell.modelSelection.model), + liveWord, + length, + beat.attempts > 1 ? nthTry(beat.attempts, m) : null, + elsewhere + ? gt("on {environment}", { environment: threadEnvironment?.label ?? threadEnvironmentId }) + : null, + ] + .filter((part) => part !== null) + .join(" · "); + return ( + + + ) : ( + + ) + } + name={beat.name} + sub={sub} + action={ + beat.thread === null ? null : threadEnvironment === null ? ( + + + Thread on {threadEnvironmentId} + + + ) : ( + + ) + } + /> + {beat.status === "failed" && beat.detail ? ( +

    + + {beat.detail} +

    + ) : null} + {summary.said === null ? null : ( + // Set off from the head, so headings in the reply read as the agent's, not the page's. +
    + + {start !== null ? ( + + ) : null} +
    + )} + {summary.facts.length === 0 ? null : } +
    + ); +} + +function WorkflowPauseCard({ + run, + name, + attempts, + reason, + nowMs, + disabled, + onResume, + kept, +}: { + readonly run: WorkflowRun; + /** The step it stopped at, when the steps say which. */ + readonly name: string | null; + readonly attempts: number; + readonly reason: string | null; + readonly nowMs: number; + readonly disabled: boolean; + readonly onResume: () => void; + /** Steps before it finished, and resuming keeps them. */ + readonly kept: boolean; +}) { + const gt = useGT(); + const m = useMessages(); + const resumes = run.resumesAt === null ? Number.NaN : Date.parse(run.resumesAt); + const next = run.retired + ? gt("cannot go on until its workflow version is registered again") + : !Number.isFinite(resumes) + ? gt("waits for you to resume it") + : resumes > nowMs + ? gt("tries again by itself in {duration}", { duration: formatDuration(resumes - nowMs) }) + : gt("about to try again by itself"); + return ( + + } + name={ + name === null + ? gt("Paused", { $context: "a workflow run is paused" }) + : gt("Paused at {step}", { step: name }) + } + sub={ + <> + {attempts > 0 ? `${nthTry(attempts, m)} · ` : null} + · {next} + + } + action={ + + } + /> + {reason ?

    {reason}

    : null} + {kept ? ( +

    + Only the failed step runs again; what finished before it is kept. +

    + ) : null} +
    + ); +} + +function WorkflowQuestionCard({ + environmentId, + question, + onOpenThread, + inline = false, +}: { + readonly environmentId: EnvironmentId; + readonly question: WorkflowQuestion; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + /** Under its step in the run, which already says that it asks. */ + readonly inline?: boolean; +}) { + const gt = useGT(); + const view = readWorkflowQuestion(question); + const drafts = useContext(AnswerDrafts); + const [ownReason, setOwnReason] = useState(null); + const draftKey = `${question.runId}:${question.name}:${question.askedAt}`; + const reason = drafts === null ? ownReason : drafts.get(draftKey); + const setReason = (next: string | null) => + drafts === null ? setOwnReason(next) : drafts.set(draftKey, next); + const [busy, setBusy] = useState(false); + const canAnswer = useAtomValue( + serverEnvironment.answerWorkflowQuestion.permissionAtom(environmentId), + ); + const answer = useAtomCommand(serverEnvironment.answerWorkflowQuestion, { + label: "workflow answer", + }); + const threadEnvironmentId = + question.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(question.thread.environmentId); + const reachable = useEnvironment(threadEnvironmentId) !== null; + const choose = async (choice: string) => { + if (busy) return; + setBusy(true); + const given = reason?.trim() ?? ""; + const result = await answer({ + environmentId, + input: { + runId: question.runId, + name: question.name, + choice, + ...(given === "" ? {} : { reason: given }), + }, + }); + setBusy(false); + reportFailure(gt("Could not answer the question"), result); + }; + return ( + + {inline ? null : ( +

    + + Needs you + + + + asked{" "} + + + {" "} + · the run waits for you + + +

    + )} +

    + {view.title} +

    + {view.body ? ( + + ) : null} +
    + {view.choices.map((choice, index) => ( + + ))} +
    + {reason === null || (question.thread !== null && reachable) ? ( +
    + {reason === null ? ( + + ) : null} + {question.thread === null || !reachable ? null : ( + + )} +
    + ) : null} + {reason === null ? null : ( +
    + setReason(event.currentTarget.value)} + /> +
    + )} +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx b/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx new file mode 100644 index 0000000000000..386ba513e0e5b --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx @@ -0,0 +1,477 @@ +import { Atom } from "effect/reactivity"; +import { + EnvironmentId, + type WorkflowQuestion, + type WorkflowRun, + type WorkflowRunReference, + type WorkflowRunsSnapshot, + type WorkflowStep, +} from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page as browserPage, userEvent } from "vite-plus/test/browser"; + +import "~/index.css"; +import { render } from "../../../test/render"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { WorkflowRunsView } from "./WorkflowRunsView"; + +const environmentId = EnvironmentId.make("laptop"); +const at = (minute: number) => new Date(Date.UTC(2026, 10, 1, 0, minute)).toISOString(); +const run = (fields: Partial & Pick): WorkflowRun => ({ + workflow: "release", + version: 1, + status: "running", + detail: null, + result: null, + pauses: 0, + retired: false, + resumesAt: null, + parentRunId: null, + parentStep: null, + startedAt: at(0), + updatedAt: at(5), + endedAt: null, + ...fields, +}); +const step = ( + fields: Partial & Pick, +): WorkflowStep => ({ + status: "completed", + attempts: 1, + detail: null, + threadId: null, + environmentId: null, + result: null, + said: null, + startedAt: at(0), + endedAt: at(0), + ...fields, +}); + +const state = vi.hoisted(() => ({ + live: { query: "live" }, + snapshot: { workflows: [], runs: [], questions: [] } as { + workflows: ReadonlyArray; + runs: ReadonlyArray; + questions: ReadonlyArray; + }, + steps: {} as Record>, + references: {} as Record>, + commands: [] as Array, + permitted: true, + detailError: null as string | null, +})); +const canOperate = Atom.make(true); +const cannotOperate = Atom.make(false); + +function setup( + given: Omit & Partial>, + steps: Record> = {}, + references: Record> = {}, +) { + state.snapshot = { workflows: [], ...given }; + state.steps = steps; + state.references = references; + state.commands = []; + state.permitted = true; + state.detailError = null; +} + +const environment = { environmentId, label: "Laptop" }; + +vi.mock(import("../../state/server"), async (original) => { + const actual = await original(); + const permissionAtom = () => (state.permitted ? canOperate : cannotOperate); + return { + ...actual, + serverEnvironment: { + ...actual.serverEnvironment, + workflowsLive: (() => state.live) as never, + workflowRun: ((target: { readonly input: { readonly runId: string } }) => + target.input) as never, + answerWorkflowQuestion: { + ...actual.serverEnvironment.answerWorkflowQuestion, + permissionAtom, + }, + resumeWorkflowRun: { ...actual.serverEnvironment.resumeWorkflowRun, permissionAtom }, + cancelWorkflowRun: { ...actual.serverEnvironment.cancelWorkflowRun, permissionAtom }, + }, + }; +}); +// Stands in for the live list and for one run's detail, which the mocked atoms above name. +vi.mock(import("../../state/query"), async (original) => ({ + ...(await original()), + useEnvironmentQuery: ((request: { readonly runId?: string }) => ({ + data: + request === state.live + ? state.snapshot + : state.detailError !== null + ? null + : { + run: null, + steps: state.steps[request.runId ?? ""] ?? [], + references: state.references[request.runId ?? ""] ?? [], + }, + error: request === state.live ? null : state.detailError, + isPending: false, + refresh: vi.fn(), + })) as never, +})); +vi.mock(import("../../state/use-atom-command"), async (original) => ({ + ...(await original()), + useAtomCommand: ((_command: unknown, options: { readonly label: string }) => + (value: { readonly input: unknown }) => { + state.commands.push([options.label, value.input]); + return Promise.resolve({ _tag: "Success", value: undefined }); + }) as never, +})); +vi.mock(import("../../state/environments"), async (original) => ({ + ...(await original()), + useEnvironment: ((id: EnvironmentId | null) => + id === environmentId ? environment : null) as never, +})); +// The chat's renderer loads its highlighter; a question's body only has to reach the page. +vi.mock("../ChatMarkdown", () => ({ + default: ({ text }: { readonly text: string }) =>
    {text}
    , +})); + +const question: WorkflowQuestion = { + runId: "ship", + name: "approve", + request: { + title: "Ship release 1.2?", + choices: ["Ship", "Hold"], + data: { body: "The diff touches the installer." }, + }, + askedAt: at(4), + thread: { threadId: "thread-9", environmentId: null }, +}; + +const issue101: WorkflowRunReference = { + kind: "issue", + key: "i101", + address: { projectId: "p1", tracker: "github", scope: "me/app", key: "101" }, + title: "Wrong minutes", + url: "https://github.com/me/app/issues/101", + state: "open", + steps: ["triage"], + origin: "trigger", +}; + +/** Wide enough for the list and the run side by side; put back when the test ends. */ +async function desktop() { + const width = window.innerWidth; + const height = window.innerHeight; + await browserPage.viewport(1280, 800); + return { [Symbol.asyncDispose]: () => browserPage.viewport(width, height) }; +} + +const page = ( + selectedRunId: string | null = null, + on: { + readonly select?: (runId: string | null) => void; + readonly thread?: () => void; + readonly reference?: () => void; + } = {}, + shownTab: WorkflowPaneTab | null = null, +) => ( + +); + +describe("WorkflowRunsView", () => { + it("opens on the question that waits, and answers it with the reason given", async () => { + setup( + { + runs: [ + run({ runId: "busy", title: "Nightly sync" }), + run({ runId: "ship", title: "Release 1.2", status: "waiting", detail: "approve" }), + ], + questions: [question], + }, + { ship: [step({ name: "approve", kind: "ask", status: "running", endedAt: null })] }, + ); + const thread = vi.fn(); + await using _desktop = await desktop(); + await using screen = await render(page(null, { thread })); + + // The list opens on what waits on a person, and the run that asks is the one shown. + const runs = screen.getByRole("navigation", { name: "Workflow runs" }); + await expect.element(runs.getByRole("button", { name: /Release 1\.2/ })).toBeVisible(); + await expect + .element(runs.getByRole("button", { name: /Nightly sync/ })) + .not.toBeInTheDocument(); + await expect.element(runs).toMatchTextContent("Asks: Ship release 1.2?"); + await expect.element(screen.getByText("The diff touches the installer.")).toBeVisible(); + + await screen.getByRole("button", { name: "Ask the agent first" }).click(); + expect(thread).toHaveBeenCalledWith("ship", { threadId: "thread-9", environmentId: null }); + + await screen.getByRole("button", { name: "Add a reason" }).click(); + await userEvent.fill( + screen.getByRole("textbox", { name: "Reason for Ship release 1.2?" }), + " Too risky today ", + ); + await screen.getByRole("button", { name: "Hold", exact: true }).click(); + + await vi.waitFor(() => + expect(state.commands).toEqual([ + [ + "workflow answer", + { runId: "ship", name: "approve", choice: "Hold", reason: "Too risky today" }, + ], + ]), + ); + }); + + it("answers a question whose steps did not load, and says a linked run is not here", async () => { + setup({ + runs: [run({ runId: "ship", title: "Release 1.2", status: "waiting", detail: "approve" })], + questions: [question], + }); + state.detailError = "The server did not answer."; + await using _desktop = await desktop(); + { + await using screen = await render(page("ship")); + await expect.element(screen.getByText("The server did not answer.")).toBeVisible(); + await screen.getByRole("button", { name: "Ship", exact: true }).click(); + await vi.waitFor(() => + expect(state.commands).toEqual([ + ["workflow answer", { runId: "ship", name: "approve", choice: "Ship" }], + ]), + ); + } + + // A link to a run this environment does not have never shows another run in its place. + const select = vi.fn(); + await using screen = await render(page("gone", { select })); + await expect.element(screen.getByText("This run is not here")).toBeVisible(); + await expect + .element(screen.getByRole("button", { name: "Ship", exact: true })) + .not.toBeInTheDocument(); + await screen.getByRole("button", { name: "Back to the runs" }).click(); + expect(select).toHaveBeenCalledWith(null); + }); + + it("says a linked run is not here where nothing has run yet", async () => { + setup({ runs: [], questions: [] }); + const select = vi.fn(); + await using screen = await render(page("gone", { select })); + await expect.element(screen.getByText("This run is not here")).toBeVisible(); + await screen.getByRole("button", { name: "Back to the runs" }).click(); + expect(select).toHaveBeenCalledWith(null); + }); + + it("turns the answers off for a session that may not operate", async () => { + setup({ + runs: [run({ runId: "ship", title: "Release 1.2", status: "waiting" })], + questions: [question], + }); + state.permitted = false; + await using _desktop = await desktop(); + await using screen = await render(page()); + + await expect.element(screen.getByRole("button", { name: "Ship", exact: true })).toBeDisabled(); + await expect.element(screen.getByRole("button", { name: "Hold", exact: true })).toBeDisabled(); + }); + + it("says why a run paused at the step that failed, and resumes it", async () => { + setup( + { + runs: [ + run({ + runId: "sync", + title: "Sync labels", + status: "paused", + detail: "apply: 503", + pauses: 1, + }), + ], + questions: [], + }, + { + sync: [ + // A failure the workflow caught and went on from is not where it paused. + step({ name: "lint", kind: "step", status: "failed", endedAt: at(1), detail: "lint" }), + step({ name: "fetch", kind: "step", startedAt: at(1), endedAt: at(1) }), + step({ + name: "apply", + kind: "agent", + status: "failed", + attempts: 3, + detail: "503", + threadId: "thread-apply", + startedAt: at(2), + endedAt: at(3), + }), + ], + }, + ); + await using _desktop = await desktop(); + await using screen = await render(page()); + + const why = screen.getByRole("region", { name: "Why it paused" }); + await expect.element(why).toMatchTextContent(/Paused at apply.*3rd try.*waits for you/); + await expect.element(why).toMatchTextContent("503"); + // The failed agent's transcript is there to read before choosing. + await expect.element(screen.getByRole("button", { name: "Transcript" })).toBeVisible(); + await expect.element(screen.getByText("Paused at lint")).not.toBeInTheDocument(); + await why.getByRole("button", { name: "Resume" }).click(); + + await vi.waitFor(() => + expect(state.commands).toEqual([["workflow resume", { runId: "sync" }]]), + ); + }); + + it("draws a finished run as a flow, and shows the step that is picked", async () => { + setup( + { + runs: [ + run({ + runId: "fix", + title: "#101 Wrong minutes", + status: "completed", + result: "merged as ba6ac7", + endedAt: at(12), + }), + ], + questions: [], + }, + { + fix: [ + step({ name: "load", kind: "step" }), + step({ name: "existing-prs", kind: "step" }), + step({ + name: "triage", + kind: "agent", + endedAt: at(3), + threadId: "thread-1", + said: "Reproduced on main.", + result: { kind: "bug", reproduced: true }, + }), + step({ + name: "implement", + kind: "agent", + startedAt: at(3), + endedAt: at(10), + threadId: "thread-2", + environmentId: "build-box", + }), + step({ + name: "approve", + kind: "ask", + startedAt: at(10), + endedAt: at(11), + result: { choice: "Fix it", reason: "It hits everyone on Windows" }, + }), + ], + }, + { fix: [issue101] }, + ); + const thread = vi.fn(); + const reference = vi.fn(); + await using screen = await render(page("fix", { thread, reference }, { thread: "thread-1" })); + + // A finished run opens on how it ended; the flow has a node for each step that mattered. + const happened = screen.getByRole("region", { name: "What happened" }); + await expect.element(happened).toMatchTextContent(/Finished.*merged as ba6ac7/); + const flow = screen.getByRole("navigation", { name: "Steps so far" }); + await expect + .element(flow) + .toMatchTextContent(/load · existing-prs.*triage.*Reproduced on main\..*implement.*approve/); + + await flow.getByRole("button", { name: /triage/ }).click(); + const triage = screen.getByRole("region", { name: "triage" }); + await expect.element(triage).toMatchTextContent(/3m 0s.*Reproduced on main\..*kind.*bug/); + // Its thread is the one open beside the run, and the button says so. + const transcript = triage.getByRole("button", { name: "Transcript" }); + await expect.element(transcript).toHaveAttribute("aria-pressed", "true"); + await transcript.click(); + expect(thread).toHaveBeenCalledWith("fix", { threadId: "thread-1", environmentId: null }); + // What the run touched is under its title, by number alone when the title already says it. + // It opens beside the run. + const touched = screen.getByRole("list", { name: "What the run touched" }); + const onRun = touched.getByRole("button", { name: "#101 Wrong minutes" }); + await expect.element(onRun).toMatchTextContent(/^#101$/); + await onRun.click(); + expect(reference).toHaveBeenCalledWith("fix", issue101); + // This client is not connected to the linked environment, so there is nothing to open. + await flow.getByRole("button", { name: /implement/ }).click(); + await expect + .element(screen.getByRole("region", { name: "implement" })) + .toMatchTextContent("Thread on build-box"); + await flow.getByRole("button", { name: /approve/ }).click(); + await expect + .element(screen.getByRole("region", { name: "approve" })) + .toMatchTextContent("You said Fix it: It hits everyone on Windows"); + await flow.getByRole("button", { name: /load · existing-prs/ }).click(); + await expect + .element(screen.getByRole("region", { name: "Quick steps" })) + .toMatchTextContent("loadexisting-prs"); + await expect + .element(screen.getByRole("button", { name: "Cancel run" })) + .not.toBeInTheDocument(); + }); + + it("opens an invoked run from its parent's story", async () => { + setup( + { + runs: [ + run({ runId: "rel", title: "Release 1.3", status: "waiting", detail: "check" }), + run({ runId: "chk", title: "Check web", parentRunId: "rel", parentStep: "check" }), + ], + questions: [], + }, + { + rel: [ + step({ name: "check/start", kind: "step" }), + step({ name: "check", kind: "wait", status: "running", endedAt: null }), + ], + }, + ); + const select = vi.fn(); + await using screen = await render(page("rel", { select })); + + const invoked = screen.getByRole("region", { name: "Check web" }); + await invoked.getByRole("button", { name: "Open run" }).click(); + expect(select).toHaveBeenCalledWith("chk"); + }); + + it("switches between what is under way and everything, one workflow at a time", async () => { + setup({ + workflows: [ + { name: "release", version: 1, triggers: ["webhook tags"] }, + { name: "report", version: 1, triggers: ["daily at 09:00"] }, + ], + runs: [ + run({ runId: "rel", title: "Release 1.3" }), + run({ runId: "old", title: "Release 1.2", status: "completed", endedAt: at(3) }), + ], + questions: [], + }); + await using _desktop = await desktop(); + await using screen = await render(page()); + + const runs = screen.getByRole("navigation", { name: "Workflow runs" }); + await expect.element(runs.getByRole("button", { name: /Release 1\.3/ })).toBeVisible(); + await expect + .element(runs.getByRole("button", { name: /Release 1\.2/ })) + .not.toBeInTheDocument(); + await screen.getByRole("button", { name: "All", exact: true }).click(); + await expect.element(runs.getByRole("button", { name: /Release 1\.2/ })).toBeVisible(); + + // A workflow that has not run is still there to be picked, with what starts it. + await screen.getByRole("combobox", { name: "Workflow" }).click(); + await screen.getByRole("option", { name: "report" }).click(); + await expect.element(screen.getByText("Starts on daily at 09:00")).toBeVisible(); + await expect.element(runs).toMatchTextContent("Has not run yet."); + }); +}); diff --git a/apps/web/src/components/workflows/WorkflowRunsView.tsx b/apps/web/src/components/workflows/WorkflowRunsView.tsx new file mode 100644 index 0000000000000..4c43539b1e1e3 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunsView.tsx @@ -0,0 +1,384 @@ +import { type EnvironmentId, type WorkflowRunReference } from "@t3tools/contracts"; +import { msg, T, useGT, useMessages } from "gt-react"; +import { WorkflowIcon } from "lucide-react"; +import { useState, type ReactNode } from "react"; + +import { cn } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { Button } from "../ui/button"; +import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; +import { ScrollArea } from "../ui/scroll-area"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { + RelativeLabel, + WorkflowChip, + WorkflowRunFeed, + WorkflowStateWord, + type WorkflowThreadTarget, +} from "./WorkflowRunFeed"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { + allWorkflowRunNodes, + defaultWorkflowListTab, + defaultWorkflowRunId, + groupWorkflowRuns, + listedWorkflowRuns, + workflowRunLists, + workflowRunNow, + workflowTriggerLine, + type WorkflowListTab, + type WorkflowRunNode, + workflowRunInvolves, +} from "@t3tools/client-runtime/workflows"; + +const WORKFLOWS_GUIDE_URL = "https://github.com/pingdotgg/t3code/blob/main/docs/user/workflows.md"; +const EVERY_WORKFLOW = ""; +const TABS: ReadonlyArray<{ readonly value: WorkflowListTab; readonly label: string }> = [ + { + value: "needs-you", + label: msg("Needs you", { $context: "tab: workflow runs that wait on the user" }), + }, + { value: "running", label: msg("Running", { $context: "tab: workflow runs under way" }) }, + { value: "all", label: msg("All", { $context: "tab: every workflow run" }) }, +]; +const NOTHING: Record = { + "needs-you": msg("Nothing waits on you."), + running: msg("Nothing is running."), + all: msg("No runs yet."), +}; + +export function WorkflowsEmpty({ + title, + description, +}: { + readonly title: string; + readonly description: ReactNode; +}) { + return ( +
    + + + + + + {title} + {description} + + +
    + ); +} + +/** One environment's runs: the list to pick from, and the picked run told as a feed. */ +export function WorkflowRunsView({ + environmentId, + selectedRunId, + paneOpen, + shownTab, + onSelect, + onOpenThread, + onOpenReference, + onOpenDefinitions, +}: { + readonly environmentId: EnvironmentId; + readonly selectedRunId: string | null; + /** Something is open beside the run, so the list makes room below `xl`. */ + readonly paneOpen: boolean; + /** What shows beside the run, so what opened it can say so. */ + readonly shownTab: WorkflowPaneTab | null; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (runId: string, thread: WorkflowThreadTarget) => void; + readonly onOpenReference: (runId: string, reference: WorkflowRunReference) => void; + readonly onOpenDefinitions: () => void; +}) { + const live = useEnvironmentQuery(serverEnvironment.workflowsLive({ environmentId, input: {} })); + const [pickedTab, setPickedTab] = useState(null); + const [workflow, setWorkflow] = useState(EVERY_WORKFLOW); + const gt = useGT(); + const m = useMessages(); + const [showSkipped, setShowSkipped] = useState(false); + const snapshot = live.data; + if (live.error) { + return ; + } + if (!snapshot) { + return ( +

    + Loading workflow runs… +

    + ); + } + // A broken file is said even where nothing has run, or its workflows would just seem missing. + const problemAlert = + snapshot.definition?.problem == null ? null : ( +
    + + + + A workflow file has a problem. + {" "} + The last version that did keeps running. + + + +
    + ); + const withProblem = (empty: ReactNode) => + problemAlert === null ? ( + empty + ) : ( +
    + {problemAlert} + {empty} +
    + ); + const notHere = ( + + This environment has no run with that link.{" "} + + + } + /> + ); + // A link to a run says it is not here, even where nothing has run at all. + if (snapshot.runs.length === 0 && snapshot.workflows.length === 0 && selectedRunId !== null) { + return withProblem(notHere); + } + if (snapshot.runs.length === 0 && snapshot.workflows.length === 0) { + return withProblem( + + A workflow ties agents, code, schedules and questions to you into one run that survives + restarts. Write one under{" "} + + , or ask an agent to.{" "} +
    + Read the guide + + + } + />, + ); + } + // A skipped run opened by its link is shown all the same. + const openedSkipped = snapshot.runs.some( + (run) => run.runId === selectedRunId && run.status === "skipped", + ); + const visible = listedWorkflowRuns(snapshot.runs, showSkipped || openedSkipped); + const groups = groupWorkflowRuns(snapshot.workflows, visible.runs, snapshot.questions); + const lists = workflowRunLists(groups); + const all = allWorkflowRunNodes(groups); + const section = groups.workflows.find((candidate) => candidate.name === workflow) ?? null; + // A run the address names is that run or none: another one's buttons would act on the wrong run. + const shownRunId = + selectedRunId === null + ? defaultWorkflowRunId(groups) + : (all.find((node) => node.run.runId === selectedRunId)?.run.runId ?? null); + const shown = all.find((node) => node.run.runId === shownRunId) ?? null; + // A run that another invoked is not in the list itself; the one it is part of stands for it. + const listedFor = (node: WorkflowRunNode | null): string | null => { + if (node === null) return null; + const parent = all.find((candidate) => candidate.run.runId === node.run.parentRunId); + return parent === undefined ? node.run.runId : listedFor(parent); + }; + const currentRunId = listedFor(shown); + // A run opened by its link is shown in a list that has it, so the list never points at nothing. + const opening = defaultWorkflowListTab(groups); + const holds = (candidate: WorkflowListTab) => + lists[candidate].some((node) => node.run.runId === currentRunId); + const tab = + pickedTab ?? + (selectedRunId === null || holds(opening) ? opening : holds("running") ? "running" : "all"); + const listed = lists[tab].filter( + (node) => section === null || workflowRunInvolves(node, section.name), + ); + return ( +
    + {problemAlert} +
    + {/* Below md there is room for one of the two: the list, or the run picked from it. */} +
    +
    + { + const value = TABS.find((candidate) => candidate.value === next[0]); + if (value !== undefined) setPickedTab(value.value); + }} + > + {TABS.map(({ value, label }) => ( + + {m(label)} + + ))} + + {groups.workflows.length > 1 ? ( + + ) : null} + {section === null ? null : ( +

    + {workflowTriggerLine(section, m)} +

    + )} +
    + + + +
    + + {shown === null ? ( + selectedRunId === null ? null : ( + notHere + ) + ) : ( + node.run.runId === shown.run.parentRunId)?.run ?? null} + shownTab={shownTab} + onSelect={onSelect} + onOpenThread={(thread) => onOpenThread(shown.run.runId, thread)} + onOpenReference={(reference) => onOpenReference(shown.run.runId, reference)} + /> + )} + +
    +
    + ); +} + +/** A run in the thread list's own shape: which workflow, its state in a word, and what it is at. */ +function WorkflowRunListItem({ + node, + current, + onSelect, +}: { + readonly node: WorkflowRunNode; + readonly current: boolean; + readonly onSelect: (runId: string | null) => void; +}) { + const { run } = node; + const m = useMessages(); + return ( +
  • + +
  • + ); +} diff --git a/apps/web/src/components/workflows/WorkflowThreadPane.tsx b/apps/web/src/components/workflows/WorkflowThreadPane.tsx new file mode 100644 index 0000000000000..7e6432eaec393 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowThreadPane.tsx @@ -0,0 +1,65 @@ +import { type ScopedThreadRef } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { useGT } from "gt-react"; + +import { ComposerHandleContext } from "../../composerHandleContext"; +import type { SideChatParentPanel } from "../../lib/sideChatPane"; +import { useQuietThreadShell } from "../../state/entities"; +import { useEnvironmentShellHasSnapshot } from "../../state/shell"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import ChatView from "../ChatView"; +import { BackgroundThreadContext } from "../chat/backgroundThread"; + +/** Opens the thread as a full thread view. */ +export function useOpenThreadPage(): (threadRef: ScopedThreadRef) => void { + const navigate = useNavigate(); + return (threadRef) => + void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(threadRef) }); +} + +/** What a transcript's tab is called: the step its agent did, or the thread's own title. */ +export function WorkflowThreadTabLabel({ threadRef }: { readonly threadRef: ScopedThreadRef }) { + const gt = useGT(); + const shell = useQuietThreadShell(threadRef); + const step = shell?.workflowRun?.step; + return step === undefined + ? (shell?.title ?? gt("Agent", { $context: "fallback title of a coding agent's thread" })) + : gt("{step} · transcript", { step, $context: "tab: the agent thread of a workflow step" }); +} + +/** + * An agent step's thread beside its run: the same chat as anywhere, composer included, so a + * person can read what the agent did and talk to it without leaving the run. + */ +export default function WorkflowThreadPane({ threadRef }: { readonly threadRef: ScopedThreadRef }) { + const gt = useGT(); + const openThreadPage = useOpenThreadPage(); + const shell = useQuietThreadShell(threadRef); + const snapshotLoaded = useEnvironmentShellHasSnapshot(threadRef.environmentId); + const openFull = () => openThreadPage(threadRef); + // The diff panel and the terminal drawer belong to the full thread view, so both lead there. + const panel: SideChatParentPanel = { + hostRef: threadRef, + openToolDiff: openFull, + runShellCommand: openFull, + }; + return shell === null ? ( +

    + {snapshotLoaded ? gt("This thread is no longer there.") : gt("Loading the thread…")} +

    + ) : ( + // The attribute is how the embedded chat knows the keyboard is meant for it. +
    + + + + + +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowsPage.tsx b/apps/web/src/components/workflows/WorkflowsPage.tsx new file mode 100644 index 0000000000000..7c42a4d00080a --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowsPage.tsx @@ -0,0 +1,328 @@ +import { EnvironmentId, type WorkflowRunReference } from "@t3tools/contracts"; +import { Link, useNavigate, useSearch } from "@tanstack/react-router"; +import { T, useGT } from "gt-react"; +import { FileCode2Icon } from "lucide-react"; +import { lazy, Suspense, useState, type MouseEvent } from "react"; + +import { isElectron } from "~/env"; +import { type FileContextMenuAction, useFileContextMenu } from "../../fileContextMenu"; +import { cn } from "../../lib/utils"; +import { readLocalApi } from "../../localApi"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { + useConnectedEnvironmentIds, + useEnvironments, + usePrimaryEnvironmentId, +} from "../../state/environments"; +import { useWorkflowEnvironmentIds } from "./useWorkflowEnvironmentIds"; +import { Button } from "../ui/button"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { SidebarInset } from "../ui/sidebar"; +import { + WorkspaceBreadcrumb, + WorkspaceBreadcrumbItem, + WorkspaceBreadcrumbSeparator, + WorkspaceBreadcrumbText, +} from "../WorkspaceBreadcrumb"; +import { WorkspacePageHeader } from "../WorkspacePageHeader"; +import { WorkflowRunsView, WorkflowsEmpty } from "./WorkflowRunsView"; +import WorkflowPane from "./WorkflowPane"; +import { + activeWorkflowPaneTab, + toggleWorkflowPaneTab, + type WorkflowPaneState, +} from "./workflowPane.logic"; + +const COPY_PATH = "copy-path"; + +// The editor brings the code view's highlighter with it, which the run list has no use for. +const WorkflowDefinitionEditor = lazy(() => import("./WorkflowDefinitionEditor")); + +export interface WorkflowsSearch extends WorkflowPaneState { + readonly env?: string; + readonly run?: string; + /** Show the definition files instead of the runs: all of them, or `file` in the editor. */ + readonly definitions?: boolean; + readonly file?: string; +} + +export function WorkflowsPage() { + const search = useSearch({ from: "/_chat/workflows" }); + const navigate = useNavigate(); + const gt = useGT(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const connectedIds = useConnectedEnvironmentIds(); + const { environments } = useEnvironments(); + const workflowIds = useWorkflowEnvironmentIds(); + // Only servers with workflows on in Labs can be picked; a connected one with them off says so. + const connected = environments.filter((environment) => + workflowIds.includes(environment.environmentId), + ); + const asked = search.env === undefined ? null : EnvironmentId.make(search.env); + const turnedOff = + asked === null + ? workflowIds.length === 0 && connectedIds.length > 0 + : connectedIds.includes(asked) && !workflowIds.includes(asked); + // An environment the address names is kept while it is away: its run and file mean nothing on + // another server. + const environmentId = + asked !== null + ? (connected.find((environment) => environment.environmentId === asked)?.environmentId ?? + null) + : (connected.find((environment) => environment.environmentId === primaryEnvironmentId) + ?.environmentId ?? + connected[0]?.environmentId ?? + null); + const select = (next: WorkflowsSearch) => + void navigate({ to: "/workflows", search: next, replace: true }); + // A level of the page, which the browser's Back should step out of again. + const go = (next: WorkflowsSearch) => void navigate({ to: "/workflows", search: next }); + // Opening a run or file pins the environment it is on, so the same address never means another. + const pinned = environmentId ?? search.env; + const env = pinned === undefined ? {} : { env: pinned }; + const away = + asked !== null && environmentId === null && !turnedOff + ? (environments.find((environment) => environment.environmentId === asked)?.label ?? asked) + : null; + const run = search.run === undefined ? {} : { run: search.run }; + const editing = search.definitions === true || search.file !== undefined; + // An open file stays open while its environment is away, so a draft in it is not lost. + const fileEnvironmentId = + environmentId ?? (search.file === undefined || turnedOff ? null : asked); + const [fileActions, setFileActions] = useState(null); + const definitions = useEnvironmentQuery( + fileEnvironmentId === null || search.file === undefined + ? null + : serverEnvironment.workflowDefinition({ environmentId: fileEnvironmentId, input: {} }), + ); + const fileMenu = useFileContextMenu(fileEnvironmentId); + /** What a right click on the open file's name offers: its path, and the editors on that machine. */ + const showFileMenu = (event: MouseEvent) => { + const api = readLocalApi(); + const directory = definitions.data?.directory; + if (api === undefined || directory === undefined || search.file === undefined) return; + event.preventDefault(); + const path = `${directory}/${search.file}`; + const target = { environmentId: fileEnvironmentId, filePath: path, workspaceRoot: undefined }; + void api.contextMenu + .show([{ id: COPY_PATH, label: gt("Copy path") }, ...fileMenu.buildItems(target)], { + x: event.clientX, + y: event.clientY, + }) + .then((picked) => { + if (picked === null) return; + if (picked === COPY_PATH) return void navigator.clipboard.writeText(path); + return fileMenu.activate(picked as FileContextMenuAction, target); + }); + }; + // The run stays in the address, so the breadcrumb back to the runs reopens it. + const openDefinitions = (file: string | null) => + go({ ...env, ...run, definitions: true, ...(file === null ? {} : { file }) }); + // What is open beside the run, which belongs to the run: picking another one closes it. + const pane: WorkflowPaneState = + environmentId === null || editing || search.pane === undefined + ? {} + : search.tab === undefined + ? { pane: search.pane } + : { pane: search.pane, tab: search.tab }; + const paneOpen = pane.pane !== undefined; + const shownTab = activeWorkflowPaneTab(pane); + // Opening something pins the run it is from, so the address keeps naming the run it belongs to. + const togglePane = (runId: string, tab: Parameters[1]) => + select({ ...env, run: runId, ...toggleWorkflowPaneTab(pane, tab) }); + + return ( + +
    + {/* Below md there is room for one thing, and an open pane is that thing. */} +
    + + + + {editing ? ( + + ) : ( +

    + Workflows +

    + )} +
    + {editing ? ( + <> + + / + + + {search.file === undefined ? ( +

    + Definitions +

    + ) : ( + + )} +
    + + ) : null} + {search.file === undefined ? null : ( + <> + + / + + +

    + + {search.file} + +

    +
    + + )} +
    + {(connected.length > 1 && environmentId !== null) || + ((away !== null || turnedOff) && connected.length > 0) ? ( + + ) : null} + {search.file === undefined ? null : ( +
    + )} + {environmentId === null || editing ? null : ( + + )} + + {editing && fileEnvironmentId !== null ? ( + + Loading the editor… +

    + } + > + +
    + ) : away !== null ? ( + + ) : turnedOff ? ( + + Turn them on for this server in{" "} + + Settings → Labs + + . + + } + /> + ) : environmentId === null ? ( + + ) : ( + openDefinitions(null)} + environmentId={environmentId} + selectedRunId={search.run ?? null} + paneOpen={paneOpen} + shownTab={shownTab} + onSelect={(runId) => select({ ...env, ...(runId === null ? {} : { run: runId }) })} + onOpenThread={(runId, thread) => + togglePane(runId, { + thread: thread.threadId, + ...(thread.environmentId === null ? {} : { env: thread.environmentId }), + }) + } + onOpenReference={(runId, reference: WorkflowRunReference) => + togglePane(runId, { kind: reference.kind, key: reference.key }) + } + /> + )} +
    + {environmentId === null || !paneOpen ? null : ( + + )} +
    + + ); +} diff --git a/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts b/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts new file mode 100644 index 0000000000000..9a8bd4a583b71 --- /dev/null +++ b/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts @@ -0,0 +1,11 @@ +import type { EnvironmentId } from "@t3tools/contracts"; + +import { useServerConfigs } from "../../state/entities"; +import { useConnectedEnvironmentIds } from "../../state/environments"; + +/** The connected environments whose server has workflows turned on in Labs. */ +export function useWorkflowEnvironmentIds(): ReadonlyArray { + const connectedIds = useConnectedEnvironmentIds(); + const configs = useServerConfigs(); + return connectedIds.filter((id) => configs.get(id)?.settings.workflowsEnabled === true); +} diff --git a/apps/web/src/components/workflows/workflowPane.logic.test.ts b/apps/web/src/components/workflows/workflowPane.logic.test.ts new file mode 100644 index 0000000000000..f9c9b54f926a2 --- /dev/null +++ b/apps/web/src/components/workflows/workflowPane.logic.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + activeWorkflowPaneTab, + closeWorkflowPaneTab, + openWorkflowPaneTab, + readWorkflowPane, + toggleWorkflowPaneTab, + type WorkflowPaneState, +} from "./workflowPane.logic"; + +const issue = { kind: "issue", key: "i412" }; +const pullRequest = { kind: "pullRequest", key: "p418" }; +const transcript = { thread: "workflow:ab", env: "env-2" }; + +describe("the pane beside a run", () => { + it("reads back from the address only what it can, once", () => { + expect( + readWorkflowPane( + [issue, { kind: "issue" }, issue, transcript, { thread: "t1", env: 3 }, "x"], + "0", + ), + ).toEqual({ pane: [issue, transcript, { thread: "t1" }], tab: 0 }); + // The last tab shows unless the address says another; one it cannot have shows the last. + expect(readWorkflowPane([issue, pullRequest], 7)).toEqual({ pane: [issue, pullRequest] }); + expect(readWorkflowPane("nope", 0)).toEqual({}); + }); + + it("opens a tab once, shows it, and closing one shows the tab beside it", () => { + let state: WorkflowPaneState = {}; + state = openWorkflowPaneTab(state, issue); + state = openWorkflowPaneTab(state, pullRequest); + state = openWorkflowPaneTab(state, transcript); + expect(state).toEqual({ pane: [issue, pullRequest, transcript] }); + state = openWorkflowPaneTab(state, { ...issue }); + expect(state).toEqual({ pane: [issue, pullRequest, transcript], tab: 0 }); + state = closeWorkflowPaneTab(state, 0); + expect(activeWorkflowPaneTab(state)).toEqual(pullRequest); + // Closing one that does not show leaves the one that does. + state = closeWorkflowPaneTab(state, 1); + expect(state).toEqual({ pane: [pullRequest] }); + expect(closeWorkflowPaneTab(state, 0)).toEqual({}); + }); + + it("asking for the tab that shows closes it, and any other shows it", () => { + const open = { pane: [issue, transcript] }; + expect(toggleWorkflowPaneTab(open, transcript)).toEqual({ pane: [issue] }); + expect(toggleWorkflowPaneTab(open, issue)).toEqual({ pane: [issue, transcript], tab: 0 }); + }); +}); diff --git a/apps/web/src/components/workflows/workflowPane.logic.ts b/apps/web/src/components/workflows/workflowPane.logic.ts new file mode 100644 index 0000000000000..9cdbc4963423d --- /dev/null +++ b/apps/web/src/components/workflows/workflowPane.logic.ts @@ -0,0 +1,103 @@ +/** + * What is open beside a run: agent transcripts and the things the run touched, one tab each. It + * lives in the address, so a reload or a shared link opens the same tabs. + */ +export type WorkflowPaneTab = + /** An agent's thread, and the linked environment it is in when not the run's own. */ + | { readonly thread: string; readonly env?: string } + /** One of the run's references, by its kind and key. */ + | { readonly kind: string; readonly key: string }; + +export interface WorkflowPaneState { + readonly pane?: ReadonlyArray; + /** Which tab shows; the last one when it names none. */ + readonly tab?: number; +} + +// A link is typed into an address bar: what it holds is capped like the rest of the address. +const MOST_TABS = 12; +const LONGEST = 400; + +const text = (value: unknown): value is string => + typeof value === "string" && value !== "" && value.length <= LONGEST; + +function readTab(raw: unknown): WorkflowPaneTab | null { + if (typeof raw !== "object" || raw === null) return null; + const fields = raw as Readonly>; + if (text(fields.thread)) { + return text(fields.env) + ? { thread: fields.thread, env: fields.env } + : { thread: fields.thread }; + } + return text(fields.kind) && text(fields.key) ? { kind: fields.kind, key: fields.key } : null; +} + +const sameWorkflowPaneTab = (left: WorkflowPaneTab, right: WorkflowPaneTab) => + "thread" in left + ? "thread" in right && left.thread === right.thread && left.env === right.env + : "kind" in right && left.kind === right.kind && left.key === right.key; + +/** The pane an address names, without what it cannot read or holds twice. */ +export function readWorkflowPane(rawPane: unknown, rawTab: unknown): WorkflowPaneState { + const tabs: Array = []; + for (const raw of Array.isArray(rawPane) ? rawPane : []) { + const tab = readTab(raw); + if (tab === null || tabs.some((open) => sameWorkflowPaneTab(open, tab))) continue; + tabs.push(tab); + if (tabs.length === MOST_TABS) break; + } + if (tabs.length === 0) return {}; + const tab = typeof rawTab === "number" ? rawTab : Number(rawTab); + return Number.isInteger(tab) && tab >= 0 && tab < tabs.length - 1 + ? { pane: tabs, tab } + : { pane: tabs }; +} + +/** The index of the tab that shows, or -1 when nothing is open. */ +export function activeWorkflowPaneIndex(state: WorkflowPaneState): number { + const count = state.pane?.length ?? 0; + return state.tab !== undefined && state.tab < count ? state.tab : count - 1; +} + +export function activeWorkflowPaneTab(state: WorkflowPaneState): WorkflowPaneTab | null { + return state.pane?.[activeWorkflowPaneIndex(state)] ?? null; +} + +const stateOf = (tabs: ReadonlyArray, active: number): WorkflowPaneState => + tabs.length === 0 + ? {} + : active === tabs.length - 1 + ? { pane: tabs } + : { pane: tabs, tab: active }; + +/** Shows `tab`, opening it after the others when it is not open yet. */ +export function openWorkflowPaneTab( + state: WorkflowPaneState, + tab: WorkflowPaneTab, +): WorkflowPaneState { + const tabs = state.pane ?? []; + const at = tabs.findIndex((open) => sameWorkflowPaneTab(open, tab)); + if (at !== -1) return stateOf(tabs, at); + const next = [...tabs, tab].slice(-MOST_TABS); + return stateOf(next, next.length - 1); +} + +/** Closes the tab at `index`. The one beside it shows if it was showing. */ +export function closeWorkflowPaneTab(state: WorkflowPaneState, index: number): WorkflowPaneState { + const tabs = state.pane ?? []; + if (index < 0 || index >= tabs.length) return state; + const active = activeWorkflowPaneIndex(state); + const rest = tabs.filter((_, at) => at !== index); + return stateOf(rest, active > index ? active - 1 : Math.min(active, rest.length - 1)); +} + +/** Asking for the tab that shows closes it, as the pressed control that asked says it will. */ +export function toggleWorkflowPaneTab( + state: WorkflowPaneState, + tab: WorkflowPaneTab, +): WorkflowPaneState { + const active = activeWorkflowPaneTab(state); + return active !== null && sameWorkflowPaneTab(active, tab) + ? closeWorkflowPaneTab(state, activeWorkflowPaneIndex(state)) + : openWorkflowPaneTab(state, tab); +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index ecdb3d4220e67..f63b5ce4f5841 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Verknüpfe diese Umgebung mit T3 Connect, um eine öffentliche URL zu erhalten.", "6b80f5b38a8f9950": "Nur dieser Computer kann diese Adresse aufrufen. Verknüpfe T3 Connect für eine öffentliche URL.", "c5a7b1d3891dd0b8": "Funktioniert überall, wo die Adresse dieser Umgebung erreichbar ist, zum Beispiel über Tailscale oder deinen eigenen Proxy. Verknüpfe T3 Connect für eine öffentliche URL.", + "3669395daf36fd33": "Auf diesem Server nicht mehr registriert", + "fe513cf316e796e3": "Läuft als Teil anderer Workflows", + "ccf00b97925efab3": "Wird von Hand gestartet", + "421e585eb092b07b": "Startet bei {triggers}", + "7bd7c58592671384": "Braucht dich", + "834ca879c14c167b": "Arbeitet", + "582d6df7dfab86fb": "Pausiert", + "ea6583ce92507ee3": "Schläft", + "7ea8cb8af281ce93": "Wartet", + "1347868f2523140e": "Fertig", + "57d76c4614054271": "Gestoppt", + "5c7344bd51d0b966": "Übersprungen", + "b2074e9bd23049a6": "Abgebrochen", + "5bb7401807ee2fb5": "Fragt: {question} und {more} weitere", + "9e4286183d5f9e34": "Fragt: {question}", + "474c18d001bd6717": "Ein Schritt ist fehlgeschlagen", + "d3890f4eb1508781": "Führt eigene Schritte aus", + "3e7ced10c9482af0": "{step} arbeitet", + "237e1bcb1cf1bdec": "Schläft bei {step}", + "3f7b17ac5a20c8d2": "Führt {run} aus", + "0306f5f324b8aaa5": "{count} Ausführungen laufen", + "e8fd779b84a202a2": "Wartet", + "b6d55657e1a027b8": "Wartet auf {step}", + "e942562a42aede34": "Abgeschlossen", + "26b2b9727fe11289": "Vorzeitig beendet", "1bb995dcec481554": "Genehmige dieses Gerät auf {host}. Dort wird der Code {verificationCode} angezeigt.", "8696a33219944832": "Der Autorisierungsnachweis für die WebSocket-Verbindung konnte nicht erstellt werden.", "5678f133a8631f7d": "Deine Cloud-Anmeldung hat sich geändert. Melde dich erneut an, um die Umgebung zu autorisieren.", @@ -1743,6 +1768,8 @@ "2e995206e087c3fc": "Versuche zu antworten, sobald die Verbindung oder ausstehende Eingabe geklärt ist.", "604ec3067171a0d7": "Unterhaltung", "d6182a057ea12624": "Übergeordneter Thread", + "f2d8537c33cc55a5": "Schritt der Workflow-Ausführung", + "ba8337dca3232880": "Ausführung öffnen", "30fa4a764d11ae42": "{name} konnte nicht heruntergeladen werden", "4952f87dc98191a7": "Der Anhang ist nicht verfügbar.", "2fd6d178493fb407": "Die aktuelle Runde konnte nicht unterbrochen werden.", @@ -1828,6 +1855,7 @@ "04fd71efaa2c3b92": "Pull Requests öffnen", "57e875b79b98ab82": "Issues öffnen", "f1db0a234c777a1d": "T3 Code in einer anderen App verwenden (MCP)", + "6050f22f63e2bcb5": "Workflows öffnen", "a0cc19e60dd99851": "Nutzung öffnen", "46694969044eee98": "Nächsten Arbeitsbereich fokussieren", "0a1011328ba42eef": "Vorherigen Arbeitsbereich fokussieren", @@ -8869,6 +8897,8 @@ "9ae293971d93c819": "Teile einen Thread mit einem Gast, der ihn live im Browser verfolgt und Nachrichten sendet, die du genehmigst. Melde dich bei T3 Connect an, um Gastlinks zu nutzen.", "0aa5406ac4d7f7c7": "Gastlinks", "f0e853acd2006d53": "Verknüpfte Umgebungen", + "ef10c2dff987f3ea": "Führe mehrstufige Workflows aus Dateien im Ordner workflows des T3-Home dieses Servers aus. Öffne sie über die Befehlspalette. Solange es aus ist, läuft nichts aus diesem Ordner; Läufe warten, bis es wieder an ist.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Nach einer Claude- oder Codex-Runde eine vorhergesagte nächste Nachricht im leeren Eingabefeld anzeigen. Tab übernimmt sie. Jede ist eine zusätzliche gecachte Anfrage in deinem Tarif. Erfordert Codex 0.165+. Claude-Threads werden nach einem Neustart aktualisiert.", "d4b2a2ec812aafb0": "Nächsten Prompt vorschlagen", "298c7150a7621c80": "Simlock-Geräte-Hosts", @@ -11816,6 +11846,7 @@ "d443390c4d2dcfd4": "barrierefreiheit a11y screenreader nvda jaws voiceover orca sprachausgabe fenstertitel tab-titel alt tab taskleiste thread status reihenfolge arbeitet genehmigung", "6826fa9579c22035": "beta teilen gast einladen link teammitglied zuschauen t3 connect tunnel", "f10c06cba0cdf7fe": "beta anderen rechner verknüpfen vps peer agenten dort arbeiten delegieren", + "bc0b409d89ce086e": "beta workflow dauerhafte läufe automatisierung schritte zeitplan webhook ordner", "4a21cf825a2045b0": "beta tab autovervollständigung nächste nachricht vorhersagen claude codex ghost text", "fea2dc36585c4a20": "Simlock-Geräte-Hosts (Alpha)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lease gateway", @@ -12372,6 +12403,262 @@ "2cddd6095abc734a": "7 Tage", "53493056306708cf": "30 Tage", "c719359d18d37ad3": "90 Tage", + "0bd950151ddc6407": "Ohne Speichern verlassen? Deine Änderungen an dieser Datei gehen verloren.", + "c0ba3f6756b09f30": "Ungespeicherte Änderungen", + "6914e22d357f0ad6": "Gespeichert und aktiv", + "aff389354a031d6f": "Die Datei auf der Festplatte lässt sich nicht laden. Die letzte funktionierende Version läuft weiter.", + "858effde748ab563": "Gespeichert, läuft aber noch nicht.", + "ddb37138df660942": "Nicht gespeichert. Auf dem Server hat sich nichts geändert.", + "6ef4db489e40e39e": "Speichern fehlgeschlagen", + "c89624a2e9af1793": "{name} ist nicht verbunden", + "b5a352a43adb4c17": "Ihre Workflows erscheinen wieder, sobald sie sich neu verbindet. Wähle eine andere Umgebung, um deren Läufe zu sehen.", + "3dcedb736d20aae5": "Die Workflow-Dateien konnten nicht gelesen werden", + "b09f4df8d76ae8ea": "{file} löschen? Die darin definierten Workflows können dann nicht mehr gestartet werden.", + "b4535f5a03689d27": "{name} ist nicht verbunden. Was du hier schreibst, bleibt erhalten und lässt sich speichern, sobald die Verbindung wieder da ist.", + "b54c78d85fd942ea": "Gelöscht, aber was läuft, ist noch nicht nachgezogen.", + "407c228d7da0b7df": "Nicht gelöscht. Auf dem Server hat sich nichts geändert.", + "1a6aa10f3cc14fff": "Diese Dateien passen nicht zusammen. Was bisher lief, läuft weiter.", + "259312516a1dbe6f": "Dateiname", + "2f48ab2aa0586853": "Definiert keine Workflows", + "ba5adfa37b55b8c5": [ + "Zeile ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Löschen", + "84c900d1ae72adc6": "Speichern", + "5912d817be03247a": "Die Datei wurde auf der Festplatte geändert, während du sie bearbeitet hast. Speichern ersetzt diese Änderung.", + "0b1e6f5608826387": "Datei laden und meine Änderungen verwerfen", + "f47b4c06aeb77c1c": "Workflow-Dateien werden geladen…", + "4353bfd401d58f87": [ + "Jede Datei in", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "definiert Workflows. Änderungen werden ohne Neustart übernommen." + ], + "0c165251a06f10f1": "Neue Datei", + "8e97cf734b4463e7": "Erstellen", + "2ec0d5108fd6cebe": "Noch keine Workflows. Erstelle hier die erste Datei oder bitte einen Agenten, eine in diesem Ordner zu schreiben.", + "5601350626e8cfe9": "Lässt sich nicht laden", + "21d778a1b9a0c234": "Neben der Ausführung geöffnet", + "62dc4d3a19ff7ca0": "Tab schließen", + "1e25265f2758fce3": "Als vollständigen Thread öffnen", + "672a3dae06b39402": "Auf eigener Seite öffnen", + "7755500a4cde5066": "Bereich schließen", + "b8dcbc93a2ca1861": "Diese Ausführung führt es nicht mehr auf.", + "115c69de3202f664": "Öffnen", + "644eafa9048b62df": "{count, plural, =1 {1. Versuch} =2 {2. Versuch} =3 {3. Versuch} other {{count}. Versuch}}", + "e39f89c909df4db0": "Die Ausführung konnte nicht fortgesetzt werden", + "865f034346b82f47": "{title} abbrechen? Die Agenten stoppen und die Ausführung kann nicht fortgesetzt werden.", + "6bc75632fd9c9136": "Die Ausführung konnte nicht abgebrochen werden", + "64e50329dcfdd5b0": "Abgeschlossen", + "350162e7cc1ebea4": "Gestoppt", + "0875cf506f4c6810": "Übersprungen", + "3cc43f1dbf3f8e0c": "Abgebrochen", + "ded70e75de6404ba": "Zurück zur Liste der Ausführungen", + "2f4ed7dbd22be30d": "Ausführung abbrechen", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "dauerte {duration}", + "aff78e1774818ff4": "bisher {duration}", + "38eddd466439afc9": "Was die Ausführung berührt hat", + "156ec271d49ddd70": "Was passiert ist", + "34f59bbbead0b97f": "{names} und {count} weitere", + "ac1556f6ce89a5ea": "{count} parallel", + "e197c4963bacc746": "{count} laufen", + "f5319ed9e18c0df1": "Fragt dich", + "882a25e9084ae1b2": "Pausiert", + "9a03d8a9afc60387": "Bisherige Schritte", + "2f2ae791afe01674": "wartet auf deine Freigabe", + "24f8060c4ccdf928": "startet", + "30a5be40eb956663": "arbeitet", + "dd7a1e58c2553933": "wacht in {duration} auf", + "95cc952724dd7310": "wacht gleich auf", + "3cc34921c0128593": "läuft", + "e777db2880f53a46": "niemand hat geantwortet", + "dc90739d391a5e67": "Du hast {choice} gesagt", + "389f2563b5b763fd": "Kurze Schritte", + "a41c8d758121ad81": "hat geschlafen", + "9db248b770096984": "hat gewartet", + "c76124517af28686": "läuft seit {duration}", + "89102905bf09b0e8": "Live ansehen", + "bdf338cdff4118f0": "Transkript", + "811e7e992f9ff820": "kann erst weitergehen, wenn ihre Workflow-Version wieder registriert ist", + "4d4cdf035e98dd57": "wartet darauf, dass du sie fortsetzt", + "eb5b21dd224a5941": "versucht es in {duration} von selbst erneut", + "6ab3dfa749fde477": "versucht es gleich von selbst erneut", + "44b6463aa70aa14c": "Grund der Pause", + "cf25e7169ab0eb7a": "Pausiert bei {step}", + "56c48c1f220f2754": "Die Frage konnte nicht beantwortet werden", + "a3c43735e1a81498": "Begründung für {title}", + "bfad234f016cfa3f": "Warum, in einem Satz. Gilt für die Antwort, die du wählst.", + "004c41aff9c97873": "Ausführungen", + "4dc0c244a2419f6c": [ + "Teil von ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "gestartet", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "ihre Version ist nicht mehr registriert", + "f92d9132f7b85d1a": "Schritte werden geladen…", + "6ebc59f64c761a49": "Noch nichts.", + "a759dccd157d7dae": [ + "Du hast", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " gesagt." + ], + "593b425188346781": [ + "Du hast", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " gesagt: ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Ausführung öffnen", + "c8eb9be36d4d51ad": [ + "Thread auf ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Fortsetzen", + "8cebd63fc4c967d5": "Nur der fehlgeschlagene Schritt läuft erneut; zuvor Abgeschlossenes bleibt erhalten.", + "bc1e0a2a0f1e9552": "Braucht dich", + "a812f51e970740f1": [ + "gefragt", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· die Ausführung wartet auf dich" + ], + "02dfe6c63fd0b8a1": "Begründung hinzufügen", + "19abd94828a3bdbc": "Erst den Agenten fragen", + "a18721fa8f328361": "Braucht dich", + "bbf24e7920c1e86b": "Läuft", + "8d6e18d2ad832db6": "Alle", + "f25af5332ffc3734": "Nichts wartet auf dich.", + "c3f0119b8d6231f8": "Es läuft nichts.", + "33028dfc1229eaa6": "Noch keine Ausführungen.", + "5459bf696a187c26": "Workflow-Ausführungen konnten nicht geladen werden", + "d57c35d43b0f163a": "Diesen Lauf gibt es hier nicht", + "b9aae2f7cdb1a379": "Noch keine Workflow-Ausführungen", + "8f15f66e545af7c0": "Welche Ausführungen", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Alle {count} Workflows", + "46d614fa7b4bf1e5": "Workflow-Ausführungen", + "1c635faa2fb45b8b": "Noch nie gelaufen.", + "156ff7b625287a1e": "Übersprungene ausblenden", + "69b985b97ab45e6b": "{count} übersprungene anzeigen", + "2400254d362de84d": "Workflow-Ausführungen werden geladen…", + "145e1f7503ba3b2c": [ + "Diese Umgebung hat keinen Lauf mit diesem Link.", + " ", + { + "t": "button", + "i": 1, + "c": "Zurück zu den Läufen" + } + ], + "783e616cb0476c17": [ + "Ein Workflow verbindet Agenten, Code, Zeitpläne und Fragen an dich zu einer Ausführung, die Neustarts übersteht. Schreib einen unter", + " ", + { + "t": "button", + "i": 1, + "c": "Definitionen" + }, + ", oder bitte einen Agenten darum.", + " ", + { + "t": "a", + "i": 2, + "c": "Anleitung lesen" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Eine Workflow-Datei hat ein Problem." + }, + " ", + "Die letzte funktionierende Version läuft weiter." + ], + "ed8ce6ebc73dc12d": "Datei öffnen", + "5d8d278ff828102d": "Alle Workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · Transkript", + "c512071143a5ba32": "Diesen Thread gibt es nicht mehr.", + "ed169d23683fb6ac": "Thread wird geladen…", + "290e0ab40b87dc17": "Workflows-Breadcrumb", + "683dd9831e54edc0": "Umgebung", + "34ad53646f06ed80": "Workflows sind aus", + "8f6589c9e0ac5d4e": "Keine Umgebung verbunden", + "744127f8dfad7d22": "Verbinde eine Umgebung, um ihre Workflow-Ausführungen zu sehen.", + "036182ec7e2ee4d4": "Neben der Ausführung", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definitionen", + "f0a212aadfe1257b": "Editor wird geladen…", + "20f194e003885e95": [ + "Aktiviere sie für diesen Server in den", + " ", + { + "t": "Link", + "i": 1, + "c": "Einstellungen → Labs" + }, + "." + ], "8367779e149f723b": "Anfrage an die primäre Umgebung während {operation} fehlgeschlagen (HTTP {status}).", "c5cd027743a2b5a6": "Ungültiges Kopplungstoken. Prüfe das Token und versuch es erneut.", "0e4b49c8203aae81": "Zeitüberschreitung beim Warten auf eine authentifizierte Sitzung nach dem Bootstrap.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 0cc2d503fd620..e3e810fe437bc 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Link this environment to T3 Connect for a public URL.", "6b80f5b38a8f9950": "Only this computer can call this address. Link T3 Connect for a public URL.", "c5a7b1d3891dd0b8": "Works wherever this environment's address is reachable, for example over Tailscale or your own proxy. Link T3 Connect for a public URL.", + "3669395daf36fd33": "No longer registered on this server", + "fe513cf316e796e3": "Runs as part of other workflows", + "ccf00b97925efab3": "Started by hand", + "421e585eb092b07b": "Starts on {triggers}", + "7bd7c58592671384": "Needs you", + "834ca879c14c167b": "Working", + "582d6df7dfab86fb": "Paused", + "ea6583ce92507ee3": "Sleeping", + "7ea8cb8af281ce93": "Waiting", + "1347868f2523140e": "Done", + "57d76c4614054271": "Stopped", + "5c7344bd51d0b966": "Skipped", + "b2074e9bd23049a6": "Cancelled", + "5bb7401807ee2fb5": "Asks: {question} and {more} more", + "9e4286183d5f9e34": "Asks: {question}", + "474c18d001bd6717": "A step failed", + "d3890f4eb1508781": "Running its own steps", + "3e7ced10c9482af0": "{step} is working", + "237e1bcb1cf1bdec": "Sleeping at {step}", + "3f7b17ac5a20c8d2": "Runs {run}", + "0306f5f324b8aaa5": "{count} runs under way", + "e8fd779b84a202a2": "Waiting", + "b6d55657e1a027b8": "Waiting for {step}", + "e942562a42aede34": "Finished", + "26b2b9727fe11289": "Ended early", "1bb995dcec481554": "Approve this device on {host}. It shows code {verificationCode}.", "8696a33219944832": "Could not create the websocket authorization proof.", "5678f133a8631f7d": "Your cloud sign-in changed. Sign in again to authorize the environment.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Try replying after the connection or pending input is resolved.", "604ec3067171a0d7": "Conversation", "d6182a057ea12624": "Parent thread", + "f2d8537c33cc55a5": "Step of the workflow run", + "ba8337dca3232880": "Open run", "30fa4a764d11ae42": "Could not download {name}", "4952f87dc98191a7": "The attachment is unavailable.", "2fd6d178493fb407": "Failed to interrupt the current turn.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Open pull requests", "57e875b79b98ab82": "Open issues", "f1db0a234c777a1d": "Use T3 Code in another app (MCP)", + "6050f22f63e2bcb5": "Open workflows", "a0cc19e60dd99851": "Open usage", "46694969044eee98": "Focus Next Workspace Area", "0a1011328ba42eef": "Focus Previous Workspace Area", @@ -8877,6 +8905,8 @@ "9ae293971d93c819": "Share a thread with a guest who watches it live in a browser and sends messages you approve. Sign in to T3 Connect to use guest links.", "0aa5406ac4d7f7c7": "Guest links", "f0e853acd2006d53": "Linked environments", + "ef10c2dff987f3ea": "Run multi-step workflows from files in the workflows folder of this server's T3 home. Open them from the command palette. While off, nothing in that folder runs; runs wait until it is on again.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Show a predicted next message in the empty composer after a Claude or Codex turn. Tab uses it. Each is an extra cached request on your plan. Needs Codex 0.165+. Claude threads update on restart.", "d4b2a2ec812aafb0": "Suggest next prompt", "298c7150a7621c80": "Simlock device hosts", @@ -11824,6 +11854,7 @@ "d443390c4d2dcfd4": "accessibility a11y screen reader nvda jaws voiceover orca narrator window title tab title alt tab taskbar thread status order working approval", "6826fa9579c22035": "beta share guest invite link teammate watch t3 connect tunnel", "f10c06cba0cdf7fe": "beta link another machine vps peer agents work there delegate", + "bc0b409d89ce086e": "beta workflow durable runs automation steps schedule webhook folder", "4a21cf825a2045b0": "beta tab autocomplete predict next message claude codex ghost text", "fea2dc36585c4a20": "Simlock device hosts (alpha)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lease gateway", @@ -12380,6 +12411,262 @@ "2cddd6095abc734a": "7 days", "53493056306708cf": "30 days", "c719359d18d37ad3": "90 days", + "0bd950151ddc6407": "Leave without saving? Your changes to this file are lost.", + "c0ba3f6756b09f30": "Unsaved changes", + "6914e22d357f0ad6": "Saved and running", + "aff389354a031d6f": "The file on disk does not load. The last version that did keeps running.", + "858effde748ab563": "Saved, but it does not run yet.", + "ddb37138df660942": "Not saved. Nothing changed on the server.", + "6ef4db489e40e39e": "Could not save", + "c89624a2e9af1793": "{name} is not connected", + "b5a352a43adb4c17": "Its workflows show again when it reconnects. Pick another environment to see its runs.", + "3dcedb736d20aae5": "Could not read the workflow files", + "b09f4df8d76ae8ea": "Delete {file}? The workflows it defines can no longer be started.", + "b4535f5a03689d27": "{name} is not connected. What you write here stays, and saves once it is back.", + "b54c78d85fd942ea": "Deleted, but what runs has not caught up yet.", + "407c228d7da0b7df": "Not deleted. Nothing changed on the server.", + "1a6aa10f3cc14fff": "These files do not fit together. What ran before keeps running.", + "259312516a1dbe6f": "File name", + "2f48ab2aa0586853": "Defines no workflows", + "ba5adfa37b55b8c5": [ + "Line ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Delete", + "84c900d1ae72adc6": "Save", + "5912d817be03247a": "The file changed on disk while you were editing. Saving replaces that change.", + "0b1e6f5608826387": "Load the file and drop my changes", + "f47b4c06aeb77c1c": "Loading the workflow files…", + "4353bfd401d58f87": [ + "Every file in", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "defines workflows. A change to one is picked up without a restart." + ], + "0c165251a06f10f1": "New file", + "8e97cf734b4463e7": "Create", + "2ec0d5108fd6cebe": "No workflows yet. Make the first file here, or ask an agent to write one in that folder.", + "5601350626e8cfe9": "Does not load", + "21d778a1b9a0c234": "Open beside the run", + "62dc4d3a19ff7ca0": "Close tab", + "1e25265f2758fce3": "Open as a full thread", + "672a3dae06b39402": "Open on its own page", + "7755500a4cde5066": "Close the pane", + "b8dcbc93a2ca1861": "This run no longer lists it.", + "115c69de3202f664": "Open", + "644eafa9048b62df": "{count, plural, =1 {1st try} =2 {2nd try} =3 {3rd try} other {{count}th try}}", + "e39f89c909df4db0": "Could not resume the run", + "865f034346b82f47": "Cancel {title}? Its agents stop and the run cannot be resumed.", + "6bc75632fd9c9136": "Could not cancel the run", + "64e50329dcfdd5b0": "Finished", + "350162e7cc1ebea4": "Stopped", + "0875cf506f4c6810": "Skipped", + "3cc43f1dbf3f8e0c": "Cancelled", + "ded70e75de6404ba": "Back to the list of runs", + "2f4ed7dbd22be30d": "Cancel run", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "took {duration}", + "aff78e1774818ff4": "{duration} so far", + "38eddd466439afc9": "What the run touched", + "156ec271d49ddd70": "What happened", + "34f59bbbead0b97f": "{names} and {count} more", + "ac1556f6ce89a5ea": "{count} in parallel", + "e197c4963bacc746": "{count} running", + "f5319ed9e18c0df1": "Asks you", + "882a25e9084ae1b2": "Paused", + "9a03d8a9afc60387": "Steps so far", + "2f2ae791afe01674": "waits for your approval", + "24f8060c4ccdf928": "starting", + "30a5be40eb956663": "working", + "dd7a1e58c2553933": "wakes in {duration}", + "95cc952724dd7310": "about to wake", + "3cc34921c0128593": "running", + "e777db2880f53a46": "nobody answered", + "dc90739d391a5e67": "You said {choice}", + "389f2563b5b763fd": "Quick steps", + "a41c8d758121ad81": "slept", + "9db248b770096984": "waited", + "c76124517af28686": "running for {duration}", + "89102905bf09b0e8": "Watch live", + "bdf338cdff4118f0": "Transcript", + "811e7e992f9ff820": "cannot go on until its workflow version is registered again", + "4d4cdf035e98dd57": "waits for you to resume it", + "eb5b21dd224a5941": "tries again by itself in {duration}", + "6ab3dfa749fde477": "about to try again by itself", + "44b6463aa70aa14c": "Why it paused", + "cf25e7169ab0eb7a": "Paused at {step}", + "56c48c1f220f2754": "Could not answer the question", + "a3c43735e1a81498": "Reason for {title}", + "bfad234f016cfa3f": "Why, in a sentence. It goes with whichever answer you pick.", + "004c41aff9c97873": "Runs", + "4dc0c244a2419f6c": [ + "Part of ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "started", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "its version is no longer registered", + "f92d9132f7b85d1a": "Loading steps…", + "6ebc59f64c761a49": "Nothing yet.", + "a759dccd157d7dae": [ + "You said", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "You said", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Open run", + "c8eb9be36d4d51ad": [ + "Thread on ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Resume", + "8cebd63fc4c967d5": "Only the failed step runs again; what finished before it is kept.", + "bc1e0a2a0f1e9552": "Needs you", + "a812f51e970740f1": [ + "asked", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· the run waits for you" + ], + "02dfe6c63fd0b8a1": "Add a reason", + "19abd94828a3bdbc": "Ask the agent first", + "a18721fa8f328361": "Needs you", + "bbf24e7920c1e86b": "Running", + "8d6e18d2ad832db6": "All", + "f25af5332ffc3734": "Nothing waits on you.", + "c3f0119b8d6231f8": "Nothing is running.", + "33028dfc1229eaa6": "No runs yet.", + "5459bf696a187c26": "Could not load workflow runs", + "d57c35d43b0f163a": "This run is not here", + "b9aae2f7cdb1a379": "No workflow runs yet", + "8f15f66e545af7c0": "Which runs", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "All {count} workflows", + "46d614fa7b4bf1e5": "Workflow runs", + "1c635faa2fb45b8b": "Has not run yet.", + "156ff7b625287a1e": "Hide skipped", + "69b985b97ab45e6b": "Show {count} skipped", + "2400254d362de84d": "Loading workflow runs…", + "145e1f7503ba3b2c": [ + "This environment has no run with that link.", + " ", + { + "t": "button", + "i": 1, + "c": "Back to the runs" + } + ], + "783e616cb0476c17": [ + "A workflow ties agents, code, schedules and questions to you into one run that survives restarts. Write one under", + " ", + { + "t": "button", + "i": 1, + "c": "Definitions" + }, + ", or ask an agent to.", + " ", + { + "t": "a", + "i": 2, + "c": "Read the guide" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "A workflow file has a problem." + }, + " ", + "The last version that did keeps running." + ], + "ed8ce6ebc73dc12d": "Open the file", + "5d8d278ff828102d": "All workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transcript", + "c512071143a5ba32": "This thread is no longer there.", + "ed169d23683fb6ac": "Loading the thread…", + "290e0ab40b87dc17": "Workflows breadcrumb", + "683dd9831e54edc0": "Environment", + "34ad53646f06ed80": "Workflows are off", + "8f6589c9e0ac5d4e": "No environment connected", + "744127f8dfad7d22": "Connect an environment to see its workflow runs.", + "036182ec7e2ee4d4": "Beside the run", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definitions", + "f0a212aadfe1257b": "Loading the editor…", + "20f194e003885e95": [ + "Turn them on for this server in", + " ", + { + "t": "Link", + "i": 1, + "c": "Settings → Labs" + }, + "." + ], "8367779e149f723b": "Primary environment request failed during {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Invalid pairing token. Check the token and try again.", "0e4b49c8203aae81": "Timed out waiting for authenticated session after bootstrap.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index daf936020ff3a..b15af98ce01ba 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Vincula este entorno a T3 Connect para tener una URL pública.", "6b80f5b38a8f9950": "Solo este equipo puede llamar a esta dirección. Vincula T3 Connect para tener una URL pública.", "c5a7b1d3891dd0b8": "Funciona donde se pueda acceder a la dirección de este entorno, por ejemplo a través de Tailscale o de tu propio proxy. Vincula T3 Connect para tener una URL pública.", + "3669395daf36fd33": "Ya no está registrado en este servidor", + "fe513cf316e796e3": "Se ejecuta como parte de otros flujos de trabajo", + "ccf00b97925efab3": "Se inicia a mano", + "421e585eb092b07b": "Se inicia con {triggers}", + "7bd7c58592671384": "Te necesitan", + "834ca879c14c167b": "Trabajando", + "582d6df7dfab86fb": "En pausa", + "ea6583ce92507ee3": "Durmiendo", + "7ea8cb8af281ce93": "Esperando", + "1347868f2523140e": "Terminada", + "57d76c4614054271": "Detenida", + "5c7344bd51d0b966": "Omitida", + "b2074e9bd23049a6": "Cancelada", + "5bb7401807ee2fb5": "Pregunta: {question} y {more} más", + "9e4286183d5f9e34": "Pregunta: {question}", + "474c18d001bd6717": "Falló un paso", + "d3890f4eb1508781": "Ejecuta sus propios pasos", + "3e7ced10c9482af0": "{step} está trabajando", + "237e1bcb1cf1bdec": "Durmiendo en {step}", + "3f7b17ac5a20c8d2": "Ejecuta {run}", + "0306f5f324b8aaa5": "{count} ejecuciones en curso", + "e8fd779b84a202a2": "Esperando", + "b6d55657e1a027b8": "Esperando a {step}", + "e942562a42aede34": "Finalizada", + "26b2b9727fe11289": "Terminó antes de tiempo", "1bb995dcec481554": "Aprueba este dispositivo en {host}. Muestra el código {verificationCode}.", "8696a33219944832": "No se pudo crear la prueba de autorización del websocket.", "5678f133a8631f7d": "Tu inicio de sesión en la nube cambió. Vuelve a iniciar sesión para autorizar el entorno.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Prueba a responder cuando se resuelva la conexión o la entrada pendiente.", "604ec3067171a0d7": "Conversación", "d6182a057ea12624": "Hilo principal", + "f2d8537c33cc55a5": "Paso de la ejecución del flujo de trabajo", + "ba8337dca3232880": "Abrir ejecución", "30fa4a764d11ae42": "No se pudo descargar {name}", "4952f87dc98191a7": "El adjunto no está disponible.", "2fd6d178493fb407": "No se pudo interrumpir el turno actual.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Abrir pull requests", "57e875b79b98ab82": "Abrir issues", "f1db0a234c777a1d": "Usar T3 Code en otra app (MCP)", + "6050f22f63e2bcb5": "Abrir flujos de trabajo", "a0cc19e60dd99851": "Abrir uso", "46694969044eee98": "Enfocar la siguiente área de trabajo", "0a1011328ba42eef": "Enfocar el área de trabajo anterior", @@ -8867,6 +8895,8 @@ "9ae293971d93c819": "Comparte un hilo con un invitado que lo ve en directo en un navegador y envía mensajes que tú apruebas. Inicia sesión en T3 Connect para usar enlaces de invitado.", "0aa5406ac4d7f7c7": "Enlaces de invitado", "f0e853acd2006d53": "Entornos vinculados", + "ef10c2dff987f3ea": "Ejecuta flujos de trabajo de varios pasos a partir de archivos en la carpeta workflows del directorio T3 de este servidor. Ábrelos desde la paleta de comandos. Mientras está desactivado, no se ejecuta nada de esa carpeta; las ejecuciones esperan hasta que se vuelva a activar.", + "2dadb2359422121c": "Flujos de trabajo", "13e86eb5d8287a71": "Muestra un mensaje siguiente previsto en el cuadro de mensaje vacío tras un turno de Claude o Codex. Tab lo usa. Cada uno es una solicitud extra en caché de tu plan. Requiere Codex 0.165+. Los hilos de Claude se actualizan al reiniciar.", "d4b2a2ec812aafb0": "Sugerir el siguiente prompt", "298c7150a7621c80": "Hosts de dispositivos Simlock", @@ -11809,6 +11839,7 @@ "d443390c4d2dcfd4": "accesibilidad a11y lector de pantalla nvda jaws voiceover orca narrador título de ventana título de pestaña alt tab barra de tareas estado del hilo orden en curso aprobación", "6826fa9579c22035": "beta compartir invitado invitar enlace compañero ver t3 connect túnel", "f10c06cba0cdf7fe": "beta vincular otra máquina vps agentes pares trabajar allí delegar", + "bc0b409d89ce086e": "beta flujo de trabajo workflow ejecuciones duraderas automatización pasos programación webhook carpeta", "4a21cf825a2045b0": "beta tab autocompletar predecir siguiente mensaje claude codex texto fantasma", "fea2dc36585c4a20": "Hosts de dispositivos Simlock (alfa)", "9d834d178130180e": "beta alfa simlock callstack simulador emulador ios android grupo préstamo gateway", @@ -12365,6 +12396,262 @@ "2cddd6095abc734a": "7 días", "53493056306708cf": "30 días", "c719359d18d37ad3": "90 días", + "0bd950151ddc6407": "¿Salir sin guardar? Se perderán tus cambios en este archivo.", + "c0ba3f6756b09f30": "Cambios sin guardar", + "6914e22d357f0ad6": "Guardado y en ejecución", + "aff389354a031d6f": "El archivo en disco no se carga. Sigue en ejecución la última versión que sí cargó.", + "858effde748ab563": "Guardado, pero todavía no se ejecuta.", + "ddb37138df660942": "No se guardó. No cambió nada en el servidor.", + "6ef4db489e40e39e": "No se pudo guardar", + "c89624a2e9af1793": "{name} no está conectado", + "b5a352a43adb4c17": "Sus flujos de trabajo vuelven a mostrarse cuando se reconecta. Elige otro entorno para ver sus ejecuciones.", + "3dcedb736d20aae5": "No se pudieron leer los archivos de flujos de trabajo", + "b09f4df8d76ae8ea": "¿Eliminar {file}? Los flujos de trabajo que define ya no se podrán iniciar.", + "b4535f5a03689d27": "{name} no está conectado. Lo que escribas aquí se conserva y se puede guardar en cuanto vuelva.", + "b54c78d85fd942ea": "Eliminado, pero lo que se ejecuta aún no se ha actualizado.", + "407c228d7da0b7df": "No se eliminó. No cambió nada en el servidor.", + "1a6aa10f3cc14fff": "Estos archivos no encajan entre sí. Lo que se ejecutaba antes sigue en ejecución.", + "259312516a1dbe6f": "Nombre del archivo", + "2f48ab2aa0586853": "No define ningún flujo de trabajo", + "ba5adfa37b55b8c5": [ + "Línea ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Eliminar", + "84c900d1ae72adc6": "Guardar", + "5912d817be03247a": "El archivo cambió en disco mientras lo editabas. Al guardar se reemplaza ese cambio.", + "0b1e6f5608826387": "Cargar el archivo y descartar mis cambios", + "f47b4c06aeb77c1c": "Cargando los archivos de flujos de trabajo…", + "4353bfd401d58f87": [ + "Cada archivo de", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "define flujos de trabajo. Los cambios se aplican sin reiniciar." + ], + "0c165251a06f10f1": "Nuevo archivo", + "8e97cf734b4463e7": "Crear", + "2ec0d5108fd6cebe": "Aún no hay flujos de trabajo. Crea aquí el primer archivo o pide a un agente que escriba uno en esa carpeta.", + "5601350626e8cfe9": "No se carga", + "21d778a1b9a0c234": "Abierto junto a la ejecución", + "62dc4d3a19ff7ca0": "Cerrar pestaña", + "1e25265f2758fce3": "Abrir como hilo completo", + "672a3dae06b39402": "Abrir en su propia página", + "7755500a4cde5066": "Cerrar el panel", + "b8dcbc93a2ca1861": "Esta ejecución ya no lo incluye.", + "115c69de3202f664": "Abrir", + "644eafa9048b62df": "{count, plural, =1 {1.er intento} =2 {2.º intento} =3 {3.er intento} other {{count}.º intento}}", + "e39f89c909df4db0": "No se pudo reanudar la ejecución", + "865f034346b82f47": "¿Cancelar {title}? Sus agentes se detienen y la ejecución no se podrá reanudar.", + "6bc75632fd9c9136": "No se pudo cancelar la ejecución", + "64e50329dcfdd5b0": "Finalizada", + "350162e7cc1ebea4": "Detenida", + "0875cf506f4c6810": "Omitida", + "3cc43f1dbf3f8e0c": "Cancelada", + "ded70e75de6404ba": "Volver a la lista de ejecuciones", + "2f4ed7dbd22be30d": "Cancelar ejecución", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "tardó {duration}", + "aff78e1774818ff4": "{duration} hasta ahora", + "38eddd466439afc9": "Lo que tocó la ejecución", + "156ec271d49ddd70": "Qué ocurrió", + "34f59bbbead0b97f": "{names} y {count} más", + "ac1556f6ce89a5ea": "{count} en paralelo", + "e197c4963bacc746": "{count} en curso", + "f5319ed9e18c0df1": "Te pregunta", + "882a25e9084ae1b2": "En pausa", + "9a03d8a9afc60387": "Pasos hasta ahora", + "2f2ae791afe01674": "espera tu aprobación", + "24f8060c4ccdf928": "empezando", + "30a5be40eb956663": "trabajando", + "dd7a1e58c2553933": "despierta en {duration}", + "95cc952724dd7310": "a punto de despertar", + "3cc34921c0128593": "en curso", + "e777db2880f53a46": "nadie respondió", + "dc90739d391a5e67": "Dijiste {choice}", + "389f2563b5b763fd": "Pasos rápidos", + "a41c8d758121ad81": "en espera", + "9db248b770096984": "esperó", + "c76124517af28686": "en ejecución desde hace {duration}", + "89102905bf09b0e8": "Ver en directo", + "bdf338cdff4118f0": "Transcripción", + "811e7e992f9ff820": "no puede continuar hasta que su versión del flujo de trabajo vuelva a registrarse", + "4d4cdf035e98dd57": "espera a que la reanudes", + "eb5b21dd224a5941": "lo reintenta sola en {duration}", + "6ab3dfa749fde477": "a punto de reintentarlo sola", + "44b6463aa70aa14c": "Por qué se pausó", + "cf25e7169ab0eb7a": "En pausa en {step}", + "56c48c1f220f2754": "No se pudo responder a la pregunta", + "a3c43735e1a81498": "Motivo de {title}", + "bfad234f016cfa3f": "El porqué, en una frase. Acompaña a la respuesta que elijas.", + "004c41aff9c97873": "Ejecuciones", + "4dc0c244a2419f6c": [ + "Parte de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "iniciada", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "su versión ya no está registrada", + "f92d9132f7b85d1a": "Cargando pasos…", + "6ebc59f64c761a49": "Nada todavía.", + "a759dccd157d7dae": [ + "Dijiste", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Dijiste", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Abrir ejecución", + "c8eb9be36d4d51ad": [ + "Hilo en ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Reanudar", + "8cebd63fc4c967d5": "Solo se vuelve a ejecutar el paso que falló; lo que terminó antes se conserva.", + "bc1e0a2a0f1e9552": "Te necesitan", + "a812f51e970740f1": [ + "preguntó", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· la ejecución te espera" + ], + "02dfe6c63fd0b8a1": "Añadir un motivo", + "19abd94828a3bdbc": "Preguntar antes al agente", + "a18721fa8f328361": "Te necesitan", + "bbf24e7920c1e86b": "En ejecución", + "8d6e18d2ad832db6": "Todas", + "f25af5332ffc3734": "Nada espera tu respuesta.", + "c3f0119b8d6231f8": "No hay nada en ejecución.", + "33028dfc1229eaa6": "Aún no hay ejecuciones.", + "5459bf696a187c26": "No se pudieron cargar las ejecuciones de flujos de trabajo", + "d57c35d43b0f163a": "Esta ejecución no está aquí", + "b9aae2f7cdb1a379": "Aún no hay ejecuciones de flujos de trabajo", + "8f15f66e545af7c0": "Qué ejecuciones", + "b6409289e0c9a4dd": "Flujo de trabajo", + "035cb02ca1ae4952": "Los {count} flujos de trabajo", + "46d614fa7b4bf1e5": "Ejecuciones de flujos de trabajo", + "1c635faa2fb45b8b": "Aún no se ha ejecutado.", + "156ff7b625287a1e": "Ocultar omitidos", + "69b985b97ab45e6b": "Mostrar {count} omitidos", + "2400254d362de84d": "Cargando ejecuciones de flujos de trabajo…", + "145e1f7503ba3b2c": [ + "Este entorno no tiene ninguna ejecución con ese enlace.", + " ", + { + "t": "button", + "i": 1, + "c": "Volver a las ejecuciones" + } + ], + "783e616cb0476c17": [ + "Un flujo de trabajo une agentes, código, programaciones y preguntas para ti en una sola ejecución que sobrevive a los reinicios. Escribe uno en", + " ", + { + "t": "button", + "i": 1, + "c": "Definiciones" + }, + ", o pídeselo a un agente.", + " ", + { + "t": "a", + "i": 2, + "c": "Leer la guía" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Un archivo de flujo de trabajo tiene un problema." + }, + " ", + "Sigue en ejecución la última versión que sí cargó." + ], + "ed8ce6ebc73dc12d": "Abrir el archivo", + "5d8d278ff828102d": "Todos los flujos de trabajo", + "39459da07479f482": "Agente", + "7741243632056b81": "{step} · transcripción", + "c512071143a5ba32": "Este hilo ya no existe.", + "ed169d23683fb6ac": "Cargando el hilo…", + "290e0ab40b87dc17": "Ruta de navegación de flujos de trabajo", + "683dd9831e54edc0": "Entorno", + "34ad53646f06ed80": "Los flujos de trabajo están desactivados", + "8f6589c9e0ac5d4e": "Ningún entorno conectado", + "744127f8dfad7d22": "Conecta un entorno para ver sus ejecuciones de flujos de trabajo.", + "036182ec7e2ee4d4": "Junto a la ejecución", + "2d6107cb78382d08": "Flujos de trabajo", + "16f7df687349b399": "Definiciones", + "f0a212aadfe1257b": "Cargando el editor…", + "20f194e003885e95": [ + "Actívalos para este servidor en", + " ", + { + "t": "Link", + "i": 1, + "c": "Ajustes → Labs" + }, + "." + ], "8367779e149f723b": "Falló una solicitud al entorno principal durante {operation} (HTTP {status}).", "c5cd027743a2b5a6": "El token de emparejamiento no es válido. Revísalo e inténtalo de nuevo.", "0e4b49c8203aae81": "Se agotó el tiempo de espera de la sesión autenticada tras el arranque.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 713eca77f3127..f2f519b25ae0b 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Associez cet environnement à T3 Connect pour obtenir une URL publique.", "6b80f5b38a8f9950": "Seul cet ordinateur peut appeler cette adresse. Associez T3 Connect pour obtenir une URL publique.", "c5a7b1d3891dd0b8": "Fonctionne partout où l’adresse de cet environnement est joignable, par exemple via Tailscale ou votre propre proxy. Associez T3 Connect pour obtenir une URL publique.", + "3669395daf36fd33": "N’est plus enregistré sur ce serveur", + "fe513cf316e796e3": "S’exécute dans le cadre d’autres workflows", + "ccf00b97925efab3": "Démarré à la main", + "421e585eb092b07b": "Démarre sur {triggers}", + "7bd7c58592671384": "Vous attendent", + "834ca879c14c167b": "En cours", + "582d6df7dfab86fb": "En pause", + "ea6583ce92507ee3": "En veille", + "7ea8cb8af281ce93": "En attente", + "1347868f2523140e": "Terminée", + "57d76c4614054271": "Arrêtée", + "5c7344bd51d0b966": "Ignorée", + "b2074e9bd23049a6": "Annulée", + "5bb7401807ee2fb5": "Demande : {question} et {more} de plus", + "9e4286183d5f9e34": "Demande : {question}", + "474c18d001bd6717": "Une étape a échoué", + "d3890f4eb1508781": "Exécute ses propres étapes", + "3e7ced10c9482af0": "{step} est en cours", + "237e1bcb1cf1bdec": "En veille à {step}", + "3f7b17ac5a20c8d2": "Exécute {run}", + "0306f5f324b8aaa5": "{count} exécutions en cours", + "e8fd779b84a202a2": "En attente", + "b6d55657e1a027b8": "En attente de {step}", + "e942562a42aede34": "Terminée", + "26b2b9727fe11289": "Terminée prématurément", "1bb995dcec481554": "Approuvez cet appareil sur {host}. Il affiche le code {verificationCode}.", "8696a33219944832": "Impossible de créer la preuve d’autorisation WebSocket.", "5678f133a8631f7d": "Votre connexion cloud a changé. Reconnectez-vous pour autoriser l’environnement.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Réessayez de répondre une fois la connexion ou la saisie en attente résolue.", "604ec3067171a0d7": "Conversation", "d6182a057ea12624": "Fil parent", + "f2d8537c33cc55a5": "Étape de l’exécution du workflow", + "ba8337dca3232880": "Ouvrir l’exécution", "30fa4a764d11ae42": "Impossible de télécharger {name}", "4952f87dc98191a7": "La pièce jointe est indisponible.", "2fd6d178493fb407": "Échec de l’interruption du tour en cours.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Ouvrir les pull requests", "57e875b79b98ab82": "Ouvrir les tickets", "f1db0a234c777a1d": "Utiliser T3 Code dans une autre app (MCP)", + "6050f22f63e2bcb5": "Ouvrir les workflows", "a0cc19e60dd99851": "Ouvrir l’utilisation", "46694969044eee98": "Activer la zone de travail suivante", "0a1011328ba42eef": "Activer la zone de travail précédente", @@ -8868,6 +8896,8 @@ "9ae293971d93c819": "Partagez un fil avec un invité qui le suit en direct dans un navigateur et envoie des messages que vous approuvez. Connectez-vous à T3 Connect pour utiliser les liens invités.", "0aa5406ac4d7f7c7": "Liens invités", "f0e853acd2006d53": "Environnements associés", + "ef10c2dff987f3ea": "Exécutez des workflows en plusieurs étapes à partir des fichiers du dossier workflows du répertoire T3 de ce serveur. Ouvrez-les depuis la palette de commandes. Tant que c'est désactivé, rien dans ce dossier ne s'exécute ; les exécutions attendent sa réactivation.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Affiche un prochain message suggéré dans la zone de saisie vide après un tour Claude ou Codex. Tab l’utilise. Chaque suggestion est une requête en cache supplémentaire sur votre forfait. Nécessite Codex 0.165+. Les fils Claude se mettent à jour au redémarrage.", "d4b2a2ec812aafb0": "Suggérer le prochain prompt", "298c7150a7621c80": "Hôtes d’appareils Simlock", @@ -11814,6 +11844,7 @@ "d443390c4d2dcfd4": "accessibilité a11y lecteur d’écran nvda jaws voiceover orca narrateur titre de fenêtre titre d’onglet alt tab barre des tâches statut du fil ordre en cours approbation", "6826fa9579c22035": "bêta partager invité invitation lien coéquipier regarder t3 connect tunnel", "f10c06cba0cdf7fe": "bêta associer une autre machine vps pair agents y travaillent déléguer", + "bc0b409d89ce086e": "bêta workflow exécutions durables automatisation étapes planification webhook dossier", "4a21cf825a2045b0": "bêta tab autocomplétion prédire prochain message claude codex texte fantôme", "fea2dc36585c4a20": "Hôtes d’appareils Simlock (alpha)", "9d834d178130180e": "bêta alpha simlock callstack simulateur émulateur ios android pool bail passerelle", @@ -12370,6 +12401,262 @@ "2cddd6095abc734a": "7 jours", "53493056306708cf": "30 jours", "c719359d18d37ad3": "90 jours", + "0bd950151ddc6407": "Quitter sans enregistrer ? Vos modifications de ce fichier seront perdues.", + "c0ba3f6756b09f30": "Modifications non enregistrées", + "6914e22d357f0ad6": "Enregistré et en service", + "aff389354a031d6f": "Le fichier sur le disque ne se charge pas. La dernière version valide continue de s’exécuter.", + "858effde748ab563": "Enregistré, mais il ne s’exécute pas encore.", + "ddb37138df660942": "Non enregistré. Rien n’a changé sur le serveur.", + "6ef4db489e40e39e": "Impossible d’enregistrer", + "c89624a2e9af1793": "{name} n’est pas connecté", + "b5a352a43adb4c17": "Ses workflows réapparaissent quand il se reconnecte. Choisis un autre environnement pour voir ses exécutions.", + "3dcedb736d20aae5": "Impossible de lire les fichiers de workflow", + "b09f4df8d76ae8ea": "Supprimer {file} ? Les workflows qu’il définit ne pourront plus être démarrés.", + "b4535f5a03689d27": "{name} n’est pas connecté. Ce que vous écrivez ici est conservé et pourra être enregistré dès son retour.", + "b54c78d85fd942ea": "Supprimé, mais ce qui s’exécute n’a pas encore suivi.", + "407c228d7da0b7df": "Non supprimé. Rien n’a changé sur le serveur.", + "1a6aa10f3cc14fff": "Ces fichiers ne sont pas cohérents entre eux. Ce qui s’exécutait avant continue de s’exécuter.", + "259312516a1dbe6f": "Nom du fichier", + "2f48ab2aa0586853": "Ne définit aucun workflow", + "ba5adfa37b55b8c5": [ + "Ligne ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " :" + ], + "d94eb9ab3201b641": "Supprimer", + "84c900d1ae72adc6": "Enregistrer", + "5912d817be03247a": "Le fichier a changé sur le disque pendant votre modification. L’enregistrement remplace ce changement.", + "0b1e6f5608826387": "Charger le fichier et abandonner mes modifications", + "f47b4c06aeb77c1c": "Chargement des fichiers de workflow…", + "4353bfd401d58f87": [ + "Chaque fichier de", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "définit des workflows. Toute modification est prise en compte sans redémarrage." + ], + "0c165251a06f10f1": "Nouveau fichier", + "8e97cf734b4463e7": "Créer", + "2ec0d5108fd6cebe": "Aucun workflow pour l’instant. Créez le premier fichier ici ou demandez à un agent d’en écrire un dans ce dossier.", + "5601350626e8cfe9": "Ne se charge pas", + "21d778a1b9a0c234": "Ouvert à côté de l’exécution", + "62dc4d3a19ff7ca0": "Fermer l’onglet", + "1e25265f2758fce3": "Ouvrir comme fil complet", + "672a3dae06b39402": "Ouvrir sur sa propre page", + "7755500a4cde5066": "Fermer le panneau", + "b8dcbc93a2ca1861": "Cette exécution ne le mentionne plus.", + "115c69de3202f664": "Ouvrir", + "644eafa9048b62df": "{count, plural, =1 {1er essai} =2 {2e essai} =3 {3e essai} other {{count}e essai}}", + "e39f89c909df4db0": "Impossible de reprendre l’exécution", + "865f034346b82f47": "Annuler {title} ? Ses agents s’arrêtent et l’exécution ne pourra pas être reprise.", + "6bc75632fd9c9136": "Impossible d’annuler l’exécution", + "64e50329dcfdd5b0": "Terminée", + "350162e7cc1ebea4": "Arrêtée", + "0875cf506f4c6810": "Ignorée", + "3cc43f1dbf3f8e0c": "Annulée", + "ded70e75de6404ba": "Retour à la liste des exécutions", + "2f4ed7dbd22be30d": "Annuler l’exécution", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "a duré {duration}", + "aff78e1774818ff4": "{duration} jusqu’ici", + "38eddd466439afc9": "Ce que l’exécution a touché", + "156ec271d49ddd70": "Ce qui s’est passé", + "34f59bbbead0b97f": "{names} et {count} de plus", + "ac1556f6ce89a5ea": "{count} en parallèle", + "e197c4963bacc746": "{count} en cours", + "f5319ed9e18c0df1": "Vous pose une question", + "882a25e9084ae1b2": "En pause", + "9a03d8a9afc60387": "Étapes jusqu’ici", + "2f2ae791afe01674": "attend ton approbation", + "24f8060c4ccdf928": "démarre", + "30a5be40eb956663": "en cours", + "dd7a1e58c2553933": "réveil dans {duration}", + "95cc952724dd7310": "réveil imminent", + "3cc34921c0128593": "en cours", + "e777db2880f53a46": "personne n’a répondu", + "dc90739d391a5e67": "Vous avez répondu {choice}", + "389f2563b5b763fd": "Étapes rapides", + "a41c8d758121ad81": "en veille", + "9db248b770096984": "a attendu", + "c76124517af28686": "en cours depuis {duration}", + "89102905bf09b0e8": "Suivre en direct", + "bdf338cdff4118f0": "Transcription", + "811e7e992f9ff820": "ne peut pas continuer tant que sa version du workflow n’est pas de nouveau enregistrée", + "4d4cdf035e98dd57": "attend que vous la repreniez", + "eb5b21dd224a5941": "réessaie d’elle-même dans {duration}", + "6ab3dfa749fde477": "va réessayer d’elle-même", + "44b6463aa70aa14c": "Raison de la pause", + "cf25e7169ab0eb7a": "En pause à {step}", + "56c48c1f220f2754": "Impossible de répondre à la question", + "a3c43735e1a81498": "Raison pour {title}", + "bfad234f016cfa3f": "Pourquoi, en une phrase. Elle accompagne la réponse que vous choisissez.", + "004c41aff9c97873": "Exécutions", + "4dc0c244a2419f6c": [ + "Fait partie de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "démarrée", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "sa version n’est plus enregistrée", + "f92d9132f7b85d1a": "Chargement des étapes…", + "6ebc59f64c761a49": "Rien pour l’instant.", + "a759dccd157d7dae": [ + "Vous avez répondu", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Vous avez répondu", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " : ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Ouvrir l’exécution", + "c8eb9be36d4d51ad": [ + "Fil sur ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Reprendre", + "8cebd63fc4c967d5": "Seule l’étape en échec est relancée ; ce qui s’est terminé avant est conservé.", + "bc1e0a2a0f1e9552": "Vous attendent", + "a812f51e970740f1": [ + "question posée", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· l’exécution vous attend" + ], + "02dfe6c63fd0b8a1": "Ajouter une raison", + "19abd94828a3bdbc": "Demander d’abord à l’agent", + "a18721fa8f328361": "Vous attendent", + "bbf24e7920c1e86b": "En cours", + "8d6e18d2ad832db6": "Toutes", + "f25af5332ffc3734": "Rien n’attend votre réponse.", + "c3f0119b8d6231f8": "Rien n’est en cours.", + "33028dfc1229eaa6": "Aucune exécution pour l’instant.", + "5459bf696a187c26": "Impossible de charger les exécutions de workflow", + "d57c35d43b0f163a": "Cette exécution n’est pas ici", + "b9aae2f7cdb1a379": "Aucune exécution de workflow pour l’instant", + "8f15f66e545af7c0": "Quelles exécutions", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Les {count} workflows", + "46d614fa7b4bf1e5": "Exécutions de workflow", + "1c635faa2fb45b8b": "Pas encore exécuté.", + "156ff7b625287a1e": "Masquer les éléments ignorés", + "69b985b97ab45e6b": "Afficher {count} ignorés", + "2400254d362de84d": "Chargement des exécutions de workflow…", + "145e1f7503ba3b2c": [ + "Cet environnement n’a aucune exécution avec ce lien.", + " ", + { + "t": "button", + "i": 1, + "c": "Retour aux exécutions" + } + ], + "783e616cb0476c17": [ + "Un workflow réunit agents, code, planifications et questions qui vous sont posées en une seule exécution qui survit aux redémarrages. Écrivez-en un dans", + " ", + { + "t": "button", + "i": 1, + "c": "Définitions" + }, + ", ou demandez-le à un agent.", + " ", + { + "t": "a", + "i": 2, + "c": "Lire le guide" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Un fichier de workflow présente un problème." + }, + " ", + "La dernière version valide continue de s’exécuter." + ], + "ed8ce6ebc73dc12d": "Ouvrir le fichier", + "5d8d278ff828102d": "Tous les workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transcription", + "c512071143a5ba32": "Ce fil n’existe plus.", + "ed169d23683fb6ac": "Chargement du fil…", + "290e0ab40b87dc17": "Fil d’Ariane des workflows", + "683dd9831e54edc0": "Environnement", + "34ad53646f06ed80": "Les workflows sont désactivés", + "8f6589c9e0ac5d4e": "Aucun environnement connecté", + "744127f8dfad7d22": "Connectez un environnement pour voir ses exécutions de workflow.", + "036182ec7e2ee4d4": "À côté de l’exécution", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Définitions", + "f0a212aadfe1257b": "Chargement de l’éditeur…", + "20f194e003885e95": [ + "Activez-les pour ce serveur dans", + " ", + { + "t": "Link", + "i": 1, + "c": "Paramètres → Labs" + }, + "." + ], "8367779e149f723b": "La requête vers l’environnement principal a échoué pendant {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Jeton d’appairage non valide. Vérifiez le jeton et réessayez.", "0e4b49c8203aae81": "Délai dépassé en attendant la session authentifiée après l’amorçage.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 2b44f05d584e1..e665b9445f6f9 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "公開 URL を使うには、この環境を T3 Connect にリンクしてください。", "6b80f5b38a8f9950": "このアドレスを呼び出せるのはこのコンピューターだけです。公開 URL を使うには T3 Connect をリンクしてください。", "c5a7b1d3891dd0b8": "この環境のアドレスに到達できる場所ならどこでも動作します (Tailscale や独自のプロキシ経由など)。公開 URL を使うには T3 Connect をリンクしてください。", + "3669395daf36fd33": "このサーバーにはもう登録されていません", + "fe513cf316e796e3": "他のワークフローの一部として実行", + "ccf00b97925efab3": "手動で開始", + "421e585eb092b07b": "{triggers} で開始", + "7bd7c58592671384": "要対応", + "834ca879c14c167b": "作業中", + "582d6df7dfab86fb": "一時停止中", + "ea6583ce92507ee3": "スリープ中", + "7ea8cb8af281ce93": "待機中", + "1347868f2523140e": "完了", + "57d76c4614054271": "停止", + "5c7344bd51d0b966": "スキップ", + "b2074e9bd23049a6": "キャンセル済み", + "5bb7401807ee2fb5": "質問: {question} ほか {more} 件", + "9e4286183d5f9e34": "質問: {question}", + "474c18d001bd6717": "ステップが失敗しました", + "d3890f4eb1508781": "自身のステップを実行中", + "3e7ced10c9482af0": "{step} が作業中", + "237e1bcb1cf1bdec": "{step} でスリープ中", + "3f7b17ac5a20c8d2": "{run} を実行", + "0306f5f324b8aaa5": "{count} 件の実行が進行中", + "e8fd779b84a202a2": "待機中", + "b6d55657e1a027b8": "{step} を待機中", + "e942562a42aede34": "完了", + "26b2b9727fe11289": "早期終了", "1bb995dcec481554": "{host} でこのデバイスを承認してください。コード {verificationCode} が表示されています。", "8696a33219944832": "WebSocket の認可証明を作成できませんでした。", "5678f133a8631f7d": "クラウドのサインインが変更されました。環境を認可するには、もう一度サインインしてください。", @@ -1743,6 +1768,8 @@ "2e995206e087c3fc": "接続または保留中の入力が解決してから、返信してください。", "604ec3067171a0d7": "会話", "d6182a057ea12624": "親スレッド", + "f2d8537c33cc55a5": "ワークフロー実行のステップ", + "ba8337dca3232880": "実行を開く", "30fa4a764d11ae42": "{name} をダウンロードできませんでした", "4952f87dc98191a7": "添付ファイルを利用できません。", "2fd6d178493fb407": "現在のターンを中断できませんでした。", @@ -1828,6 +1855,7 @@ "04fd71efaa2c3b92": "プルリクエストを開く", "57e875b79b98ab82": "Issue を開く", "f1db0a234c777a1d": "他のアプリで T3 Code を使用 (MCP)", + "6050f22f63e2bcb5": "ワークフローを開く", "a0cc19e60dd99851": "使用量を開く", "46694969044eee98": "次のワークスペース領域にフォーカス", "0a1011328ba42eef": "前のワークスペース領域にフォーカス", @@ -8825,6 +8853,8 @@ "9ae293971d93c819": "スレッドをゲストと共有します。ゲストはブラウザーでライブで閲覧し、あなたが承認したメッセージを送信できます。ゲストリンクを使うには T3 Connect にサインインしてください。", "0aa5406ac4d7f7c7": "ゲストリンク", "f0e853acd2006d53": "リンクされた環境", + "ef10c2dff987f3ea": "このサーバーの T3 ホームにある workflows フォルダーのファイルから、複数ステップのワークフローを実行します。コマンドパレットから開けます。オフの間はそのフォルダーの内容は実行されず、実行はオンに戻るまで待機します。", + "2dadb2359422121c": "ワークフロー", "13e86eb5d8287a71": "Claude または Codex のターンの後、空の入力欄に次のメッセージの予測を表示します。Tab で使用します。毎回、プランでキャッシュされたリクエストが 1 つ追加されます。Codex 0.165 以降が必要です。Claude のスレッドは再起動時に更新されます。", "d4b2a2ec812aafb0": "次のプロンプトを提案", "298c7150a7621c80": "Simlock デバイスホスト", @@ -11765,6 +11795,7 @@ "d443390c4d2dcfd4": "アクセシビリティ a11y スクリーンリーダー NVDA JAWS VoiceOver Orca ナレーター ウィンドウタイトル タブタイトル Alt+Tab タスクバー スレッド ステータス 順序 作業中 承認 accessibility", "6826fa9579c22035": "ベータ 共有 ゲスト 招待 リンク チームメイト 閲覧 T3 Connect トンネル beta share guest", "f10c06cba0cdf7fe": "ベータ リンク 別のマシン VPS ピア エージェント そこで作業 委任 beta link machine", + "bc0b409d89ce086e": "ベータ ワークフロー 永続 実行 自動化 ステップ スケジュール webhook フォルダー beta workflow", "4a21cf825a2045b0": "ベータ Tab 補完 次のメッセージを予測 Claude Codex ゴーストテキスト autocomplete", "fea2dc36585c4a20": "Simlock デバイスホスト (アルファ版)", "9d834d178130180e": "ベータ アルファ simlock callstack シミュレーター エミュレーター iOS Android プール リース ゲートウェイ simulator", @@ -12321,6 +12352,254 @@ "2cddd6095abc734a": "7 日間", "53493056306708cf": "30 日間", "c719359d18d37ad3": "90 日間", + "0bd950151ddc6407": "保存せずに移動しますか?このファイルへの変更は失われます。", + "c0ba3f6756b09f30": "未保存の変更", + "6914e22d357f0ad6": "保存済み、実行中", + "aff389354a031d6f": "ディスク上のファイルを読み込めません。正常に読み込めた最後のバージョンが引き続き実行されます。", + "858effde748ab563": "保存しましたが、まだ実行されていません。", + "ddb37138df660942": "保存されませんでした。サーバー上では何も変更されていません。", + "6ef4db489e40e39e": "保存できませんでした", + "c89624a2e9af1793": "{name} は接続されていません", + "b5a352a43adb4c17": "再接続するとワークフローがまた表示されます。別の環境を選ぶと、その実行を確認できます。", + "3dcedb736d20aae5": "ワークフローファイルを読み取れませんでした", + "b09f4df8d76ae8ea": "{file} を削除しますか?このファイルで定義されたワークフローは開始できなくなります。", + "b4535f5a03689d27": "{name} は接続されていません。ここに書いた内容は残り、再接続後に保存できます。", + "b54c78d85fd942ea": "削除しましたが、実行中の内容はまだ反映されていません。", + "407c228d7da0b7df": "削除されませんでした。サーバー上では何も変更されていません。", + "1a6aa10f3cc14fff": "これらのファイルは互いに整合しません。以前のものが引き続き実行されます。", + "259312516a1dbe6f": "ファイル名", + "2f48ab2aa0586853": "ワークフローの定義なし", + "ba5adfa37b55b8c5": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 行目:" + ], + "d94eb9ab3201b641": "削除", + "84c900d1ae72adc6": "保存", + "5912d817be03247a": "編集中にディスク上のファイルが変更されました。保存するとその変更が上書きされます。", + "0b1e6f5608826387": "ファイルを読み込んで自分の変更を破棄", + "f47b4c06aeb77c1c": "ワークフローファイルを読み込んでいます…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "内のすべてのファイルがワークフローを定義します。変更は再起動なしで反映されます。" + ], + "0c165251a06f10f1": "新しいファイル", + "8e97cf734b4463e7": "作成", + "2ec0d5108fd6cebe": "ワークフローはまだありません。ここで最初のファイルを作成するか、エージェントにそのフォルダーへ作成するよう依頼してください。", + "5601350626e8cfe9": "読み込めません", + "21d778a1b9a0c234": "実行の横で開いているもの", + "62dc4d3a19ff7ca0": "タブを閉じる", + "1e25265f2758fce3": "通常のスレッドとして開く", + "672a3dae06b39402": "専用のページで開く", + "7755500a4cde5066": "ペインを閉じる", + "b8dcbc93a2ca1861": "この実行には含まれなくなりました。", + "115c69de3202f664": "開く", + "644eafa9048b62df": "{count, plural, =1 {1 回目の試行} =2 {2 回目の試行} =3 {3 回目の試行} other {{count} 回目の試行}}", + "e39f89c909df4db0": "実行を再開できませんでした", + "865f034346b82f47": "{title} をキャンセルしますか?エージェントは停止し、この実行は再開できなくなります。", + "6bc75632fd9c9136": "実行をキャンセルできませんでした", + "64e50329dcfdd5b0": "完了", + "350162e7cc1ebea4": "停止", + "0875cf506f4c6810": "スキップ", + "3cc43f1dbf3f8e0c": "キャンセル済み", + "ded70e75de6404ba": "実行一覧に戻る", + "2f4ed7dbd22be30d": "実行をキャンセル", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "所要時間 {duration}", + "aff78e1774818ff4": "{duration} 経過", + "38eddd466439afc9": "この実行が扱ったもの", + "156ec271d49ddd70": "経過", + "34f59bbbead0b97f": "{names} ほか {count} 件", + "ac1556f6ce89a5ea": "{count} 件を並行", + "e197c4963bacc746": "{count} 件実行中", + "f5319ed9e18c0df1": "あなたへの質問", + "882a25e9084ae1b2": "一時停止中", + "9a03d8a9afc60387": "これまでのステップ", + "2f2ae791afe01674": "承認待ち", + "24f8060c4ccdf928": "開始中", + "30a5be40eb956663": "作業中", + "dd7a1e58c2553933": "{duration} 後にスリープ解除", + "95cc952724dd7310": "まもなくスリープ解除", + "3cc34921c0128593": "実行中", + "e777db2880f53a46": "回答なし", + "dc90739d391a5e67": "あなたの回答: {choice}", + "389f2563b5b763fd": "短いステップ", + "a41c8d758121ad81": "スリープ", + "9db248b770096984": "待機", + "c76124517af28686": "{duration} 実行中", + "89102905bf09b0e8": "ライブで見る", + "bdf338cdff4118f0": "トランスクリプト", + "811e7e992f9ff820": "ワークフローのバージョンが再登録されるまで続行できません", + "4d4cdf035e98dd57": "手動での再開待ち", + "eb5b21dd224a5941": "{duration} 後に自動で再試行", + "6ab3dfa749fde477": "まもなく自動で再試行", + "44b6463aa70aa14c": "一時停止の理由", + "cf25e7169ab0eb7a": "{step} で一時停止中", + "56c48c1f220f2754": "質問に回答できませんでした", + "a3c43735e1a81498": "{title} の理由", + "bfad234f016cfa3f": "理由を一文で。どの回答を選んでも一緒に送信されます。", + "004c41aff9c97873": "実行", + "4dc0c244a2419f6c": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " の一部" + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "に開始" + ], + "8bffb377e2a6a7de": "そのバージョンはもう登録されていません", + "f92d9132f7b85d1a": "ステップを読み込んでいます…", + "6ebc59f64c761a49": "まだ何もありません。", + "a759dccd157d7dae": [ + "あなたの回答: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "あなたの回答: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "実行を開く", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 上のスレッド" + ], + "3d9761e81798fcd8": "再開", + "8cebd63fc4c967d5": "失敗したステップだけが再実行されます。それより前に完了したものは保持されます。", + "bc1e0a2a0f1e9552": "要対応", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "に質問", + " ", + "· 実行はあなたの回答を待っています" + ], + "02dfe6c63fd0b8a1": "理由を追加", + "19abd94828a3bdbc": "先にエージェントに質問", + "a18721fa8f328361": "要対応", + "bbf24e7920c1e86b": "実行中", + "8d6e18d2ad832db6": "すべて", + "f25af5332ffc3734": "対応待ちのものはありません。", + "c3f0119b8d6231f8": "実行中のものはありません。", + "33028dfc1229eaa6": "実行はまだありません。", + "5459bf696a187c26": "ワークフローの実行を読み込めませんでした", + "d57c35d43b0f163a": "この実行はここにありません", + "b9aae2f7cdb1a379": "ワークフローの実行はまだありません", + "8f15f66e545af7c0": "表示する実行", + "b6409289e0c9a4dd": "ワークフロー", + "035cb02ca1ae4952": "すべてのワークフロー ({count} 件)", + "46d614fa7b4bf1e5": "ワークフローの実行", + "1c635faa2fb45b8b": "まだ実行されていません。", + "156ff7b625287a1e": "スキップ済みを非表示", + "69b985b97ab45e6b": "スキップ済み {count} 件を表示", + "2400254d362de84d": "ワークフローの実行を読み込んでいます…", + "145e1f7503ba3b2c": [ + "この環境には、そのリンクの実行はありません。", + " ", + { + "t": "button", + "i": 1, + "c": "実行一覧に戻る" + } + ], + "783e616cb0476c17": [ + "ワークフローは、エージェント、コード、スケジュール、あなたへの質問を、再起動後も継続する 1 つの実行にまとめます。", + { + "t": "button", + "i": 1, + "c": "定義" + }, + " ", + "で作成するか、エージェントに依頼してください。", + " ", + { + "t": "a", + "i": 2, + "c": "ガイドを読む" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "ワークフローファイルに問題があります。" + }, + " ", + "正常に読み込めた最後のバージョンが引き続き実行されます。" + ], + "ed8ce6ebc73dc12d": "ファイルを開く", + "5d8d278ff828102d": "すべてのワークフロー", + "39459da07479f482": "エージェント", + "7741243632056b81": "{step} · トランスクリプト", + "c512071143a5ba32": "このスレッドはもう存在しません。", + "ed169d23683fb6ac": "スレッドを読み込んでいます…", + "290e0ab40b87dc17": "ワークフローのパンくずリスト", + "683dd9831e54edc0": "環境", + "34ad53646f06ed80": "ワークフローはオフです", + "8f6589c9e0ac5d4e": "接続されている環境がありません", + "744127f8dfad7d22": "環境を接続すると、そのワークフローの実行が表示されます。", + "036182ec7e2ee4d4": "実行の横", + "2d6107cb78382d08": "ワークフロー", + "16f7df687349b399": "定義", + "f0a212aadfe1257b": "エディターを読み込んでいます…", + "20f194e003885e95": [ + "このサーバーの", + " ", + { + "t": "Link", + "i": 1, + "c": "設定 → Labs" + }, + " でオンにしてください。" + ], "8367779e149f723b": "プライマリ環境へのリクエストが {operation} 中に失敗しました (HTTP {status})。", "c5cd027743a2b5a6": "ペアリングトークンが無効です。トークンを確認して、もう一度お試しください。", "0e4b49c8203aae81": "ブートストラップ後、認証済みセッションの待機がタイムアウトしました。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 48dc094c371ad..90614ef54230d 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "공개 URL을 사용하려면 이 환경을 T3 Connect에 연결하세요.", "6b80f5b38a8f9950": "이 컴퓨터에서만 이 주소를 호출할 수 있습니다. 공개 URL을 사용하려면 T3 Connect를 연결하세요.", "c5a7b1d3891dd0b8": "Tailscale이나 자체 프록시처럼 이 환경의 주소에 접근할 수 있는 곳이면 어디서든 작동합니다. 공개 URL을 사용하려면 T3 Connect를 연결하세요.", + "3669395daf36fd33": "이 서버에 더 이상 등록되어 있지 않음", + "fe513cf316e796e3": "다른 워크플로의 일부로 실행", + "ccf00b97925efab3": "수동으로 시작", + "421e585eb092b07b": "{triggers}에서 시작", + "7bd7c58592671384": "확인 필요", + "834ca879c14c167b": "작업 중", + "582d6df7dfab86fb": "일시 중지됨", + "ea6583ce92507ee3": "슬립 중", + "7ea8cb8af281ce93": "대기 중", + "1347868f2523140e": "완료", + "57d76c4614054271": "중지됨", + "5c7344bd51d0b966": "건너뜀", + "b2074e9bd23049a6": "취소됨", + "5bb7401807ee2fb5": "질문: {question} 외 {more}개", + "9e4286183d5f9e34": "질문: {question}", + "474c18d001bd6717": "단계 실패", + "d3890f4eb1508781": "자체 단계 실행 중", + "3e7ced10c9482af0": "{step} 작업 중", + "237e1bcb1cf1bdec": "{step}에서 슬립 중", + "3f7b17ac5a20c8d2": "{run} 실행", + "0306f5f324b8aaa5": "실행 {count}개 진행 중", + "e8fd779b84a202a2": "대기 중", + "b6d55657e1a027b8": "{step} 대기 중", + "e942562a42aede34": "완료", + "26b2b9727fe11289": "조기 종료", "1bb995dcec481554": "{host}에서 이 기기를 승인하세요. 코드 {verificationCode}이(가) 표시됩니다.", "8696a33219944832": "WebSocket 인증 증명을 만들 수 없습니다.", "5678f133a8631f7d": "클라우드 로그인이 변경되었습니다. 환경을 인증하려면 다시 로그인하세요.", @@ -1743,6 +1768,8 @@ "2e995206e087c3fc": "연결 또는 대기 중인 입력이 해결된 후 답장해 보세요.", "604ec3067171a0d7": "대화", "d6182a057ea12624": "상위 스레드", + "f2d8537c33cc55a5": "워크플로 실행의 단계", + "ba8337dca3232880": "실행 열기", "30fa4a764d11ae42": "{name}을(를) 다운로드할 수 없습니다", "4952f87dc98191a7": "첨부 파일을 사용할 수 없습니다.", "2fd6d178493fb407": "현재 턴을 중단하지 못했습니다.", @@ -1828,6 +1855,7 @@ "04fd71efaa2c3b92": "풀 리퀘스트 열기", "57e875b79b98ab82": "이슈 열기", "f1db0a234c777a1d": "다른 앱에서 T3 Code 사용(MCP)", + "6050f22f63e2bcb5": "워크플로 열기", "a0cc19e60dd99851": "사용량 열기", "46694969044eee98": "다음 작업 영역으로 포커스 이동", "0a1011328ba42eef": "이전 작업 영역으로 포커스 이동", @@ -8828,6 +8856,8 @@ "9ae293971d93c819": "브라우저에서 실시간으로 지켜보고 승인한 메시지를 보낼 수 있는 게스트와 스레드를 공유합니다. 게스트 링크를 사용하려면 T3 Connect에 로그인하세요.", "0aa5406ac4d7f7c7": "게스트 링크", "f0e853acd2006d53": "연결된 환경", + "ef10c2dff987f3ea": "이 서버 T3 홈의 workflows 폴더에 있는 파일로 여러 단계의 워크플로를 실행합니다. 명령 팔레트에서 엽니다. 꺼져 있는 동안에는 그 폴더의 어떤 것도 실행되지 않으며, 실행은 다시 켤 때까지 기다립니다.", + "2dadb2359422121c": "워크플로", "13e86eb5d8287a71": "Claude 또는 Codex 턴이 끝난 뒤 빈 입력창에 예상되는 다음 메시지를 표시합니다. Tab을 누르면 사용합니다. 제안마다 요금제에서 캐시된 요청이 하나 더 발생합니다. Codex 0.165 이상이 필요합니다. Claude 스레드는 다시 시작하면 업데이트됩니다.", "d4b2a2ec812aafb0": "다음 프롬프트 제안", "298c7150a7621c80": "Simlock 기기 호스트", @@ -11761,6 +11791,7 @@ "d443390c4d2dcfd4": "접근성 a11y 화면 낭독기 nvda jaws voiceover orca 내레이터 창 제목 탭 제목 alt tab 작업 표시줄 스레드 상태 순서 작업 중 승인", "6826fa9579c22035": "베타 공유 게스트 초대 링크 팀원 지켜보기 T3 Connect 터널", "f10c06cba0cdf7fe": "베타 다른 머신 연결 vps 피어 에이전트 원격 작업 위임", + "bc0b409d89ce086e": "베타 워크플로 workflow 지속 실행 자동화 단계 일정 webhook 폴더", "4a21cf825a2045b0": "베타 탭 자동 완성 다음 메시지 예측 Claude Codex 고스트 텍스트", "fea2dc36585c4a20": "Simlock 기기 호스트(알파)", "9d834d178130180e": "베타 알파 simlock callstack 시뮬레이터 에뮬레이터 iOS Android 풀 임대 게이트웨이", @@ -12317,6 +12348,255 @@ "2cddd6095abc734a": "7일", "53493056306708cf": "30일", "c719359d18d37ad3": "90일", + "0bd950151ddc6407": "저장하지 않고 나갈까요? 이 파일의 변경 사항이 사라집니다.", + "c0ba3f6756b09f30": "저장되지 않은 변경 사항", + "6914e22d357f0ad6": "저장되어 실행 중", + "aff389354a031d6f": "디스크의 파일을 불러올 수 없습니다. 마지막으로 불러온 버전이 계속 실행됩니다.", + "858effde748ab563": "저장했지만 아직 실행되지 않습니다.", + "ddb37138df660942": "저장되지 않았습니다. 서버에서 변경된 것은 없습니다.", + "6ef4db489e40e39e": "저장할 수 없습니다", + "c89624a2e9af1793": "{name}이(가) 연결되어 있지 않습니다", + "b5a352a43adb4c17": "다시 연결되면 워크플로가 다시 표시됩니다. 다른 환경을 선택하면 그 환경의 실행을 볼 수 있습니다.", + "3dcedb736d20aae5": "워크플로 파일을 읽을 수 없습니다", + "b09f4df8d76ae8ea": "{file}을(를) 삭제할까요? 이 파일에 정의된 워크플로는 더 이상 시작할 수 없습니다.", + "b4535f5a03689d27": "{name}이(가) 연결되어 있지 않습니다. 여기에 작성한 내용은 유지되며, 다시 연결되면 저장할 수 있습니다.", + "b54c78d85fd942ea": "삭제했지만 실행 중인 내용에 아직 반영되지 않았습니다.", + "407c228d7da0b7df": "삭제되지 않았습니다. 서버에서 변경된 것은 없습니다.", + "1a6aa10f3cc14fff": "이 파일들은 서로 맞지 않습니다. 이전에 실행되던 것이 계속 실행됩니다.", + "259312516a1dbe6f": "파일 이름", + "2f48ab2aa0586853": "정의된 워크플로 없음", + "ba5adfa37b55b8c5": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "번째 줄:" + ], + "d94eb9ab3201b641": "삭제", + "84c900d1ae72adc6": "저장", + "5912d817be03247a": "편집하는 동안 디스크의 파일이 변경되었습니다. 저장하면 해당 변경 사항을 덮어씁니다.", + "0b1e6f5608826387": "파일을 불러오고 내 변경 사항 버리기", + "f47b4c06aeb77c1c": "워크플로 파일을 불러오는 중…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "의 모든 파일이 워크플로를 정의합니다. 파일을 변경하면 다시 시작하지 않아도 반영됩니다." + ], + "0c165251a06f10f1": "새 파일", + "8e97cf734b4463e7": "만들기", + "2ec0d5108fd6cebe": "아직 워크플로가 없습니다. 여기에서 첫 파일을 만들거나 에이전트에게 해당 폴더에 작성해 달라고 요청하세요.", + "5601350626e8cfe9": "불러올 수 없음", + "21d778a1b9a0c234": "실행 옆에 열린 항목", + "62dc4d3a19ff7ca0": "탭 닫기", + "1e25265f2758fce3": "전체 스레드로 열기", + "672a3dae06b39402": "전용 페이지에서 열기", + "7755500a4cde5066": "창 닫기", + "b8dcbc93a2ca1861": "이 실행에 더 이상 포함되지 않습니다.", + "115c69de3202f664": "열기", + "644eafa9048b62df": "{count, plural, =1 {1번째 시도} =2 {2번째 시도} =3 {3번째 시도} other {{count}번째 시도}}", + "e39f89c909df4db0": "실행을 재개할 수 없습니다", + "865f034346b82f47": "{title}을(를) 취소할까요? 에이전트가 중지되며 이 실행은 재개할 수 없습니다.", + "6bc75632fd9c9136": "실행을 취소할 수 없습니다", + "64e50329dcfdd5b0": "완료", + "350162e7cc1ebea4": "중지됨", + "0875cf506f4c6810": "건너뜀", + "3cc43f1dbf3f8e0c": "취소됨", + "ded70e75de6404ba": "실행 목록으로 돌아가기", + "2f4ed7dbd22be30d": "실행 취소", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "{duration} 소요", + "aff78e1774818ff4": "현재까지 {duration}", + "38eddd466439afc9": "이 실행이 다룬 항목", + "156ec271d49ddd70": "진행 내역", + "34f59bbbead0b97f": "{names} 외 {count}개", + "ac1556f6ce89a5ea": "{count}개 병렬", + "e197c4963bacc746": "{count}개 실행 중", + "f5319ed9e18c0df1": "사용자에게 질문", + "882a25e9084ae1b2": "일시 중지됨", + "9a03d8a9afc60387": "지금까지의 단계", + "2f2ae791afe01674": "승인을 기다리는 중", + "24f8060c4ccdf928": "시작하는 중", + "30a5be40eb956663": "작업 중", + "dd7a1e58c2553933": "{duration} 후 깨어남", + "95cc952724dd7310": "곧 깨어남", + "3cc34921c0128593": "실행 중", + "e777db2880f53a46": "응답 없음", + "dc90739d391a5e67": "내 답변: {choice}", + "389f2563b5b763fd": "빠른 단계", + "a41c8d758121ad81": "슬립", + "9db248b770096984": "대기", + "c76124517af28686": "{duration}째 실행 중", + "89102905bf09b0e8": "실시간 보기", + "bdf338cdff4118f0": "대화 기록", + "811e7e992f9ff820": "워크플로 버전이 다시 등록될 때까지 계속할 수 없음", + "4d4cdf035e98dd57": "사용자가 재개하기를 기다리는 중", + "eb5b21dd224a5941": "{duration} 후 자동으로 다시 시도", + "6ab3dfa749fde477": "곧 자동으로 다시 시도", + "44b6463aa70aa14c": "일시 중지된 이유", + "cf25e7169ab0eb7a": "{step}에서 일시 중지됨", + "56c48c1f220f2754": "질문에 답변할 수 없습니다", + "a3c43735e1a81498": "{title}의 이유", + "bfad234f016cfa3f": "이유를 한 문장으로 적어 주세요. 어떤 답변을 고르든 함께 전달됩니다.", + "004c41aff9c97873": "실행", + "4dc0c244a2419f6c": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "의 일부" + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "시작" + ], + "8bffb377e2a6a7de": "해당 버전이 더 이상 등록되어 있지 않음", + "f92d9132f7b85d1a": "단계를 불러오는 중…", + "6ebc59f64c761a49": "아직 아무것도 없습니다.", + "a759dccd157d7dae": [ + "내 답변: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "내 답변: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "실행 열기", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "의 스레드" + ], + "3d9761e81798fcd8": "재개", + "8cebd63fc4c967d5": "실패한 단계만 다시 실행되며, 그 전에 완료된 내용은 유지됩니다.", + "bc1e0a2a0f1e9552": "확인 필요", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "질문", + " ", + "· 실행이 답변을 기다리는 중" + ], + "02dfe6c63fd0b8a1": "이유 추가", + "19abd94828a3bdbc": "먼저 에이전트에게 묻기", + "a18721fa8f328361": "확인 필요", + "bbf24e7920c1e86b": "실행 중", + "8d6e18d2ad832db6": "전체", + "f25af5332ffc3734": "확인이 필요한 항목이 없습니다.", + "c3f0119b8d6231f8": "실행 중인 항목이 없습니다.", + "33028dfc1229eaa6": "아직 실행이 없습니다.", + "5459bf696a187c26": "워크플로 실행을 불러올 수 없습니다", + "d57c35d43b0f163a": "이 실행은 여기에 없습니다", + "b9aae2f7cdb1a379": "아직 워크플로 실행이 없습니다", + "8f15f66e545af7c0": "표시할 실행", + "b6409289e0c9a4dd": "워크플로", + "035cb02ca1ae4952": "워크플로 {count}개 전체", + "46d614fa7b4bf1e5": "워크플로 실행", + "1c635faa2fb45b8b": "아직 실행된 적이 없습니다.", + "156ff7b625287a1e": "건너뛴 항목 숨기기", + "69b985b97ab45e6b": "건너뛴 항목 {count}개 표시", + "2400254d362de84d": "워크플로 실행을 불러오는 중…", + "145e1f7503ba3b2c": [ + "이 환경에는 해당 링크의 실행이 없습니다.", + " ", + { + "t": "button", + "i": 1, + "c": "실행 목록으로 돌아가기" + } + ], + "783e616cb0476c17": [ + "워크플로는 에이전트, 코드, 일정, 사용자에게 묻는 질문을 다시 시작해도 유지되는 하나의 실행으로 묶습니다.", + " ", + { + "t": "button", + "i": 1, + "c": "정의" + }, + "에서 직접 작성하거나 에이전트에게 요청하세요.", + " ", + { + "t": "a", + "i": 2, + "c": "가이드 읽기" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "워크플로 파일에 문제가 있습니다." + }, + " ", + "마지막으로 불러온 버전이 계속 실행됩니다." + ], + "ed8ce6ebc73dc12d": "파일 열기", + "5d8d278ff828102d": "모든 워크플로", + "39459da07479f482": "에이전트", + "7741243632056b81": "{step} · 기록", + "c512071143a5ba32": "이 스레드는 더 이상 존재하지 않습니다.", + "ed169d23683fb6ac": "스레드를 불러오는 중…", + "290e0ab40b87dc17": "워크플로 탐색 경로", + "683dd9831e54edc0": "환경", + "34ad53646f06ed80": "워크플로가 꺼져 있습니다", + "8f6589c9e0ac5d4e": "연결된 환경 없음", + "744127f8dfad7d22": "환경을 연결하면 해당 환경의 워크플로 실행을 볼 수 있습니다.", + "036182ec7e2ee4d4": "실행 옆", + "2d6107cb78382d08": "워크플로", + "16f7df687349b399": "정의", + "f0a212aadfe1257b": "편집기를 불러오는 중…", + "20f194e003885e95": [ + "이 서버의", + " ", + { + "t": "Link", + "i": 1, + "c": "설정 → Labs" + }, + "에서 켜세요." + ], "8367779e149f723b": "{operation} 중 기본 환경 요청에 실패했습니다(HTTP {status}).", "c5cd027743a2b5a6": "잘못된 페어링 토큰입니다. 토큰을 확인하고 다시 시도하세요.", "0e4b49c8203aae81": "부트스트랩 후 인증된 세션을 기다리다 시간이 초과되었습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 9cc052192b4eb..e8d50d83a5f44 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Vincule este ambiente ao T3 Connect para ter uma URL pública.", "6b80f5b38a8f9950": "Só este computador pode acessar este endereço. Vincule o T3 Connect para ter uma URL pública.", "c5a7b1d3891dd0b8": "Funciona onde o endereço deste ambiente for acessível, por exemplo pelo Tailscale ou pelo seu próprio proxy. Vincule o T3 Connect para ter uma URL pública.", + "3669395daf36fd33": "Não está mais registrado neste servidor", + "fe513cf316e796e3": "Executa como parte de outros workflows", + "ccf00b97925efab3": "Iniciado manualmente", + "421e585eb092b07b": "Inicia com {triggers}", + "7bd7c58592671384": "Precisam de você", + "834ca879c14c167b": "Trabalhando", + "582d6df7dfab86fb": "Pausada", + "ea6583ce92507ee3": "Dormindo", + "7ea8cb8af281ce93": "Aguardando", + "1347868f2523140e": "Concluída", + "57d76c4614054271": "Parada", + "5c7344bd51d0b966": "Pulada", + "b2074e9bd23049a6": "Cancelada", + "5bb7401807ee2fb5": "Pergunta: {question} e mais {more}", + "9e4286183d5f9e34": "Pergunta: {question}", + "474c18d001bd6717": "Uma etapa falhou", + "d3890f4eb1508781": "Executando as próprias etapas", + "3e7ced10c9482af0": "{step} está trabalhando", + "237e1bcb1cf1bdec": "Dormindo em {step}", + "3f7b17ac5a20c8d2": "Executa {run}", + "0306f5f324b8aaa5": "{count} execuções em andamento", + "e8fd779b84a202a2": "Aguardando", + "b6d55657e1a027b8": "Aguardando {step}", + "e942562a42aede34": "Concluída", + "26b2b9727fe11289": "Encerrada antes do fim", "1bb995dcec481554": "Aprove este dispositivo em {host}. Ele mostra o código {verificationCode}.", "8696a33219944832": "Não foi possível criar a prova de autorização do websocket.", "5678f133a8631f7d": "Seu login na nuvem mudou. Entre novamente para autorizar o ambiente.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Tente responder depois que a conexão ou a resposta pendente for resolvida.", "604ec3067171a0d7": "Conversa", "d6182a057ea12624": "Thread principal", + "f2d8537c33cc55a5": "Etapa da execução do workflow", + "ba8337dca3232880": "Abrir execução", "30fa4a764d11ae42": "Não foi possível baixar {name}", "4952f87dc98191a7": "O anexo não está disponível.", "2fd6d178493fb407": "Falha ao interromper o turno atual.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Abrir pull requests", "57e875b79b98ab82": "Abrir issues", "f1db0a234c777a1d": "Usar o T3 Code em outro app (MCP)", + "6050f22f63e2bcb5": "Abrir workflows", "a0cc19e60dd99851": "Abrir uso", "46694969044eee98": "Focar a próxima área do workspace", "0a1011328ba42eef": "Focar a área anterior do workspace", @@ -8867,6 +8895,8 @@ "9ae293971d93c819": "Compartilhe uma thread com um convidado que a acompanha ao vivo no navegador e envia mensagens que você aprova. Entre no T3 Connect para usar links de convidado.", "0aa5406ac4d7f7c7": "Links de convidado", "f0e853acd2006d53": "Ambientes vinculados", + "ef10c2dff987f3ea": "Execute workflows de várias etapas a partir de arquivos na pasta workflows da pasta T3 deste servidor. Abra-os pela paleta de comandos. Enquanto estiver desativado, nada dessa pasta é executado; as execuções aguardam até que seja ativado novamente.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Mostra uma próxima mensagem prevista no editor vazio após um turno do Claude ou do Codex. Tab a usa. Cada uma é uma requisição extra em cache no seu plano. Requer Codex 0.165+. As threads do Claude são atualizadas ao reiniciar.", "d4b2a2ec812aafb0": "Sugerir próximo prompt", "298c7150a7621c80": "Hosts de dispositivos Simlock", @@ -11814,6 +11844,7 @@ "d443390c4d2dcfd4": "acessibilidade a11y leitor de tela nvda jaws voiceover orca narrador título da janela título da aba alt tab barra de tarefas status da thread ordem trabalhando aprovação", "6826fa9579c22035": "beta compartilhar convidado convite link colega acompanhar t3 connect túnel", "f10c06cba0cdf7fe": "beta vincular outra máquina vps par agentes trabalham lá delegar", + "bc0b409d89ce086e": "beta workflow execuções duráveis automação etapas agendamento webhook pasta", "4a21cf825a2045b0": "beta tab autocompletar prever próxima mensagem claude codex texto fantasma", "fea2dc36585c4a20": "Hosts de dispositivos Simlock (alfa)", "9d834d178130180e": "beta alpha simlock callstack simulador emulador ios android pool lease gateway", @@ -12370,6 +12401,262 @@ "2cddd6095abc734a": "7 dias", "53493056306708cf": "30 dias", "c719359d18d37ad3": "90 dias", + "0bd950151ddc6407": "Sair sem salvar? Suas alterações neste arquivo serão perdidas.", + "c0ba3f6756b09f30": "Alterações não salvas", + "6914e22d357f0ad6": "Salvo e em execução", + "aff389354a031d6f": "O arquivo no disco não carrega. A última versão que carregou continua em execução.", + "858effde748ab563": "Salvo, mas ainda não está em execução.", + "ddb37138df660942": "Não salvo. Nada mudou no servidor.", + "6ef4db489e40e39e": "Não foi possível salvar", + "c89624a2e9af1793": "{name} não está conectado", + "b5a352a43adb4c17": "Os fluxos de trabalho dele voltam a aparecer quando ele se reconectar. Escolha outro ambiente para ver as execuções dele.", + "3dcedb736d20aae5": "Não foi possível ler os arquivos de workflow", + "b09f4df8d76ae8ea": "Excluir {file}? Os workflows que ele define não poderão mais ser iniciados.", + "b4535f5a03689d27": "{name} não está conectado. O que você escrever aqui fica guardado e pode ser salvo assim que ele voltar.", + "b54c78d85fd942ea": "Excluído, mas o que está em execução ainda não foi atualizado.", + "407c228d7da0b7df": "Não excluído. Nada mudou no servidor.", + "1a6aa10f3cc14fff": "Estes arquivos não são compatíveis entre si. O que rodava antes continua em execução.", + "259312516a1dbe6f": "Nome do arquivo", + "2f48ab2aa0586853": "Não define nenhum workflow", + "ba5adfa37b55b8c5": [ + "Linha ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Excluir", + "84c900d1ae72adc6": "Salvar", + "5912d817be03247a": "O arquivo mudou no disco enquanto você editava. Salvar substitui essa alteração.", + "0b1e6f5608826387": "Carregar o arquivo e descartar minhas alterações", + "f47b4c06aeb77c1c": "Carregando os arquivos de workflow…", + "4353bfd401d58f87": [ + "Cada arquivo em", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "define workflows. Uma alteração em qualquer um deles é aplicada sem reiniciar." + ], + "0c165251a06f10f1": "Novo arquivo", + "8e97cf734b4463e7": "Criar", + "2ec0d5108fd6cebe": "Nenhum workflow ainda. Crie o primeiro arquivo aqui ou peça a um agente para escrever um nessa pasta.", + "5601350626e8cfe9": "Não carrega", + "21d778a1b9a0c234": "Aberto ao lado da execução", + "62dc4d3a19ff7ca0": "Fechar aba", + "1e25265f2758fce3": "Abrir como thread completa", + "672a3dae06b39402": "Abrir na própria página", + "7755500a4cde5066": "Fechar o painel", + "b8dcbc93a2ca1861": "Esta execução não o lista mais.", + "115c69de3202f664": "Abrir", + "644eafa9048b62df": "{count, plural, =1 {1ª tentativa} =2 {2ª tentativa} =3 {3ª tentativa} other {{count}ª tentativa}}", + "e39f89c909df4db0": "Não foi possível retomar a execução", + "865f034346b82f47": "Cancelar {title}? Os agentes param e a execução não pode ser retomada.", + "6bc75632fd9c9136": "Não foi possível cancelar a execução", + "64e50329dcfdd5b0": "Concluída", + "350162e7cc1ebea4": "Parada", + "0875cf506f4c6810": "Pulada", + "3cc43f1dbf3f8e0c": "Cancelada", + "ded70e75de6404ba": "Voltar à lista de execuções", + "2f4ed7dbd22be30d": "Cancelar execução", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "levou {duration}", + "aff78e1774818ff4": "{duration} até agora", + "38eddd466439afc9": "O que a execução tocou", + "156ec271d49ddd70": "O que aconteceu", + "34f59bbbead0b97f": "{names} e mais {count}", + "ac1556f6ce89a5ea": "{count} em paralelo", + "e197c4963bacc746": "{count} em execução", + "f5319ed9e18c0df1": "Pergunta a você", + "882a25e9084ae1b2": "Pausada", + "9a03d8a9afc60387": "Etapas até agora", + "2f2ae791afe01674": "aguarda sua aprovação", + "24f8060c4ccdf928": "iniciando", + "30a5be40eb956663": "trabalhando", + "dd7a1e58c2553933": "acorda em {duration}", + "95cc952724dd7310": "prestes a acordar", + "3cc34921c0128593": "em execução", + "e777db2880f53a46": "ninguém respondeu", + "dc90739d391a5e67": "Você disse {choice}", + "389f2563b5b763fd": "Etapas rápidas", + "a41c8d758121ad81": "em espera", + "9db248b770096984": "aguardou", + "c76124517af28686": "em execução há {duration}", + "89102905bf09b0e8": "Assistir ao vivo", + "bdf338cdff4118f0": "Transcrição", + "811e7e992f9ff820": "não pode continuar até que a versão do workflow seja registrada novamente", + "4d4cdf035e98dd57": "aguarda você retomá-la", + "eb5b21dd224a5941": "tenta de novo sozinha em {duration}", + "6ab3dfa749fde477": "prestes a tentar de novo sozinha", + "44b6463aa70aa14c": "Por que pausou", + "cf25e7169ab0eb7a": "Pausada em {step}", + "56c48c1f220f2754": "Não foi possível responder à pergunta", + "a3c43735e1a81498": "Motivo para {title}", + "bfad234f016cfa3f": "O motivo, em uma frase. Ele acompanha a resposta que você escolher.", + "004c41aff9c97873": "Execuções", + "4dc0c244a2419f6c": [ + "Parte de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "iniciada", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "sua versão não está mais registrada", + "f92d9132f7b85d1a": "Carregando etapas…", + "6ebc59f64c761a49": "Nada ainda.", + "a759dccd157d7dae": [ + "Você disse", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Você disse", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Abrir execução", + "c8eb9be36d4d51ad": [ + "Thread em ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Retomar", + "8cebd63fc4c967d5": "Só a etapa que falhou é executada de novo; o que terminou antes dela é mantido.", + "bc1e0a2a0f1e9552": "Precisam de você", + "a812f51e970740f1": [ + "perguntou", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· a execução aguarda você" + ], + "02dfe6c63fd0b8a1": "Adicionar um motivo", + "19abd94828a3bdbc": "Perguntar ao agente primeiro", + "a18721fa8f328361": "Precisam de você", + "bbf24e7920c1e86b": "Em execução", + "8d6e18d2ad832db6": "Todas", + "f25af5332ffc3734": "Nada aguarda você.", + "c3f0119b8d6231f8": "Nada em execução.", + "33028dfc1229eaa6": "Nenhuma execução ainda.", + "5459bf696a187c26": "Não foi possível carregar as execuções de workflow", + "d57c35d43b0f163a": "Esta execução não está aqui", + "b9aae2f7cdb1a379": "Nenhuma execução de workflow ainda", + "8f15f66e545af7c0": "Quais execuções", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Todos os workflows ({count})", + "46d614fa7b4bf1e5": "Execuções de workflow", + "1c635faa2fb45b8b": "Ainda não foi executado.", + "156ff7b625287a1e": "Ocultar puladas", + "69b985b97ab45e6b": "Mostrar puladas ({count})", + "2400254d362de84d": "Carregando execuções de workflow…", + "145e1f7503ba3b2c": [ + "Este ambiente não tem nenhuma execução com esse link.", + " ", + { + "t": "button", + "i": 1, + "c": "Voltar às execuções" + } + ], + "783e616cb0476c17": [ + "Um workflow reúne agentes, código, agendamentos e perguntas para você em uma única execução que sobrevive a reinicializações. Escreva um em", + " ", + { + "t": "button", + "i": 1, + "c": "Definições" + }, + ", ou peça a um agente.", + " ", + { + "t": "a", + "i": 2, + "c": "Leia o guia" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Um arquivo de workflow tem um problema." + }, + " ", + "A última versão que carregou continua em execução." + ], + "ed8ce6ebc73dc12d": "Abrir o arquivo", + "5d8d278ff828102d": "Todos os workflows", + "39459da07479f482": "Agente", + "7741243632056b81": "{step} · transcrição", + "c512071143a5ba32": "Esta thread não existe mais.", + "ed169d23683fb6ac": "Carregando a thread…", + "290e0ab40b87dc17": "Trilha de navegação de workflows", + "683dd9831e54edc0": "Ambiente", + "34ad53646f06ed80": "Os workflows estão desativados", + "8f6589c9e0ac5d4e": "Nenhum ambiente conectado", + "744127f8dfad7d22": "Conecte um ambiente para ver as execuções de workflow dele.", + "036182ec7e2ee4d4": "Ao lado da execução", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definições", + "f0a212aadfe1257b": "Carregando o editor…", + "20f194e003885e95": [ + "Ative-os para este servidor em", + " ", + { + "t": "Link", + "i": 1, + "c": "Configurações → Labs" + }, + "." + ], "8367779e149f723b": "A requisição ao ambiente principal falhou durante {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Token de pareamento inválido. Verifique o token e tente novamente.", "0e4b49c8203aae81": "Tempo esgotado aguardando a sessão autenticada após a inicialização.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 1d8bc14fde51f..f15a9f71b21f2 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Привяжите это окружение к T3 Connect, чтобы получить публичный URL.", "6b80f5b38a8f9950": "Обращаться к этому адресу может только этот компьютер. Привяжите T3 Connect, чтобы получить публичный URL.", "c5a7b1d3891dd0b8": "Работает везде, где доступен адрес этого окружения, например через Tailscale или ваш прокси. Привяжите T3 Connect, чтобы получить публичный URL.", + "3669395daf36fd33": "Больше не зарегистрирован на этом сервере", + "fe513cf316e796e3": "Запускается в составе других воркфлоу", + "ccf00b97925efab3": "Запускается вручную", + "421e585eb092b07b": "Запускается по: {triggers}", + "7bd7c58592671384": "Ждут вас", + "834ca879c14c167b": "Работает", + "582d6df7dfab86fb": "Приостановлен", + "ea6583ce92507ee3": "Спит", + "7ea8cb8af281ce93": "Ожидает", + "1347868f2523140e": "Готово", + "57d76c4614054271": "Остановлен", + "5c7344bd51d0b966": "Пропущен", + "b2074e9bd23049a6": "Отменён", + "5bb7401807ee2fb5": "Спрашивает: {question} и ещё {more}", + "9e4286183d5f9e34": "Спрашивает: {question}", + "474c18d001bd6717": "Шаг завершился ошибкой", + "d3890f4eb1508781": "Выполняет свои шаги", + "3e7ced10c9482af0": "{step} работает", + "237e1bcb1cf1bdec": "Спит на шаге {step}", + "3f7b17ac5a20c8d2": "Запускает {run}", + "0306f5f324b8aaa5": "Запусков в работе: {count}", + "e8fd779b84a202a2": "Ожидает", + "b6d55657e1a027b8": "Ожидает шага {step}", + "e942562a42aede34": "Завершён", + "26b2b9727fe11289": "Завершён досрочно", "1bb995dcec481554": "Подтвердите это устройство на {host}. Там отображается код {verificationCode}.", "8696a33219944832": "Не удалось создать подтверждение авторизации WebSocket.", "5678f133a8631f7d": "Ваш облачный вход изменился. Войдите снова, чтобы авторизовать окружение.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Попробуйте ответить после восстановления подключения или завершения ожидающего ввода.", "604ec3067171a0d7": "Беседа", "d6182a057ea12624": "Родительский тред", + "f2d8537c33cc55a5": "Шаг запуска воркфлоу", + "ba8337dca3232880": "Открыть запуск", "30fa4a764d11ae42": "Не удалось скачать {name}", "4952f87dc98191a7": "Вложение недоступно.", "2fd6d178493fb407": "Не удалось прервать текущий ход.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Открыть пул-реквесты", "57e875b79b98ab82": "Открыть issue", "f1db0a234c777a1d": "Использовать T3 Code в другом приложении (MCP)", + "6050f22f63e2bcb5": "Открыть воркфлоу", "a0cc19e60dd99851": "Открыть использование", "46694969044eee98": "Фокус на следующую панель рабочей области", "0a1011328ba42eef": "Фокус на предыдущую панель рабочей области", @@ -8869,6 +8897,8 @@ "9ae293971d93c819": "Поделитесь тредом с гостем: он смотрит его в браузере в реальном времени и отправляет сообщения, которые вы одобряете. Войдите в T3 Connect, чтобы использовать гостевые ссылки.", "0aa5406ac4d7f7c7": "Гостевые ссылки", "f0e853acd2006d53": "Привязанные окружения", + "ef10c2dff987f3ea": "Запускайте многошаговые воркфлоу из файлов в папке workflows домашней папки T3 этого сервера. Открывайте их из палитры команд. Пока функция выключена, ничего из этой папки не выполняется; запуски ждут, пока её снова не включат.", + "2dadb2359422121c": "Воркфлоу", "13e86eb5d8287a71": "Показывать предполагаемое следующее сообщение в пустом поле ввода после хода Claude или Codex. Tab вставляет его. Каждое — дополнительный кешированный запрос в рамках вашего плана. Нужен Codex 0.165+. Треды Claude обновятся после перезапуска.", "d4b2a2ec812aafb0": "Предлагать следующий промпт", "298c7150a7621c80": "Хосты устройств Simlock", @@ -11815,6 +11845,7 @@ "d443390c4d2dcfd4": "доступность a11y экранный диктор nvda jaws voiceover orca экранный диктор заголовок окна заголовок вкладки alt tab панель задач статус треда порядок в работе подтверждение", "6826fa9579c22035": "бета поделиться гость приглашение ссылка коллега наблюдать t3 connect туннель", "f10c06cba0cdf7fe": "бета привязать другой компьютер vps агенты работают там делегировать", + "bc0b409d89ce086e": "бета воркфлоу workflow надёжные запуски автоматизация шаги расписание webhook папка", "4a21cf825a2045b0": "бета tab автодополнение предсказать следующее сообщение claude codex подсказка", "fea2dc36585c4a20": "Хосты устройств Simlock (альфа)", "9d834d178130180e": "бета альфа simlock callstack симулятор эмулятор ios android пул аренда шлюз", @@ -12371,6 +12402,262 @@ "2cddd6095abc734a": "7 дней", "53493056306708cf": "30 дней", "c719359d18d37ad3": "90 дней", + "0bd950151ddc6407": "Уйти без сохранения? Изменения в этом файле будут потеряны.", + "c0ba3f6756b09f30": "Несохранённые изменения", + "6914e22d357f0ad6": "Сохранено и работает", + "aff389354a031d6f": "Файл на диске не загружается. Продолжает работать последняя версия, которая загрузилась.", + "858effde748ab563": "Сохранено, но пока не запускается.", + "ddb37138df660942": "Не сохранено. На сервере ничего не изменилось.", + "6ef4db489e40e39e": "Не удалось сохранить", + "c89624a2e9af1793": "{name} не подключено", + "b5a352a43adb4c17": "Его рабочие процессы снова появятся после переподключения. Выберите другое окружение, чтобы увидеть его запуски.", + "3dcedb736d20aae5": "Не удалось прочитать файлы воркфлоу", + "b09f4df8d76ae8ea": "Удалить {file}? Воркфлоу, которые он определяет, больше нельзя будет запустить.", + "b4535f5a03689d27": "{name} не подключено. Написанное здесь сохранится, и его можно будет сохранить, когда подключение вернётся.", + "b54c78d85fd942ea": "Удалено, но то, что запущено, ещё не обновилось.", + "407c228d7da0b7df": "Не удалено. На сервере ничего не изменилось.", + "1a6aa10f3cc14fff": "Эти файлы не согласуются между собой. Продолжает работать то, что работало раньше.", + "259312516a1dbe6f": "Имя файла", + "2f48ab2aa0586853": "Не определяет ни одного воркфлоу", + "ba5adfa37b55b8c5": [ + "Строка ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Удалить", + "84c900d1ae72adc6": "Сохранить", + "5912d817be03247a": "Файл изменился на диске, пока вы его редактировали. Сохранение заменит это изменение.", + "0b1e6f5608826387": "Загрузить файл и сбросить мои изменения", + "f47b4c06aeb77c1c": "Загрузка файлов воркфлоу…", + "4353bfd401d58f87": [ + "Каждый файл в", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "определяет воркфлоу. Изменения в любом из них подхватываются без перезапуска." + ], + "0c165251a06f10f1": "Новый файл", + "8e97cf734b4463e7": "Создать", + "2ec0d5108fd6cebe": "Воркфлоу пока нет. Создайте первый файл здесь или попросите агента написать его в этой папке.", + "5601350626e8cfe9": "Не загружается", + "21d778a1b9a0c234": "Открыто рядом с запуском", + "62dc4d3a19ff7ca0": "Закрыть вкладку", + "1e25265f2758fce3": "Открыть как полноценный тред", + "672a3dae06b39402": "Открыть на отдельной странице", + "7755500a4cde5066": "Закрыть панель", + "b8dcbc93a2ca1861": "Этого больше нет в запуске.", + "115c69de3202f664": "Открыть", + "644eafa9048b62df": "{count, plural, =1 {1-я попытка} =2 {2-я попытка} =3 {3-я попытка} one {{count}-я попытка} few {{count}-я попытка} many {{count}-я попытка} other {{count}-я попытка}}", + "e39f89c909df4db0": "Не удалось возобновить запуск", + "865f034346b82f47": "Отменить {title}? Его агенты остановятся, и запуск нельзя будет возобновить.", + "6bc75632fd9c9136": "Не удалось отменить запуск", + "64e50329dcfdd5b0": "Завершён", + "350162e7cc1ebea4": "Остановлен", + "0875cf506f4c6810": "Пропущен", + "3cc43f1dbf3f8e0c": "Отменён", + "ded70e75de6404ba": "Назад к списку запусков", + "2f4ed7dbd22be30d": "Отменить запуск", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "занял {duration}", + "aff78e1774818ff4": "пока {duration}", + "38eddd466439afc9": "Что затронул запуск", + "156ec271d49ddd70": "Что произошло", + "34f59bbbead0b97f": "{names} и ещё {count}", + "ac1556f6ce89a5ea": "параллельно: {count}", + "e197c4963bacc746": "выполняется: {count}", + "f5319ed9e18c0df1": "Спрашивает вас", + "882a25e9084ae1b2": "Приостановлен", + "9a03d8a9afc60387": "Шаги на данный момент", + "2f2ae791afe01674": "ждёт вашего одобрения", + "24f8060c4ccdf928": "запускается", + "30a5be40eb956663": "работает", + "dd7a1e58c2553933": "проснётся через {duration}", + "95cc952724dd7310": "вот-вот проснётся", + "3cc34921c0128593": "выполняется", + "e777db2880f53a46": "никто не ответил", + "dc90739d391a5e67": "Вы ответили: {choice}", + "389f2563b5b763fd": "Быстрые шаги", + "a41c8d758121ad81": "спал", + "9db248b770096984": "ждал", + "c76124517af28686": "выполняется {duration}", + "89102905bf09b0e8": "Смотреть вживую", + "bdf338cdff4118f0": "Транскрипт", + "811e7e992f9ff820": "не может продолжиться, пока версия его воркфлоу не будет снова зарегистрирована", + "4d4cdf035e98dd57": "ждёт, пока вы его возобновите", + "eb5b21dd224a5941": "повторит попытку сам через {duration}", + "6ab3dfa749fde477": "вот-вот повторит попытку сам", + "44b6463aa70aa14c": "Почему приостановлен", + "cf25e7169ab0eb7a": "Приостановлен на шаге {step}", + "56c48c1f220f2754": "Не удалось ответить на вопрос", + "a3c43735e1a81498": "Причина: {title}", + "bfad234f016cfa3f": "Причина в одном предложении. Она прикладывается к любому выбранному ответу.", + "004c41aff9c97873": "Запуски", + "4dc0c244a2419f6c": [ + "В составе: ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "запущен", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "его версия больше не зарегистрирована", + "f92d9132f7b85d1a": "Загрузка шагов…", + "6ebc59f64c761a49": "Пока ничего.", + "a759dccd157d7dae": [ + "Вы ответили:", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Вы ответили:", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " — ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Открыть запуск", + "c8eb9be36d4d51ad": [ + "Тред на ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Возобновить", + "8cebd63fc4c967d5": "Заново выполняется только упавший шаг; всё, что завершилось до него, сохраняется.", + "bc1e0a2a0f1e9552": "Ждут вас", + "a812f51e970740f1": [ + "спросил", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· запуск ждёт вас" + ], + "02dfe6c63fd0b8a1": "Добавить причину", + "19abd94828a3bdbc": "Сначала спросить агента", + "a18721fa8f328361": "Ждут вас", + "bbf24e7920c1e86b": "Выполняются", + "8d6e18d2ad832db6": "Все", + "f25af5332ffc3734": "Вас ничего не ждёт.", + "c3f0119b8d6231f8": "Ничего не выполняется.", + "33028dfc1229eaa6": "Запусков пока нет.", + "5459bf696a187c26": "Не удалось загрузить запуски воркфлоу", + "d57c35d43b0f163a": "Этого запуска здесь нет", + "b9aae2f7cdb1a379": "Запусков воркфлоу пока нет", + "8f15f66e545af7c0": "Какие запуски", + "b6409289e0c9a4dd": "Воркфлоу", + "035cb02ca1ae4952": "Все воркфлоу ({count})", + "46d614fa7b4bf1e5": "Запуски воркфлоу", + "1c635faa2fb45b8b": "Ещё не запускался.", + "156ff7b625287a1e": "Скрыть пропущенные", + "69b985b97ab45e6b": "Показать пропущенные ({count})", + "2400254d362de84d": "Загрузка запусков воркфлоу…", + "145e1f7503ba3b2c": [ + "В этом окружении нет запуска по этой ссылке.", + " ", + { + "t": "button", + "i": 1, + "c": "Вернуться к запускам" + } + ], + "783e616cb0476c17": [ + "Воркфлоу объединяет агентов, код, расписания и вопросы к вам в один запуск, который переживает перезапуски. Напишите его в разделе", + " ", + { + "t": "button", + "i": 1, + "c": "Определения" + }, + " или попросите об этом агента.", + " ", + { + "t": "a", + "i": 2, + "c": "Читать руководство" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "В файле воркфлоу есть ошибка." + }, + " ", + "Продолжает работать последняя версия, которая загрузилась." + ], + "ed8ce6ebc73dc12d": "Открыть файл", + "5d8d278ff828102d": "Все воркфлоу", + "39459da07479f482": "Агент", + "7741243632056b81": "{step} · расшифровка", + "c512071143a5ba32": "Этого треда больше нет.", + "ed169d23683fb6ac": "Загрузка треда…", + "290e0ab40b87dc17": "Навигационная цепочка воркфлоу", + "683dd9831e54edc0": "Окружение", + "34ad53646f06ed80": "Воркфлоу выключены", + "8f6589c9e0ac5d4e": "Нет подключённых окружений", + "744127f8dfad7d22": "Подключите окружение, чтобы увидеть его запуски воркфлоу.", + "036182ec7e2ee4d4": "Рядом с запуском", + "2d6107cb78382d08": "Воркфлоу", + "16f7df687349b399": "Определения", + "f0a212aadfe1257b": "Загрузка редактора…", + "20f194e003885e95": [ + "Включите их для этого сервера в разделе", + " ", + { + "t": "Link", + "i": 1, + "c": "«Настройки → Labs»" + }, + "." + ], "8367779e149f723b": "Запрос к основному окружению не удался во время {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Недействительный токен сопряжения. Проверьте токен и попробуйте ещё раз.", "0e4b49c8203aae81": "Истекло время ожидания аутентифицированного сеанса после начальной загрузки.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 234479a1b2558..6d53cb0b38d73 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "Länka den här miljön till T3 Connect för en publik URL.", "6b80f5b38a8f9950": "Bara den här datorn kan anropa den här adressen. Länka T3 Connect för en publik URL.", "c5a7b1d3891dd0b8": "Fungerar där den här miljöns adress kan nås, till exempel via Tailscale eller din egen proxy. Länka T3 Connect för en publik URL.", + "3669395daf36fd33": "Inte längre registrerat på den här servern", + "fe513cf316e796e3": "Körs som en del av andra arbetsflöden", + "ccf00b97925efab3": "Startas manuellt", + "421e585eb092b07b": "Startar vid {triggers}", + "7bd7c58592671384": "Behöver dig", + "834ca879c14c167b": "Arbetar", + "582d6df7dfab86fb": "Pausad", + "ea6583ce92507ee3": "Sover", + "7ea8cb8af281ce93": "Väntar", + "1347868f2523140e": "Klar", + "57d76c4614054271": "Stoppad", + "5c7344bd51d0b966": "Överhoppad", + "b2074e9bd23049a6": "Avbruten", + "5bb7401807ee2fb5": "Frågar: {question} och {more} till", + "9e4286183d5f9e34": "Frågar: {question}", + "474c18d001bd6717": "Ett steg misslyckades", + "d3890f4eb1508781": "Kör sina egna steg", + "3e7ced10c9482af0": "{step} arbetar", + "237e1bcb1cf1bdec": "Sover vid {step}", + "3f7b17ac5a20c8d2": "Kör {run}", + "0306f5f324b8aaa5": "{count} körningar pågår", + "e8fd779b84a202a2": "Väntar", + "b6d55657e1a027b8": "Väntar på {step}", + "e942562a42aede34": "Klar", + "26b2b9727fe11289": "Avslutad i förtid", "1bb995dcec481554": "Godkänn den här enheten på {host}. Den visar koden {verificationCode}.", "8696a33219944832": "Kunde inte skapa auktoriseringsbeviset för websocket.", "5678f133a8631f7d": "Din molninloggning har ändrats. Logga in igen för att auktorisera miljön.", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "Försök svara när anslutningen eller den väntande inmatningen är löst.", "604ec3067171a0d7": "Konversation", "d6182a057ea12624": "Överordnad tråd", + "f2d8537c33cc55a5": "Steg i arbetsflödeskörningen", + "ba8337dca3232880": "Öppna körning", "30fa4a764d11ae42": "Kunde inte ladda ned {name}", "4952f87dc98191a7": "Bilagan är inte tillgänglig.", "2fd6d178493fb407": "Det gick inte att avbryta den aktuella omgången.", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "Öppna pull requests", "57e875b79b98ab82": "Öppna ärenden", "f1db0a234c777a1d": "Använd T3 Code i en annan app (MCP)", + "6050f22f63e2bcb5": "Öppna arbetsflöden", "a0cc19e60dd99851": "Öppna användning", "46694969044eee98": "Fokusera nästa område i arbetsytan", "0a1011328ba42eef": "Fokusera föregående område i arbetsytan", @@ -8875,6 +8903,8 @@ "9ae293971d93c819": "Dela en tråd med en gäst som följer den live i en webbläsare och skickar meddelanden som du godkänner. Logga in på T3 Connect för att använda gästlänkar.", "0aa5406ac4d7f7c7": "Gästlänkar", "f0e853acd2006d53": "Länkade miljöer", + "ef10c2dff987f3ea": "Kör arbetsflöden i flera steg från filer i mappen workflows i serverns T3-hemkatalog. Öppna dem från kommandopaletten. När det är av körs inget i mappen; körningar väntar tills det slås på igen.", + "2dadb2359422121c": "Arbetsflöden", "13e86eb5d8287a71": "Visa ett förutsagt nästa meddelande i det tomma inmatningsfältet efter en omgång med Claude eller Codex. Tab använder det. Varje förslag är en extra cachad begäran i ditt abonnemang. Kräver Codex 0.165+. Claude-trådar uppdateras vid omstart.", "d4b2a2ec812aafb0": "Föreslå nästa prompt", "298c7150a7621c80": "Simlock-enhetsvärdar", @@ -11822,6 +11852,7 @@ "d443390c4d2dcfd4": "tillgänglighet a11y skärmläsare nvda jaws voiceover orca skärmläsaren fönstertitel fliktitel alt tab aktivitetsfält trådstatus ordning arbetar godkännande", "6826fa9579c22035": "beta dela gäst bjud in länk kollega titta t3 connect tunnel", "f10c06cba0cdf7fe": "beta länka en annan dator vps peer agenter arbetar där delegera", + "bc0b409d89ce086e": "beta arbetsflöde workflow beständiga körningar automatisering steg schema webhook mapp", "4a21cf825a2045b0": "beta tabb autokomplettering förutsäg nästa meddelande claude codex spöktext", "fea2dc36585c4a20": "Simlock-enhetsvärdar (alfa)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lån gateway", @@ -12378,6 +12409,262 @@ "2cddd6095abc734a": "7 dagar", "53493056306708cf": "30 dagar", "c719359d18d37ad3": "90 dagar", + "0bd950151ddc6407": "Lämna utan att spara? Dina ändringar i filen går förlorade.", + "c0ba3f6756b09f30": "Osparade ändringar", + "6914e22d357f0ad6": "Sparad och körs", + "aff389354a031d6f": "Filen på disken går inte att läsa in. Den senaste versionen som gick att läsa in körs vidare.", + "858effde748ab563": "Sparad, men den körs inte än.", + "ddb37138df660942": "Inte sparad. Inget ändrades på servern.", + "6ef4db489e40e39e": "Kunde inte spara", + "c89624a2e9af1793": "{name} är inte ansluten", + "b5a352a43adb4c17": "Dess arbetsflöden visas igen när den ansluter igen. Välj en annan miljö för att se dess körningar.", + "3dcedb736d20aae5": "Kunde inte läsa arbetsflödesfilerna", + "b09f4df8d76ae8ea": "Ta bort {file}? Arbetsflödena som den definierar kan inte längre startas.", + "b4535f5a03689d27": "{name} är inte ansluten. Det du skriver här finns kvar och kan sparas när den är tillbaka.", + "b54c78d85fd942ea": "Borttagen, men det som körs har inte hunnit ikapp än.", + "407c228d7da0b7df": "Inte borttagen. Inget ändrades på servern.", + "1a6aa10f3cc14fff": "De här filerna passar inte ihop. Det som kördes förut körs vidare.", + "259312516a1dbe6f": "Filnamn", + "2f48ab2aa0586853": "Definierar inga arbetsflöden", + "ba5adfa37b55b8c5": [ + "Rad ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Ta bort", + "84c900d1ae72adc6": "Spara", + "5912d817be03247a": "Filen ändrades på disken medan du redigerade. Om du sparar ersätts den ändringen.", + "0b1e6f5608826387": "Läs in filen och släng mina ändringar", + "f47b4c06aeb77c1c": "Läser in arbetsflödesfilerna…", + "4353bfd401d58f87": [ + "Varje fil i", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "definierar arbetsflöden. En ändring i någon av dem plockas upp utan omstart." + ], + "0c165251a06f10f1": "Ny fil", + "8e97cf734b4463e7": "Skapa", + "2ec0d5108fd6cebe": "Inga arbetsflöden än. Skapa den första filen här, eller be en agent skriva en i den mappen.", + "5601350626e8cfe9": "Går inte att läsa in", + "21d778a1b9a0c234": "Öppet bredvid körningen", + "62dc4d3a19ff7ca0": "Stäng flik", + "1e25265f2758fce3": "Öppna som en hel tråd", + "672a3dae06b39402": "Öppna på en egen sida", + "7755500a4cde5066": "Stäng panelen", + "b8dcbc93a2ca1861": "Körningen listar det inte längre.", + "115c69de3202f664": "Öppna", + "644eafa9048b62df": "{count, plural, =1 {1:a försöket} =2 {2:a försöket} =3 {3:e försöket} other {försök {count}}}", + "e39f89c909df4db0": "Kunde inte återuppta körningen", + "865f034346b82f47": "Avbryta {title}? Dess agenter stoppas och körningen kan inte återupptas.", + "6bc75632fd9c9136": "Kunde inte avbryta körningen", + "64e50329dcfdd5b0": "Klar", + "350162e7cc1ebea4": "Stoppad", + "0875cf506f4c6810": "Överhoppad", + "3cc43f1dbf3f8e0c": "Avbruten", + "ded70e75de6404ba": "Tillbaka till listan över körningar", + "2f4ed7dbd22be30d": "Avbryt körningen", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "tog {duration}", + "aff78e1774818ff4": "{duration} hittills", + "38eddd466439afc9": "Vad körningen rörde", + "156ec271d49ddd70": "Vad som hände", + "34f59bbbead0b97f": "{names} och {count} till", + "ac1556f6ce89a5ea": "{count} parallellt", + "e197c4963bacc746": "{count} körs", + "f5319ed9e18c0df1": "Frågar dig", + "882a25e9084ae1b2": "Pausad", + "9a03d8a9afc60387": "Steg hittills", + "2f2ae791afe01674": "väntar på ditt godkännande", + "24f8060c4ccdf928": "startar", + "30a5be40eb956663": "arbetar", + "dd7a1e58c2553933": "vaknar om {duration}", + "95cc952724dd7310": "vaknar strax", + "3cc34921c0128593": "körs", + "e777db2880f53a46": "ingen svarade", + "dc90739d391a5e67": "Du svarade {choice}", + "389f2563b5b763fd": "Snabba steg", + "a41c8d758121ad81": "sov", + "9db248b770096984": "väntade", + "c76124517af28686": "har körts i {duration}", + "89102905bf09b0e8": "Följ live", + "bdf338cdff4118f0": "Transkript", + "811e7e992f9ff820": "kan inte fortsätta förrän dess arbetsflödesversion registreras igen", + "4d4cdf035e98dd57": "väntar på att du återupptar den", + "eb5b21dd224a5941": "försöker igen själv om {duration}", + "6ab3dfa749fde477": "försöker strax igen själv", + "44b6463aa70aa14c": "Varför den pausades", + "cf25e7169ab0eb7a": "Pausad vid {step}", + "56c48c1f220f2754": "Kunde inte svara på frågan", + "a3c43735e1a81498": "Skäl för {title}", + "bfad234f016cfa3f": "Varför, i en mening. Det följer med vilket svar du än väljer.", + "004c41aff9c97873": "Körningar", + "4dc0c244a2419f6c": [ + "Del av ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "startade", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "dess version är inte längre registrerad", + "f92d9132f7b85d1a": "Läser in steg…", + "6ebc59f64c761a49": "Inget än.", + "a759dccd157d7dae": [ + "Du svarade", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Du svarade", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Öppna körning", + "c8eb9be36d4d51ad": [ + "Tråd på ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Återuppta", + "8cebd63fc4c967d5": "Bara det misslyckade steget körs igen; det som blev klart före det behålls.", + "bc1e0a2a0f1e9552": "Behöver dig", + "a812f51e970740f1": [ + "frågade", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· körningen väntar på dig" + ], + "02dfe6c63fd0b8a1": "Lägg till ett skäl", + "19abd94828a3bdbc": "Fråga agenten först", + "a18721fa8f328361": "Behöver dig", + "bbf24e7920c1e86b": "Körs", + "8d6e18d2ad832db6": "Alla", + "f25af5332ffc3734": "Inget väntar på dig.", + "c3f0119b8d6231f8": "Inget körs.", + "33028dfc1229eaa6": "Inga körningar än.", + "5459bf696a187c26": "Kunde inte läsa in arbetsflödeskörningarna", + "d57c35d43b0f163a": "Den här körningen finns inte här", + "b9aae2f7cdb1a379": "Inga arbetsflödeskörningar än", + "8f15f66e545af7c0": "Vilka körningar", + "b6409289e0c9a4dd": "Arbetsflöde", + "035cb02ca1ae4952": "Alla arbetsflöden ({count})", + "46d614fa7b4bf1e5": "Arbetsflödeskörningar", + "1c635faa2fb45b8b": "Har inte körts än.", + "156ff7b625287a1e": "Dölj överhoppade", + "69b985b97ab45e6b": "Visa överhoppade ({count})", + "2400254d362de84d": "Läser in arbetsflödeskörningar…", + "145e1f7503ba3b2c": [ + "Den här miljön har ingen körning med den länken.", + " ", + { + "t": "button", + "i": 1, + "c": "Tillbaka till körningarna" + } + ], + "783e616cb0476c17": [ + "Ett arbetsflöde knyter ihop agenter, kod, scheman och frågor till dig i en enda körning som överlever omstarter. Skriv ett under", + " ", + { + "t": "button", + "i": 1, + "c": "Definitioner" + }, + ", eller be en agent göra det.", + " ", + { + "t": "a", + "i": 2, + "c": "Läs guiden" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "En arbetsflödesfil har ett problem." + }, + " ", + "Den senaste versionen som gick att läsa in körs vidare." + ], + "ed8ce6ebc73dc12d": "Öppna filen", + "5d8d278ff828102d": "Alla arbetsflöden", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transkript", + "c512071143a5ba32": "Den här tråden finns inte längre.", + "ed169d23683fb6ac": "Läser in tråden…", + "290e0ab40b87dc17": "Brödsmulor för arbetsflöden", + "683dd9831e54edc0": "Miljö", + "34ad53646f06ed80": "Arbetsflöden är avstängda", + "8f6589c9e0ac5d4e": "Ingen miljö ansluten", + "744127f8dfad7d22": "Anslut en miljö för att se dess arbetsflödeskörningar.", + "036182ec7e2ee4d4": "Bredvid körningen", + "2d6107cb78382d08": "Arbetsflöden", + "16f7df687349b399": "Definitioner", + "f0a212aadfe1257b": "Läser in redigeraren…", + "20f194e003885e95": [ + "Slå på dem för den här servern i", + " ", + { + "t": "Link", + "i": 1, + "c": "Inställningar → Labs" + }, + "." + ], "8367779e149f723b": "Begäran till den primära miljön misslyckades under {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Ogiltig parkopplingstoken. Kontrollera token och försök igen.", "0e4b49c8203aae81": "Tidsgränsen överskreds i väntan på en autentiserad session efter uppstart.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 19eff455a318c..deaa65edcc1ec 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -396,6 +396,31 @@ "476ca970255eaea4": "将此环境关联到 T3 Connect,获取公网 URL。", "6b80f5b38a8f9950": "只有本机可以访问此地址。关联 T3 Connect 可获取公网 URL。", "c5a7b1d3891dd0b8": "只要能连接此环境的地址(例如通过 Tailscale 或你自己的代理)即可使用。关联 T3 Connect 可获取公网 URL。", + "3669395daf36fd33": "已不再注册到此服务器", + "fe513cf316e796e3": "作为其他工作流的一部分运行", + "ccf00b97925efab3": "手动启动", + "421e585eb092b07b": "由 {triggers} 触发启动", + "7bd7c58592671384": "等你处理", + "834ca879c14c167b": "运行中", + "582d6df7dfab86fb": "已暂停", + "ea6583ce92507ee3": "休眠中", + "7ea8cb8af281ce93": "等待中", + "1347868f2523140e": "完成", + "57d76c4614054271": "已停止", + "5c7344bd51d0b966": "已跳过", + "b2074e9bd23049a6": "已取消", + "5bb7401807ee2fb5": "提问:{question},另有 {more} 个", + "9e4286183d5f9e34": "提问:{question}", + "474c18d001bd6717": "有步骤失败", + "d3890f4eb1508781": "正在运行自身的步骤", + "3e7ced10c9482af0": "{step} 正在运行", + "237e1bcb1cf1bdec": "在 {step} 休眠中", + "3f7b17ac5a20c8d2": "运行 {run}", + "0306f5f324b8aaa5": "{count} 个运行进行中", + "e8fd779b84a202a2": "等待中", + "b6d55657e1a027b8": "正在等待 {step}", + "e942562a42aede34": "已完成", + "26b2b9727fe11289": "提前结束", "1bb995dcec481554": "请在 {host} 上批准此设备。它会显示代码 {verificationCode}。", "8696a33219944832": "无法创建 WebSocket 授权证明。", "5678f133a8631f7d": "你的云端登录已变化。请重新登录以授权环境。", @@ -1744,6 +1769,8 @@ "2e995206e087c3fc": "请在连接恢复或待处理的输入完成后重试回复。", "604ec3067171a0d7": "对话", "d6182a057ea12624": "父会话", + "f2d8537c33cc55a5": "工作流运行的步骤", + "ba8337dca3232880": "打开运行", "30fa4a764d11ae42": "无法下载 {name}", "4952f87dc98191a7": "附件不可用。", "2fd6d178493fb407": "无法中断当前这一轮。", @@ -1829,6 +1856,7 @@ "04fd71efaa2c3b92": "打开 PR", "57e875b79b98ab82": "打开 issue", "f1db0a234c777a1d": "在其他应用中使用 T3 Code(MCP)", + "6050f22f63e2bcb5": "打开工作流", "a0cc19e60dd99851": "打开用量", "46694969044eee98": "聚焦下一个工作区区域", "0a1011328ba42eef": "聚焦上一个工作区区域", @@ -8885,6 +8913,8 @@ "9ae293971d93c819": "与访客共享会话,访客可在浏览器中实时查看,并发送需要你批准的消息。登录 T3 Connect 后即可使用访客链接。", "0aa5406ac4d7f7c7": "访客链接", "f0e853acd2006d53": "关联环境", + "ef10c2dff987f3ea": "从此服务器 T3 主目录下 workflows 文件夹中的文件运行多步骤工作流。可从命令面板打开。关闭期间,该文件夹中的内容都不会运行;运行会等到重新开启后继续。", + "2dadb2359422121c": "工作流", "13e86eb5d8287a71": "Claude 或 Codex 完成一轮回复后,在空输入框中预测下一条消息。按 Tab 使用它。每次预测都会在你的套餐上产生一次额外的缓存请求。需要 Codex 0.165+。Claude 会话在重启后更新。", "d4b2a2ec812aafb0": "建议下一条提示词", "298c7150a7621c80": "Simlock 设备主机", @@ -11839,6 +11869,7 @@ "d443390c4d2dcfd4": "无障碍 a11y 屏幕阅读器 nvda jaws voiceover orca 讲述人 窗口标题 标签页标题 alt tab 任务栏 会话状态 顺序 运行中 批准", "6826fa9579c22035": "测试版 共享 访客 邀请 链接 队友 观看 t3 connect 隧道", "f10c06cba0cdf7fe": "测试版 关联 另一台机器 vps 对等 智能体 在那里工作 委派", + "bc0b409d89ce086e": "测试版 工作流 workflow 持久 运行 自动化 步骤 计划 webhook 文件夹", "4a21cf825a2045b0": "测试版 tab 自动补全 预测 下一条消息 claude codex 幽灵文本", "fea2dc36585c4a20": "Simlock 设备主机(早期测试)", "9d834d178130180e": "测试版 alpha simlock callstack 模拟器 ios android 池 租用 网关", @@ -12396,6 +12427,255 @@ "2cddd6095abc734a": "7 天", "53493056306708cf": "30 天", "c719359d18d37ad3": "90 天", + "0bd950151ddc6407": "不保存就离开?对此文件的更改将丢失。", + "c0ba3f6756b09f30": "未保存的更改", + "6914e22d357f0ad6": "已保存并生效", + "aff389354a031d6f": "磁盘上的文件无法加载。上一个可加载的版本会继续运行。", + "858effde748ab563": "已保存,但尚未运行。", + "ddb37138df660942": "未保存。服务器上没有任何更改。", + "6ef4db489e40e39e": "无法保存", + "c89624a2e9af1793": "{name} 未连接", + "b5a352a43adb4c17": "重新连接后,它的工作流会再次显示。选择其他环境可查看其运行。", + "3dcedb736d20aae5": "无法读取工作流文件", + "b09f4df8d76ae8ea": "要删除 {file} 吗?它定义的工作流将无法再启动。", + "b4535f5a03689d27": "{name} 未连接。你在这里写的内容会保留,重新连接后即可保存。", + "b54c78d85fd942ea": "已删除,但正在运行的内容尚未更新。", + "407c228d7da0b7df": "未删除。服务器上没有任何更改。", + "1a6aa10f3cc14fff": "这些文件彼此不匹配。之前的版本会继续运行。", + "259312516a1dbe6f": "文件名", + "2f48ab2aa0586853": "未定义任何工作流", + "ba5adfa37b55b8c5": [ + "第 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 行:" + ], + "d94eb9ab3201b641": "删除", + "84c900d1ae72adc6": "保存", + "5912d817be03247a": "编辑期间磁盘上的文件发生了变化。保存会覆盖该变化。", + "0b1e6f5608826387": "加载该文件并放弃我的更改", + "f47b4c06aeb77c1c": "正在加载工作流文件…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "中的每个文件都定义工作流。修改后无需重启即可生效。" + ], + "0c165251a06f10f1": "新建文件", + "8e97cf734b4463e7": "创建", + "2ec0d5108fd6cebe": "还没有工作流。在这里创建第一个文件,或让智能体在该文件夹中编写一个。", + "5601350626e8cfe9": "无法加载", + "21d778a1b9a0c234": "在运行旁打开的内容", + "62dc4d3a19ff7ca0": "关闭标签页", + "1e25265f2758fce3": "作为完整会话打开", + "672a3dae06b39402": "在单独的页面打开", + "7755500a4cde5066": "关闭面板", + "b8dcbc93a2ca1861": "此运行不再列出它。", + "115c69de3202f664": "打开", + "644eafa9048b62df": "{count, plural, =1 {第 1 次尝试} =2 {第 2 次尝试} =3 {第 3 次尝试} other {第 {count} 次尝试}}", + "e39f89c909df4db0": "无法继续此运行", + "865f034346b82f47": "要取消 {title} 吗?其智能体将停止,且此运行无法再继续。", + "6bc75632fd9c9136": "无法取消此运行", + "64e50329dcfdd5b0": "已完成", + "350162e7cc1ebea4": "已停止", + "0875cf506f4c6810": "已跳过", + "3cc43f1dbf3f8e0c": "已取消", + "ded70e75de6404ba": "返回运行列表", + "2f4ed7dbd22be30d": "取消运行", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "用时 {duration}", + "aff78e1774818ff4": "已用时 {duration}", + "38eddd466439afc9": "此运行涉及的内容", + "156ec271d49ddd70": "经过", + "34f59bbbead0b97f": "{names} 等另外 {count} 个", + "ac1556f6ce89a5ea": "{count} 个并行", + "e197c4963bacc746": "{count} 个运行中", + "f5319ed9e18c0df1": "向你提问", + "882a25e9084ae1b2": "已暂停", + "9a03d8a9afc60387": "目前的步骤", + "2f2ae791afe01674": "等待你的批准", + "24f8060c4ccdf928": "正在启动", + "30a5be40eb956663": "工作中", + "dd7a1e58c2553933": "{duration} 后唤醒", + "95cc952724dd7310": "即将唤醒", + "3cc34921c0128593": "运行中", + "e777db2880f53a46": "无人回答", + "dc90739d391a5e67": "你的回答:{choice}", + "389f2563b5b763fd": "快速步骤", + "a41c8d758121ad81": "已休眠", + "9db248b770096984": "已等待", + "c76124517af28686": "已运行 {duration}", + "89102905bf09b0e8": "实时查看", + "bdf338cdff4118f0": "对话记录", + "811e7e992f9ff820": "需重新注册其工作流版本后才能继续", + "4d4cdf035e98dd57": "等你手动继续", + "eb5b21dd224a5941": "{duration} 后自动重试", + "6ab3dfa749fde477": "即将自动重试", + "44b6463aa70aa14c": "暂停原因", + "cf25e7169ab0eb7a": "暂停于 {step}", + "56c48c1f220f2754": "无法回答此问题", + "a3c43735e1a81498": "{title} 的理由", + "bfad234f016cfa3f": "用一句话说明理由。无论你选哪个回答,它都会一并附上。", + "004c41aff9c97873": "运行", + "4dc0c244a2419f6c": [ + "属于 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "开始" + ], + "8bffb377e2a6a7de": "其版本已不再注册", + "f92d9132f7b85d1a": "正在加载步骤…", + "6ebc59f64c761a49": "暂无内容。", + "a759dccd157d7dae": [ + "你的回答:", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "你的回答:", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ":", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "打开运行", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 上的会话" + ], + "3d9761e81798fcd8": "继续", + "8cebd63fc4c967d5": "只会重新运行失败的步骤;此前已完成的内容会保留。", + "bc1e0a2a0f1e9552": "等你处理", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "提问", + " ", + "· 运行正在等你回答" + ], + "02dfe6c63fd0b8a1": "添加理由", + "19abd94828a3bdbc": "先问问智能体", + "a18721fa8f328361": "等你处理", + "bbf24e7920c1e86b": "运行中", + "8d6e18d2ad832db6": "全部", + "f25af5332ffc3734": "没有等你处理的内容。", + "c3f0119b8d6231f8": "没有正在运行的内容。", + "33028dfc1229eaa6": "还没有运行。", + "5459bf696a187c26": "无法加载工作流运行", + "d57c35d43b0f163a": "此运行不在这里", + "b9aae2f7cdb1a379": "还没有工作流运行", + "8f15f66e545af7c0": "显示哪些运行", + "b6409289e0c9a4dd": "工作流", + "035cb02ca1ae4952": "全部 {count} 个工作流", + "46d614fa7b4bf1e5": "工作流运行", + "1c635faa2fb45b8b": "尚未运行过。", + "156ff7b625287a1e": "隐藏已跳过", + "69b985b97ab45e6b": "显示 {count} 个已跳过", + "2400254d362de84d": "正在加载工作流运行…", + "145e1f7503ba3b2c": [ + "此环境中没有该链接对应的运行。", + " ", + { + "t": "button", + "i": 1, + "c": "返回运行列表" + } + ], + "783e616cb0476c17": [ + "工作流将智能体、代码、定时计划和向你提出的问题串联成一次重启后仍会继续的运行。可在", + " ", + { + "t": "button", + "i": 1, + "c": "定义" + }, + " ", + "中编写,或让智能体代写。", + " ", + { + "t": "a", + "i": 2, + "c": "阅读指南" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "有工作流文件存在问题。" + }, + "上一个可加载的版本会继续运行。" + ], + "ed8ce6ebc73dc12d": "打开文件", + "5d8d278ff828102d": "全部工作流", + "39459da07479f482": "智能体", + "7741243632056b81": "{step} · 记录", + "c512071143a5ba32": "此会话已不存在。", + "ed169d23683fb6ac": "正在加载会话…", + "290e0ab40b87dc17": "工作流面包屑导航", + "683dd9831e54edc0": "环境", + "34ad53646f06ed80": "工作流已关闭", + "8f6589c9e0ac5d4e": "未连接任何环境", + "744127f8dfad7d22": "连接一个环境以查看其工作流运行。", + "036182ec7e2ee4d4": "运行旁", + "2d6107cb78382d08": "工作流", + "16f7df687349b399": "定义", + "f0a212aadfe1257b": "正在加载编辑器…", + "20f194e003885e95": [ + "在此服务器的", + " ", + { + "t": "Link", + "i": 1, + "c": "设置 → Labs" + }, + " 中开启。" + ], "8367779e149f723b": "主环境请求在 {operation} 期间失败(HTTP {status})。", "c5cd027743a2b5a6": "配对 token 无效。请检查后重试。", "0e4b49c8203aae81": "引导完成后等待登录状态超时。", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 2b19b90cc28e3..15380512f4060 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -231,6 +231,10 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil --animate-stash-pulse-row: stash-pulse-row 1400ms; --animate-stash-pulse-row-alt: stash-pulse-row-alt 1400ms; --animate-stash-pulse-count: stash-pulse-count 1400ms step-start; + /* One-off arrivals in a workflow run's timeline; nothing here loops. */ + --animate-step-in: step-in 180ms ease-out; + --animate-step-ping: step-ping 520ms ease-out; + --animate-check-draw: check-draw 200ms ease-out; --color-warning-foreground: var(--warning-foreground); --color-warning: var(--warning); --color-warning-surface: var(--warning-surface); @@ -345,6 +349,27 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil opacity: 1; } } + @keyframes step-in { + from { + opacity: 0; + translate: 0 4px; + } + } + @keyframes step-ping { + from { + opacity: 0.55; + scale: 0.7; + } + to { + opacity: 0; + scale: 1.45; + } + } + @keyframes check-draw { + from { + stroke-dashoffset: 12; + } + } @keyframes status-ping { /* Burst first (immediate feedback for click ripples), then hold invisible for the rest of the cycle. Mirrors animate-ping's diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 2d2e74ab58ef2..b1cc1b86c29ba 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -18,6 +18,7 @@ import { Route as ApproveAgentRouteImport } from './routes/approve-agent' import { Route as ChatRouteImport } from './routes/_chat' import { Route as ChatIndexRouteImport } from './routes/_chat.index' import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey' +import { Route as ChatWorkflowsRouteImport } from './routes/_chat.workflows' import { Route as ChatUsageRouteImport } from './routes/_chat.usage' import { Route as ChatSettingsRouteImport } from './routes/_chat.settings' import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-requests' @@ -99,6 +100,11 @@ const ProjectsProjectKeyRoute = ProjectsProjectKeyRouteImport.update({ path: '/projects/$projectKey', getParentRoute: () => rootRouteImport, } as any) +const ChatWorkflowsRoute = ChatWorkflowsRouteImport.update({ + id: '/workflows', + path: '/workflows', + getParentRoute: () => ChatRoute, +} as any) const ChatUsageRoute = ChatUsageRouteImport.update({ id: '/usage', path: '/usage', @@ -302,6 +308,7 @@ export interface FileRoutesByFullPath { '/pull-requests': typeof ChatPullRequestsRoute '/settings': typeof ChatSettingsRouteWithChildren '/usage': typeof ChatUsageRoute + '/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute '/draft/$draftId': typeof ChatDraftDraftIdRoute @@ -347,6 +354,7 @@ export interface FileRoutesByTo { '/pull-requests': typeof ChatPullRequestsRoute '/settings': typeof ChatSettingsRouteWithChildren '/usage': typeof ChatUsageRoute + '/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/': typeof ChatIndexRoute '/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute @@ -395,6 +403,7 @@ export interface FileRoutesById { '/_chat/pull-requests': typeof ChatPullRequestsRoute '/_chat/settings': typeof ChatSettingsRouteWithChildren '/_chat/usage': typeof ChatUsageRoute + '/_chat/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/_chat/': typeof ChatIndexRoute '/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute @@ -444,6 +453,7 @@ export interface FileRouteTypes { | '/pull-requests' | '/settings' | '/usage' + | '/workflows' | '/projects/$projectKey' | '/$environmentId/$threadId' | '/draft/$draftId' @@ -489,6 +499,7 @@ export interface FileRouteTypes { | '/pull-requests' | '/settings' | '/usage' + | '/workflows' | '/projects/$projectKey' | '/' | '/$environmentId/$threadId' @@ -536,6 +547,7 @@ export interface FileRouteTypes { | '/_chat/pull-requests' | '/_chat/settings' | '/_chat/usage' + | '/_chat/workflows' | '/projects/$projectKey' | '/_chat/' | '/_chat/$environmentId/$threadId' @@ -648,6 +660,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ProjectsProjectKeyRouteImport parentRoute: typeof rootRouteImport } + '/_chat/workflows': { + id: '/_chat/workflows' + path: '/workflows' + fullPath: '/workflows' + preLoaderRoute: typeof ChatWorkflowsRouteImport + parentRoute: typeof ChatRoute + } '/_chat/usage': { id: '/_chat/usage' path: '/usage' @@ -973,6 +992,7 @@ interface ChatRouteChildren { ChatPullRequestsRoute: typeof ChatPullRequestsRoute ChatSettingsRoute: typeof ChatSettingsRouteWithChildren ChatUsageRoute: typeof ChatUsageRoute + ChatWorkflowsRoute: typeof ChatWorkflowsRoute ChatIndexRoute: typeof ChatIndexRoute ChatEnvironmentIdThreadIdRoute: typeof ChatEnvironmentIdThreadIdRoute ChatDraftDraftIdRoute: typeof ChatDraftDraftIdRoute @@ -985,6 +1005,7 @@ const ChatRouteChildren: ChatRouteChildren = { ChatPullRequestsRoute: ChatPullRequestsRoute, ChatSettingsRoute: ChatSettingsRouteWithChildren, ChatUsageRoute: ChatUsageRoute, + ChatWorkflowsRoute: ChatWorkflowsRoute, ChatIndexRoute: ChatIndexRoute, ChatEnvironmentIdThreadIdRoute: ChatEnvironmentIdThreadIdRoute, ChatDraftDraftIdRoute: ChatDraftDraftIdRoute, diff --git a/apps/web/src/routes/_chat.workflows.tsx b/apps/web/src/routes/_chat.workflows.tsx new file mode 100644 index 0000000000000..c755da76d5b38 --- /dev/null +++ b/apps/web/src/routes/_chat.workflows.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { readWorkflowPane } from "../components/workflows/workflowPane.logic"; +import { WorkflowsPage, type WorkflowsSearch } from "../components/workflows/WorkflowsPage"; + +export const Route = createFileRoute("/_chat/workflows")({ + validateSearch: (raw: Record): WorkflowsSearch => ({ + ...(typeof raw.env === "string" && raw.env ? { env: raw.env.slice(0, 200) } : {}), + ...(typeof raw.run === "string" && raw.run ? { run: raw.run.slice(0, 200) } : {}), + ...readWorkflowPane(raw.pane, raw.tab), + ...(raw.definitions === true || raw.definitions === "true" ? { definitions: true } : {}), + ...(typeof raw.file === "string" && raw.file ? { file: raw.file.slice(0, 200) } : {}), + }), + component: WorkflowsPage, +}); diff --git a/docs/user/workflows.md b/docs/user/workflows.md new file mode 100644 index 0000000000000..3327d28062bf9 --- /dev/null +++ b/docs/user/workflows.md @@ -0,0 +1,92 @@ +# Workflows + +A workflow is a TypeScript script that chains agents, plain code, schedules, webhooks, issue and pull request events, and questions to you into one durable run that survives server restarts. Each step's result is saved when it succeeds, so restarts pick up where the run left off and failures do not lose earlier work. Workflows are an early feature: start runs from the `t3` CLI or a trigger, and follow them in the app. + +For one prompt on a timer or webhook, use a scheduled task. Use a workflow when work has stages — such as triage, a fix, your approval, and a release. + +## Turn on workflows + +Workflows are a Labs feature, off by default. Turn on **Settings → Labs → Workflows** for the server that runs them. On a server without a desktop, set `"workflowsEnabled": true` in `userdata/settings.json` in its T3 home (`~/.t3` by default). While off, nothing in the workflows folder runs and `t3 workflow` says how to turn it on; runs are kept and continue once it is on again. + +## Create a workflow + +Workflow files live in `~/.t3/workflows/` (or wherever `T3CODE_WORKFLOWS` points — a folder or a single file). The server watches the folder and reloads changes without a restart. + +- **Ask an agent (recommended):** copy the [`t3-workflows` skill](https://github.com/pingdotgg/t3code/blob/main/skills/t3-workflows/SKILL.md) into your agent's skills folder (such as `~/.claude/skills/` or `~/.agents/skills/`) and describe what you want. +- **Edit directly:** edit files in `~/.t3/workflows/`, or use **Definitions** on the Workflows page (saving and deleting in the app require terminal access). Before anything has run, open the page with **Open workflows** in the command palette. + +A small workflow, saved as `~/.t3/workflows/release.ts`: + +```ts +const { workflow, step, ask, stop, title } = T3; + +export default workflow( + "release", + { version: 1, payload: Schema.Struct({ name: Schema.String }) }, + Effect.fn(function* (payload) { + yield* title(`Release ${payload.name}`); + const notes = yield* step("notes", { returns: Schema.String }, Effect.succeed("3 fixes")); + const answer = yield* ask("ship", { + title: `Ship ${payload.name}? ${notes}`, + choices: ["Ship", "Hold"], + }); + if (Option.isNone(answer) || answer.value.choice !== "Ship") return yield* stop("held back"); + return { shipped: payload.name }; + }), +); +``` + +Start it with `t3 workflow start release --input '{"name":"v1.4"}' --key v1.4`, then answer its question in the app. `T3`, `Effect`, `Schema` and `Option` are provided; a workflow file imports nothing from T3 or Effect. Name files with letters, digits, `-`, `_` and `.`; other names are skipped with a warning. + +Saving checks that the file loads, does not duplicate a workflow name and version, and does not remove a version with unfinished runs. A file that fails these checks keeps its last working version while the Workflows page (and the server log) shows why; other files are not affected. A change held back by unfinished runs goes in by itself once those runs end or are cancelled. Mistakes inside a workflow body surface when a run hits them and pauses. To change steps while runs are unfinished, add the new body under a higher `version` and keep the old one until those runs end. + +Dot-files and subfolders are ignored. Keep shared helpers in a subfolder and restart the server after editing an imported file. + +## Start and steer + +```sh +t3 workflow start --input '' --key +t3 workflow list [--status paused] +t3 workflow show +t3 workflow resume +t3 workflow cancel [--reason ''] +t3 workflow questions +t3 workflow signal '{"choice":"yes"}' --run --wait +t3 workflow signal '' --workflow --channel +t3 workflow hooks +t3 workflow store list +t3 workflow store set '' +``` + +Every start needs a `--key`: starting twice with the same key returns the same run — even after a version bump — so retries do not duplicate work. Use `signal` with `--run` and `--wait` to answer a question or wake a run, or with `--workflow` and `--channel` to wake whichever run waits on that channel. A signal for a question that is no longer open is kept for a later wait rather than refused, so check `t3 workflow questions` first. Use `store` to read or change state kept between runs. + +## Triggers + +- **Schedules:** `every` runs on an interval, starting one interval after the workflow loads; `daily` runs at a local time of day (a time missed by more than 10 minutes while the server is down is skipped). +- **Webhooks:** `t3 workflow hooks` prints each hook's path; prepend your server's address. The path contains the hook's secret, so share it only with the sender. A sender's retry that repeats its delivery header (such as GitHub's `X-GitHub-Delivery`) starts no second run, and bodies over 1 MiB are refused. Organization policies blocking webhook tasks block workflow webhooks too. +- **Issues and pull requests:** workflows can start on new issues or pull requests and read, comment on, or update them via **Settings → Source control & issues** — no webhook needed. T3 Code checks roughly once a minute, and only items opened after the workflow was first loaded start runs. + +## Follow runs in the app + +Open the Workflows page with **Open workflows** in the command palette of the web or desktop app; the entry shows once a connected server has workflows on. Filter by **Needs you**, **Running**, or **All** (skipped runs stay hidden unless toggled on), open child runs from their parent, and answer questions, resume paused runs, or cancel active runs (requires permission to operate threads). The issues and pull requests a run touched show as chips under its title and on the steps that touched them; a chip opens the item beside the run, in a tab next to any agent transcripts you opened. + +### Agent threads + +Each `agent` step runs in an ordinary thread, left out of thread lists (including `t3 thread list`). Open it from the run to watch it live, read its transcript, or send follow-up messages; the thread links back to the run. + +An `agent` step can launch a new thread with its own `workspace` (such as a worktree), `runtimeMode`, `interactionMode`, `title`, and typed `returns`, or continue an earlier step's thread. Runs can set their display name with `title(text)`. An `agent` step can also target a project on a [linked environment](remote-access.md#link-another-environment) (requires **Settings → Labs → Linked environments**); the run itself stays on the server that started it. + +### Failures, pause, and cancel + +A plain code step runs once unless it asks for retries. When a step fails, the run pauses there instead of losing earlier work: + +- **Code step failures** retry automatically after 5, 20, and 80 minutes by default, or immediately when you resume; only that step runs again. +- **Agent failures** — when an agent ran and gave up or timed out — pause and wait for you to resume rather than retrying automatically. An agent that could not be started at all, for example because its environment was offline, retries on its own like a failed step. + +Cancelling a run stops its active agent turns and cancels child runs it invoked. A cancelled run cannot be resumed. + +## Limits + +- Runs live on the server that started them and only advance while it is running; use an always-on machine for schedules or webhooks you cannot miss. +- Keep older workflow versions defined until their unfinished runs end or are cancelled. +- Signals sent to a `channel` before a run waits on it are kept for 7 days by default. diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index d20a890bf90da..0ff07506e941d 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -47,6 +47,10 @@ "types": "./src/contractLabels.ts", "default": "./src/contractLabels.ts" }, + "./workflows": { + "types": "./src/workflows.ts", + "default": "./src/workflows.ts" + }, "./locales": { "types": "./src/locales.ts", "default": "./src/locales.ts" diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index 0947b1c046085..d86da6082dc29 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -71,6 +71,8 @@ export type EnvironmentSubscriptionRpcTag = | typeof WS_METHODS.subscribeServerConfig | typeof WS_METHODS.subscribeServerLifecycle | typeof WS_METHODS.scheduledTasksSubscribe + | typeof WS_METHODS.workflowsSubscribe + | typeof WS_METHODS.workflowsCounts | typeof WS_METHODS.serverGetStorageCleanupReport | typeof WS_METHODS.serverGetDatabaseStorage | typeof WS_METHODS.subscribeTerminalMetadata diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index 18dee4bd56b41..a3b1861ca0351 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -11,6 +11,7 @@ import { AuthAccessWriteScope, AuthEnvironmentMaintainScope, AuthOrchestrationOperateScope, + AuthTerminalOperateScope, AuthOrchestrationReadScope, AuthPreviewOperateScope, AuthProvidersManageScope, @@ -224,21 +225,43 @@ describe("command permissions", () => { ), ); - it.effect.each([WS_METHODS.scheduledTasksDelete, ORCHESTRATION_V2_WS_METHODS.stopWorkflow])( - "uses the target grant for both availability and execution of %s", - (method) => - Effect.gen(function* () { - const registry = yield* setup; - const permissions = createCommandPermissions(runtime, method); - registry.set(sessions(env), AsyncResult.success(grant(true))); - expect(registry.get(permissions.permissionAtom(env))).toBe(true); - expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env)); - yield* permissions.authorize(registry, env); - registry.set(sessions(other), AsyncResult.success(grant(false))); - expect(registry.get(permissions.permissionAtom(other))).toBe(false); - const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip); - expect(denied._tag).toBe("EnvironmentAuthorizationError"); - }), + it.effect.each([ + WS_METHODS.scheduledTasksDelete, + ORCHESTRATION_V2_WS_METHODS.stopWorkflow, + WS_METHODS.workflowsAnswer, + WS_METHODS.workflowsResume, + WS_METHODS.workflowsCancel, + ])("uses the target grant for both availability and execution of %s", (method) => + Effect.gen(function* () { + const registry = yield* setup; + const permissions = createCommandPermissions(runtime, method); + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(permissions.permissionAtom(env))).toBe(true); + expect(permissions.permissionAtom(env)).toBe(permissions.permissionAtom(env)); + yield* permissions.authorize(registry, env); + registry.set(sessions(other), AsyncResult.success(grant(false))); + expect(registry.get(permissions.permissionAtom(other))).toBe(false); + const denied = yield* permissions.authorize(registry, other).pipe(Effect.flip); + expect(denied._tag).toBe("EnvironmentAuthorizationError"); + }), + ); + it.effect("saving workflow definitions takes more than operating threads", () => + Effect.gen(function* () { + const registry = yield* setup; + const saving = createCommandPermissions(runtime, WS_METHODS.workflowsSaveDefinition); + // The server runs that file, so the grant that answers a question does not cover it. + registry.set(sessions(env), AsyncResult.success(grant(true))); + expect(registry.get(saving.permissionAtom(env))).toBe(false); + registry.set( + sessions(env), + AsyncResult.success({ + ...grant(true), + scopes: [AuthTerminalOperateScope], + permissions: [AuthTerminalOperateScope], + }), + ); + expect(registry.get(saving.permissionAtom(env))).toBe(true); + }), ); it.effect("waits for an initial grant", () => Effect.gen(function* () { diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 4401f90e898c3..4b708662839b2 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -162,6 +162,8 @@ export interface EnvironmentThreadShell { readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null; /** The thread in a linked environment that delegated this one, if one did. */ readonly delegatedFrom: OrchestrationV2ThreadShell["delegatedFrom"] | null; + /** The workflow run this thread is an agent step of, if it is one. */ + readonly workflowRun: OrchestrationV2ThreadShell["workflowRun"] | null; readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"]; readonly latestRun: ThreadRunSummary | null; readonly runtime: ThreadRuntimeSummary | null; @@ -314,6 +316,7 @@ export function presentThreadShell( forkedFrom: thread.forkedFrom, linkOrigin: thread.linkOrigin ?? null, delegatedFrom: thread.delegatedFrom ?? null, + workflowRun: thread.workflowRun ?? null, activeProviderThreadId: thread.activeProviderThreadId, latestRun, runtime, diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 6545f377cc632..61bcd4bcac53a 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -53,6 +53,7 @@ import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import { safeErrorLogAttributes } from "../errors/safeLog.ts"; import * as Persistence from "../platform/persistence.ts"; import { runCachePersistence } from "./cachePersistence.ts"; +import { workflowRunRefreshKey } from "../workflows.ts"; import { currentSession, isRpcClientError, @@ -1461,6 +1462,36 @@ export function createServerEnvironmentAtoms( ), ); }); + const workflowsLive = createEnvironmentRpcSubscriptionAtomFamily(runtime, { + label: "environment-data:server:workflows:live", + tag: WS_METHODS.workflowsSubscribe, + }); + const liveWorkflowSnapshot = (environmentId: EnvironmentId) => { + const live = workflowsLive({ environmentId, input: {} }); + return (get: Atom.AtomContext) => Option.getOrUndefined(AsyncResult.value(get(live))); + }; + // Keyed by a JSON array of environment ids, like the compaction notice, to read them as one. + const workflowsLiveAcross = Atom.family((environmentIdsKey: string) => { + const sources = (JSON.parse(environmentIdsKey) as EnvironmentId[]).map((environmentId) => ({ + environmentId, + atom: workflowsLive({ environmentId, input: {} }), + })); + return Atom.make((get) => + sources.map(({ environmentId, atom }) => ({ environmentId, result: get(atom) })), + ).pipe(Atom.withLabel(`environment-data:server:workflows:live-across:${environmentIdsKey}`)); + }); + // One change of a run or file at a time per target, so a double click does not act twice. + const workflowRunConcurrency = { + mode: "singleFlight" as const, + key: ({ environmentId, input }: { environmentId: EnvironmentId; input: { runId: string } }) => + JSON.stringify([environmentId, input.runId]), + }; + const workflowDefinitionScheduler = createAtomCommandScheduler(); + const workflowDefinitionConcurrency = { + mode: "serial" as const, + key: ({ environmentId, input }: { environmentId: EnvironmentId; input: { name: string } }) => + JSON.stringify([environmentId, input.name]), + }; const welcome = (target: { readonly environmentId: EnvironmentId; readonly input: EnvironmentRpcInput; @@ -1607,6 +1638,26 @@ export function createServerEnvironmentAtoms( label: "environment-data:server:scheduled-task:webhook-delivery", tag: WS_METHODS.scheduledTasksGetWebhookDelivery, }), + workflowsLive, + workflowsLiveAcross, + workflowRun: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:server:workflows:run", + tag: WS_METHODS.workflowsGet, + refreshTrigger: ({ environmentId, input }) => { + const snapshot = liveWorkflowSnapshot(environmentId); + return Atom.make((get) => workflowRunRefreshKey(snapshot(get), input.runId)); + }, + isFinal: (detail) => detail.run.endedAt !== null, + }), + // Read again whenever the server loads the files or finds them wrong, which `revision` says. + workflowDefinition: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:server:workflows:definition", + tag: WS_METHODS.workflowsGetDefinition, + refreshTrigger: ({ environmentId }) => { + const snapshot = liveWorkflowSnapshot(environmentId); + return Atom.make((get) => snapshot(get)?.definition?.revision); + }, + }), scheduledTasksLive: createEnvironmentRpcSubscriptionAtomFamily(runtime, { label: "environment-data:server:scheduled-tasks:live", tag: WS_METHODS.scheduledTasksSubscribe, @@ -1904,6 +1955,37 @@ export function createServerEnvironmentAtoms( scheduler: configScheduler, concurrency: configConcurrency, }), + answerWorkflowQuestion: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:workflows:answer", + tag: WS_METHODS.workflowsAnswer, + concurrency: { + mode: "singleFlight", + key: ({ environmentId, input }) => JSON.stringify([environmentId, input.runId, input.name]), + }, + }), + resumeWorkflowRun: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:workflows:resume", + tag: WS_METHODS.workflowsResume, + concurrency: workflowRunConcurrency, + }), + cancelWorkflowRun: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:workflows:cancel", + tag: WS_METHODS.workflowsCancel, + concurrency: workflowRunConcurrency, + }), + // Saves and deletes of one file go one after another: each carries its own text. + saveWorkflowDefinition: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:workflows:save-definition", + tag: WS_METHODS.workflowsSaveDefinition, + scheduler: workflowDefinitionScheduler, + concurrency: workflowDefinitionConcurrency, + }), + deleteWorkflowDefinition: createEnvironmentRpcCommand(runtime, { + label: "environment-data:server:workflows:delete-definition", + tag: WS_METHODS.workflowsDeleteDefinition, + scheduler: workflowDefinitionScheduler, + concurrency: workflowDefinitionConcurrency, + }), createGuestShare: createEnvironmentRpcCommand(runtime, { label: "environment-data:server:guest-share:create", tag: WS_METHODS.guestShareCreate, diff --git a/packages/client-runtime/src/workflows.test.ts b/packages/client-runtime/src/workflows.test.ts new file mode 100644 index 0000000000000..9fce777fd5642 --- /dev/null +++ b/packages/client-runtime/src/workflows.test.ts @@ -0,0 +1,521 @@ +import type { + WorkflowQuestion, + WorkflowRun, + WorkflowRunReference, + WorkflowStep, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + allWorkflowRunNodes, + buildWorkflowFeed, + buildWorkflowTimeline, + defaultWorkflowListTab, + defaultWorkflowRunId, + groupWorkflowRuns, + listedWorkflowRuns, + readWorkflowQuestion, + workflowAgentSummary, + workflowAnswer, + workflowChip, + workflowFlowFocus, + workflowPausedBeat, + workflowResultLines, + workflowRunInvolves, + workflowRunLists, + workflowRunNow, + workflowRunRefreshKey, + workflowReferenceIssue, + workflowReferenceLabel, + workflowReferencePullRequest, + workflowRunState, + workflowSaidStart, + workflowStepReferences, + workflowStepTime, + workflowOneLine, + workflowTriggerLine, +} from "./workflows.ts"; + +const two = (value: number) => String(value).padStart(2, "0"); +const at = (minute: number, second = 0) => `2026-11-01T00:${two(minute)}:${two(second)}.000Z`; + +const run = (runId: string, fields: Partial = {}): WorkflowRun => ({ + runId, + workflow: "release", + version: 1, + title: runId, + status: "running", + detail: null, + result: null, + pauses: 0, + retired: false, + resumesAt: null, + parentRunId: null, + parentStep: null, + startedAt: at(0), + updatedAt: at(0), + endedAt: null, + ...fields, +}); +const step = ( + name: string, + kind: WorkflowStep["kind"], + from: string, + to: string | null, + fields: Partial = {}, +): WorkflowStep => ({ + name, + kind, + status: to === null ? "running" : "completed", + attempts: 1, + detail: null, + threadId: null, + environmentId: null, + result: null, + said: null, + startedAt: from, + endedAt: to, + ...fields, +}); +const question = (runId: string, request: unknown = { title: "Ship?" }): WorkflowQuestion => ({ + runId, + name: "approve", + request: request as never, + askedAt: at(1), + thread: null, +}); + +describe("groupWorkflowRuns", () => { + const registered = [ + { name: "release", version: 1, triggers: ["webhook tags"] }, + { name: "check", version: 1, triggers: [] }, + { name: "report", version: 2, triggers: ["daily at 09:00"] }, + ]; + + it("puts what waits on a person first, then each workflow with its own runs", () => { + const groups = groupWorkflowRuns( + registered, + [ + run("done", { status: "completed", endedAt: at(9) }), + run("busy"), + run("parent", { status: "waiting", detail: "check" }), + // The child is what is paused, so its parent is the entry that needs someone. + run("child", { + workflow: "check", + status: "paused", + parentRunId: "parent", + parentStep: "check", + }), + run("asks", { workflow: "old", status: "waiting", detail: "approve" }), + run("orphan", { workflow: "old", status: "completed", endedAt: at(8), parentRunId: "x" }), + ], + [question("asks")], + ); + expect(groups.needsYou.map((node) => node.run.runId)).toEqual(["parent", "asks"]); + expect(groups.needsYou[0]?.children.map((node) => node.run.runId)).toEqual(["child"]); + expect( + groups.workflows.map((section) => [ + section.name, + workflowTriggerLine(section), + [...section.active, ...section.finished].map((node) => node.run.runId), + ]), + ).toEqual([ + // What is under way comes first, then what has run, then what only exists. + ["release", "Starts on webhook tags", ["busy", "done"]], + ["old", "No longer registered on this server", ["orphan"]], + ["check", "Runs as part of other workflows", []], + ["report", "Starts on daily at 09:00", []], + ]); + expect(allWorkflowRunNodes(groups).map((node) => node.run.runId)).toEqual([ + "parent", + "child", + "asks", + "busy", + "done", + "orphan", + ]); + // Opening the page lands on the first thing to act on, not on its untroubled parent. + expect(defaultWorkflowRunId(groups)).toBe("child"); + }); + + it("opens a run that is under way when nothing waits on anyone, else the newest", () => { + const quiet = groupWorkflowRuns( + registered, + [run("old", { endedAt: at(2), updatedAt: at(2) }), run("live", { workflow: "report" })], + [], + ); + expect(defaultWorkflowRunId(quiet)).toBe("live"); + const over = groupWorkflowRuns( + registered, + [ + run("first", { endedAt: at(2), updatedAt: at(2) }), + run("last", { workflow: "report", endedAt: at(5), updatedAt: at(5) }), + ], + [], + ); + expect(defaultWorkflowRunId(over)).toBe("last"); + expect(defaultWorkflowRunId(groupWorkflowRuns(registered, [], []))).toBeNull(); + }); +}); + +describe("the list of runs", () => { + const only = (fields: Partial, questions: ReadonlyArray = []) => + allWorkflowRunNodes(groupWorkflowRuns([], [run("a", fields)], questions))[0]!; + + it("gives a run the word the thread list would, and says what it is at", () => { + const told = (fields: Partial, questions?: ReadonlyArray) => { + const node = only(fields, questions); + return `${workflowRunState(node).word}: ${workflowRunNow(node)}`; + }; + expect(told({ status: "waiting", detail: "agent review" })).toBe("Working: review is working"); + expect(told({ status: "waiting", detail: "sleep night" })).toBe("Sleeping: Sleeping at night"); + expect(told({ status: "waiting", detail: "ci" })).toBe("Waiting: Waiting for ci"); + expect(told({ status: "waiting", detail: "approve" }, [question("a")])).toBe( + "Needs you: Asks: Ship?", + ); + expect(told({ status: "paused", detail: "build: exit 1\n at build.ts" })).toBe( + "Paused: build: exit 1", + ); + expect(told({ status: "completed", endedAt: at(1), result: { merged: "ba6ac73" } })).toBe( + "Done: merged: ba6ac73", + ); + expect(told({ status: "cancelled", endedAt: at(1), detail: "superseded" })).toBe( + "Cancelled: superseded", + ); + }); + + it("says of a run that waits on one it invoked what that one waits on", () => { + const groups = groupWorkflowRuns( + [], + [ + run("child", { parentRunId: "parent", status: "waiting", title: "Check web" }), + run("parent", { status: "waiting", detail: "check" }), + ], + [question("child")], + ); + const parent = allWorkflowRunNodes(groups)[0]!; + expect(workflowRunState(parent).word).toBe("Needs you"); + expect(workflowRunNow(parent)).toBe("Check web: Asks: Ship?"); + }); + + it("sorts runs into what waits on a person, what is under way, and everything", () => { + const groups = groupWorkflowRuns( + [], + [ + run("old", { status: "completed", endedAt: at(1), updatedAt: at(1) }), + run("busy", { updatedAt: at(2) }), + run("stuck", { status: "paused", updatedAt: at(3) }), + run("new", { status: "completed", endedAt: at(4), updatedAt: at(4) }), + ], + [], + ); + const lists = workflowRunLists(groups); + const ids = (nodes: ReadonlyArray<{ readonly run: WorkflowRun }>) => + nodes.map((node) => node.run.runId); + expect(ids(lists["needs-you"])).toEqual(["stuck"]); + expect(ids(lists.running)).toEqual(["busy"]); + expect(ids(lists.all)).toEqual(["stuck", "busy", "new", "old"]); + expect(defaultWorkflowListTab(groups)).toBe("needs-you"); + expect(defaultWorkflowListTab(groupWorkflowRuns([], [run("busy")], []))).toBe("running"); + expect( + defaultWorkflowListTab( + groupWorkflowRuns([], [run("old", { status: "completed", endedAt: at(1) })], []), + ), + ).toBe("all"); + const invoked = workflowRunLists( + groupWorkflowRuns( + [], + [run("parent"), run("child", { workflow: "check", parentRunId: "parent" }), run("other")], + [], + ), + ).all; + expect(ids(invoked.filter((node) => workflowRunInvolves(node, "check")))).toEqual(["parent"]); + }); + + it("leaves out what a workflow skipped, but not a skipped step of another run", () => { + const runs = [ + run("ignored", { status: "skipped", endedAt: at(1) }), + run("parent"), + run("child", { status: "skipped", endedAt: at(1), parentRunId: "parent" }), + ]; + expect(listedWorkflowRuns(runs, false)).toEqual({ runs: [runs[1], runs[2]], skipped: 1 }); + expect(listedWorkflowRuns(runs, true)).toEqual({ runs, skipped: 1 }); + }); + + it("marks a workflow with the same letters and colour every time", () => { + expect(workflowChip("nightly-report").letters).toBe("NR"); + expect(workflowChip("issue").letters).toBe("IS"); + expect(workflowChip("issue")).toEqual(workflowChip("issue")); + }); +}); + +describe("workflowRunRefreshKey", () => { + it("reads an ended run again only when it changes, and one under way on any change", () => { + const snapshot = (runs: ReadonlyArray) => ({ workflows: [], runs, questions: [] }); + const ended = run("old", { endedAt: at(5), updatedAt: at(5) }); + const before = snapshot([ended, run("busy", { updatedAt: at(6) })]); + const after = snapshot([ended, run("busy", { updatedAt: at(7) })]); + expect(workflowRunRefreshKey(before, "old")).toBe(workflowRunRefreshKey(after, "old")); + expect(workflowRunRefreshKey(before, "busy")).not.toBe(workflowRunRefreshKey(after, "busy")); + }); +}); + +describe("workflowAgentSummary", () => { + it("tells an agent's words apart from the facts of its result", () => { + expect(workflowAgentSummary({ result: "Fixed in one line.", said: null })).toEqual({ + said: "Fixed in one line.", + facts: [], + }); + expect( + workflowAgentSummary({ + said: "Reproduced on main.", + result: { kind: "bug", reproduced: true, surfaces: ["web", "desktop"], prUrl: null }, + }), + ).toEqual({ + said: "Reproduced on main.", + facts: [ + { label: "kind", value: "bug" }, + { label: "reproduced", value: "yes" }, + { label: "surfaces", value: "web, desktop" }, + ], + }); + }); + + it("lets the longest prose of a result speak when no closing words were kept", () => { + const summary = + "The draft is stored per thread id, and a reload before the thread exists drops it for good."; + expect(workflowAgentSummary({ said: null, result: { verdict: "merge", summary } })).toEqual({ + said: summary, + facts: [{ label: "verdict", value: "merge" }], + }); + }); +}); + +describe("workflowSaidStart", () => { + it("cuts a long reply where a paragraph ends", () => { + const said = + "It is a real bug.\n\n**Where:** line 5.\n\n**Reproduced:** yes, with 3660 seconds."; + expect(workflowSaidStart(said, 200)).toBeNull(); + expect(workflowSaidStart(said, 40)).toBe("It is a real bug.\n\n**Where:** line 5."); + expect(workflowSaidStart(said, 10)).toBe("It is a real bug."); + }); +}); + +describe("buildWorkflowTimeline", () => { + it("keeps the beats of a run and folds the bookkeeping between them", () => { + const parent = run("r", { startedAt: at(0), endedAt: at(10) }); + const child = run("c", { parentRunId: "r", parentStep: "check", title: "Check web" }); + const timeline = buildWorkflowTimeline({ + run: parent, + children: [child], + nowMs: Date.parse(at(10)), + steps: [ + step("load", "step", at(0), at(0)), + step("switch", "step", at(0), at(0)), + step("triage", "agent", at(0), at(3), { threadId: "t1" }), + // Two reviews at once. + step("review-a", "agent", at(3), at(5)), + step("review-b", "agent", at(3), at(6)), + step("record", "step", at(6), at(6)), + step("check/start", "step", at(6), at(6)), + step("check", "wait", at(6), at(8)), + step("build", "step", at(8), at(9)), + step("publish", "step", at(9), at(9), { status: "failed", detail: "503" }), + ], + }); + expect( + timeline.rows.map((row) => + row.kind === "quick" + ? `quick:${row.steps.map((quick) => quick.name).join(",")}` + : `${row.kind}:${row.name}${row.parallel ? ":parallel" : ""}`, + ), + ).toEqual([ + "quick:load,switch", + "agent:triage", + "agent:review-a:parallel", + "agent:review-b:parallel", + "quick:record", + // The step that started the invoked run is told by the wait for it. + "run:check", + // A plain step that took a minute is a beat; so is one that failed in no time. + "step:build", + "step:publish", + ]); + const invoked = timeline.rows.find((row) => row.kind === "run"); + expect(invoked?.kind === "run" ? invoked.childRun?.title : null).toBe("Check web"); + // Read as a feed, the two reviews are one row, and the path has a stop per row that matters. + const feed = buildWorkflowFeed(timeline); + expect( + feed.map((row) => + row.kind === "together" + ? row.beats.map((beat) => beat.name).join("+") + : row.kind === "quick" + ? "quick" + : row.name, + ), + ).toEqual(["quick", "triage", "review-a+review-b", "quick", "check", "build", "publish"]); + // The flow opens where the run needs someone, then where it failed, then on how it ended. + const focus = (status: WorkflowRun["status"], questions: ReadonlyArray = []) => + workflowFlowFocus({ rows: feed, status, ended: status === "completed", questions }); + expect(focus("waiting", ["approve"])).toBe("question:approve"); + expect(focus("paused")).toBe("step:publish"); + expect(focus("completed")).toBe("end"); + expect(focus("running")).toBe("step:publish"); + expect(workflowPausedBeat(feed, "paused")?.name).toBe("publish"); + // A failure the workflow caught, with the run going on after it, is not where it paused. + const caught = buildWorkflowFeed( + buildWorkflowTimeline({ + run: run("r", { startedAt: at(0) }), + children: [], + nowMs: Date.parse(at(10)), + steps: [ + step("lint", "agent", at(0), at(2), { status: "failed", detail: "timed out" }), + step("build", "agent", at(2), at(4)), + ], + }), + ); + expect(workflowPausedBeat(caught, "paused")).toBeNull(); + expect(workflowFlowFocus({ rows: caught, status: "paused", ended: false, questions: [] })).toBe( + "pause", + ); + }); + + it("measures a step that is under way up to now", () => { + const timeline = buildWorkflowTimeline({ + run: run("r", { startedAt: at(0) }), + children: [], + nowMs: Date.parse(at(4)), + steps: [step("fix", "agent", at(1), null)], + }); + const [fix] = timeline.rows; + expect(fix?.kind === "agent" ? [fix.endMs - fix.startMs, timeline.endMs] : null).toEqual([ + 180_000, + Date.parse(at(4)), + ]); + // Six started at once and a clock a minute behind: still one row, and no time runs backwards. + const wide = buildWorkflowTimeline({ + run: run("r", { startedAt: at(1) }), + children: [], + nowMs: Date.parse(at(0)), + steps: [ + step("a", "sleep", at(1), at(2)), + ...["b", "c", "d", "e", "f"].map((name) => step(name, "sleep", at(1), null)), + ], + }); + expect( + buildWorkflowFeed(wide).map((row) => (row.kind === "together" ? row.beats.length : 1)), + ).toEqual([6]); + expect(wide.rows.every((row) => row.endMs >= row.startMs)).toBe(true); + }); +}); + +describe("workflowResultLines", () => { + it("reads a result as a sentence or as its fields", () => { + expect(workflowResultLines("merged as ba6ac7")).toEqual([ + { label: null, value: "merged as ba6ac7" }, + ]); + expect(workflowResultLines({ sent: true, to: "everyone" })).toEqual([ + { label: "sent", value: "true" }, + { label: "to", value: "everyone" }, + ]); + expect(workflowResultLines(null)).toEqual([]); + }); +}); + +describe("readWorkflowQuestion", () => { + it("reads the title, the choices and the body, and drops parts of another shape", () => { + expect( + readWorkflowQuestion( + question("r", { title: "Ship it?", choices: ["yes", 2], data: { body: "Diff is small." } }), + ), + ).toEqual({ title: "Ship it?", choices: ["yes"], body: "Diff is small." }); + expect(readWorkflowQuestion(question("r", null))).toEqual({ + title: "approve", + choices: [], + body: null, + }); + }); +}); + +describe("workflowAnswer", () => { + it("reads a person's answer off a question's result", () => { + expect(workflowAnswer({ choice: "Ship", reason: " " })).toEqual({ + choice: "Ship", + reason: null, + }); + expect(workflowAnswer({ choice: "Hold", reason: "Too risky" })).toEqual({ + choice: "Hold", + reason: "Too risky", + }); + expect(workflowAnswer("done")).toBeNull(); + expect(workflowAnswer(null)).toBeNull(); + }); +}); + +describe("workflow references", () => { + const reference = (fields: Partial): WorkflowRunReference => ({ + kind: "issue", + key: "k", + address: {}, + title: "", + url: null, + state: null, + steps: [], + origin: "step", + ...fields, + }); + const issue = (key: string) => + reference({ + key, + address: { projectId: "p1", tracker: "github", scope: "me/app", key }, + steps: ["triage"], + }); + const pullRequest = reference({ + kind: "pullRequest", + key: "pr", + address: { projectId: "p1", host: "github.com", repository: "me/app", number: 418 }, + steps: ["fix", "checks"], + }); + const machine = reference({ kind: "machine", address: { id: 1 }, title: "box-1" }); + + it("names each by what its kind calls it, and a kind it does not know by its title", () => { + expect( + [issue("412"), issue("ENG-12"), pullRequest, machine].map(workflowReferenceLabel), + ).toEqual(["#412", "ENG-12", "#418", "box-1"]); + expect(workflowReferenceLabel(reference({ kind: "machine" }))).toBe("machine"); + }); + + it("opens an issue or pull request only when its address reads as one", () => { + expect(workflowReferencePullRequest(pullRequest)?.number).toBe(418); + expect(workflowReferenceIssue(pullRequest)).toBeNull(); + expect(workflowReferenceIssue(reference({ address: { key: 1 } }))).toBeNull(); + expect(workflowReferenceIssue(machine)).toBeNull(); + }); + + it("gives a step the things it touched", () => { + const all = [issue("412"), pullRequest, machine]; + expect(workflowStepReferences(all, "checks")).toEqual([pullRequest]); + expect(workflowStepReferences(all, "merge")).toEqual([]); + }); +}); + +describe("workflowStepTime", () => { + it("keeps one shape down the column", () => { + expect(workflowStepTime(9)).toBe("0.1s"); + expect(workflowStepTime(342)).toBe("0.3s"); + expect(workflowStepTime(9_700)).toBe("9.7s"); + expect(workflowStepTime(4_000)).toBe("4s"); + expect(workflowStepTime(12_400)).toBe("12s"); + }); +}); + +describe("workflowOneLine", () => { + it("reads a reply's first sentence as plain words", () => { + expect(workflowOneLine("## Done\n\nI added `clamp` next to **sum**. Tests pass.")).toBe( + "I added clamp next to sum.", + ); + expect(workflowOneLine("- See [the issue](https://x.test/2) first")).toBe( + "See the issue first", + ); + }); +}); diff --git a/packages/client-runtime/src/workflows.ts b/packages/client-runtime/src/workflows.ts new file mode 100644 index 0000000000000..3808f94703237 --- /dev/null +++ b/packages/client-runtime/src/workflows.ts @@ -0,0 +1,770 @@ +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; +import { + type IssueRef, + type PullRequestRef, + WorkflowIssueAddress, + WorkflowPullRequestAddress, + WorkflowReferenceKind, + type WorkflowQuestion, + type WorkflowRun, + type WorkflowRunReference, + type WorkflowRunsSnapshot, + type WorkflowStep, + type WorkflowSummary, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { formatDuration } from "@t3tools/shared/orchestrationTiming"; + +export interface WorkflowQuestionView { + readonly title: string; + readonly choices: ReadonlyArray; + readonly body: string | null; +} + +function field(value: unknown, key: string): unknown { + return typeof value === "object" && value !== null && !Array.isArray(value) + ? (value as Readonly>)[key] + : undefined; +} + +/** + * What a question shows. `request` is whatever the workflow handed `ask`, so a part that is + * missing or of another shape is left out instead of failing the whole list. + */ +export function readWorkflowQuestion(question: WorkflowQuestion): WorkflowQuestionView { + const title = field(question.request, "title"); + const choices = field(question.request, "choices"); + const body = field(field(question.request, "data"), "body"); + return { + title: typeof title === "string" && title.trim() !== "" ? title : question.name, + choices: Array.isArray(choices) + ? choices.filter((choice): choice is string => typeof choice === "string") + : [], + body: typeof body === "string" && body.trim() !== "" ? body : null, + }; +} + +/** + * What a run's detail is read again on, out of the live list: the run's last change once it has + * ended. Steps do not move a run's `updatedAt`, so one under way is read again on any change. + */ +export function workflowRunRefreshKey( + snapshot: WorkflowRunsSnapshot | undefined, + runId: string, +): unknown { + const run = snapshot?.runs.find((candidate) => candidate.runId === runId); + return run === undefined || run.endedAt === null ? snapshot : run.updatedAt; +} + +export interface WorkflowRunNode { + readonly run: WorkflowRun; + /** The runs it invoked, in the order they started. */ + readonly children: ReadonlyArray; + /** Questions open on this run. */ + readonly questions: ReadonlyArray; +} + +/** One workflow and the runs of it that nobody has to act on. */ +export interface WorkflowSection { + readonly name: string; + /** What starts it, in words. Null for a workflow this server no longer has registered. */ + readonly triggers: ReadonlyArray | null; + readonly active: ReadonlyArray; + readonly finished: ReadonlyArray; + /** It has runs, and every one was invoked by a run of another workflow. */ + readonly invokedOnly: boolean; + /** It has never run here, as far as the list goes back. */ + readonly neverRan: boolean; +} + +export interface WorkflowRunGroups { + /** Runs a person has to act on: one has a question open or is paused, itself or below it. */ + readonly needsYou: ReadonlyArray; + /** Every workflow there is, busiest first, each with its other runs. */ + readonly workflows: ReadonlyArray; +} + +const needsPerson = (node: WorkflowRunNode): boolean => + node.questions.length > 0 || node.run.status === "paused" || node.children.some(needsPerson); + +/** + * The list a person reads: what waits on them first, then each workflow with its runs. A run + * that another invoked sits under that one, so a piece of work is one entry, and a workflow that + * has not run yet is still listed, since the list is also how one learns what exists. `runs` is + * newest first and that order is kept. + */ +/** + * The runs a list shows: without those a workflow skipped as not its to do, unless asked for + * them. A skipped run that another run invoked stays, as a step of that one. + */ +export function listedWorkflowRuns( + runs: ReadonlyArray, + showSkipped: boolean, +): { readonly runs: ReadonlyArray; readonly skipped: number } { + const hidden = (run: WorkflowRun) => run.status === "skipped" && run.parentRunId === null; + const skipped = runs.filter(hidden).length; + return { runs: showSkipped ? runs : runs.filter((run) => !hidden(run)), skipped }; +} + +export function groupWorkflowRuns( + workflows: ReadonlyArray, + runs: ReadonlyArray, + questions: ReadonlyArray, +): WorkflowRunGroups { + const listed = new Set(runs.map((run) => run.runId)); + const childrenOf = new Map(); + const roots: WorkflowRun[] = []; + for (const run of runs) { + if (run.parentRunId === null || !listed.has(run.parentRunId)) { + roots.push(run); + continue; + } + const siblings = childrenOf.get(run.parentRunId); + if (siblings) siblings.push(run); + else childrenOf.set(run.parentRunId, [run]); + } + const node = (run: WorkflowRun): WorkflowRunNode => ({ + run, + questions: questions.filter((question) => question.runId === run.runId), + children: (childrenOf.get(run.runId) ?? []) + .slice() + .sort((left, right) => left.startedAt.localeCompare(right.startedAt)) + .map(node), + }); + const needsYou: WorkflowRunNode[] = []; + const sections = new Map(); + const sectionOf = (name: string) => { + const known = sections.get(name); + if (known) return known; + const made = { active: [], finished: [] }; + sections.set(name, made); + return made; + }; + for (const root of roots.map(node)) { + if (needsPerson(root)) needsYou.push(root); + else if (root.run.endedAt === null) sectionOf(root.run.workflow).active.push(root); + else sectionOf(root.run.workflow).finished.push(root); + } + const registered = new Map(workflows.map((workflow) => [workflow.name, workflow] as const)); + const hasRuns = new Set(runs.map((run) => run.workflow)); + const hasRootRuns = new Set(roots.map((run) => run.workflow)); + const names = [...new Set([...sections.keys(), ...registered.keys(), ...hasRuns])]; + const rank = (name: string) => { + const section = sections.get(name); + if (section !== undefined && section.active.length > 0) return 0; + return section !== undefined && section.finished.length > 0 ? 1 : 2; + }; + return { + needsYou, + workflows: names + .map((name) => ({ + name, + triggers: registered.get(name)?.triggers ?? null, + active: sections.get(name)?.active ?? [], + finished: sections.get(name)?.finished ?? [], + invokedOnly: hasRuns.has(name) && !hasRootRuns.has(name), + neverRan: !hasRuns.has(name), + })) + .slice() + .sort( + (left, right) => rank(left.name) - rank(right.name) || left.name.localeCompare(right.name), + ), + }; +} + +/** Every run of these, parents before the runs they invoked. */ +function flattenWorkflowRunNodes( + nodes: ReadonlyArray, +): ReadonlyArray { + return nodes.flatMap((node) => [node, ...flattenWorkflowRunNodes(node.children)]); +} + +/** Every run in the list, in the order it is listed. */ +export function allWorkflowRunNodes(groups: WorkflowRunGroups): ReadonlyArray { + return flattenWorkflowRunNodes([ + ...groups.needsYou, + ...groups.workflows.flatMap((section) => [...section.active, ...section.finished]), + ]); +} + +/** The run to show when none was picked: the first that waits on a person, else one under way. */ +export function defaultWorkflowRunId(groups: WorkflowRunGroups): string | null { + const waiting = flattenWorkflowRunNodes(groups.needsYou).find( + (node) => node.questions.length > 0 || node.run.status === "paused", + ); + const rest = groups.workflows; + return ( + waiting?.run.runId ?? + rest.find((section) => section.active.length > 0)?.active[0]?.run.runId ?? + rest + .flatMap((section) => section.finished) + .slice() + .sort((left, right) => right.run.updatedAt.localeCompare(left.run.updatedAt))[0]?.run.runId ?? + null + ); +} + +/** What starts a workflow, in words. */ +export function workflowTriggerLine( + section: WorkflowSection, + resolve: MFunctionType = mFallback, +): string { + if (section.triggers === null) return resolve(msg("No longer registered on this server")); + if (section.invokedOnly) return resolve(msg("Runs as part of other workflows")); + return section.triggers.length === 0 + ? resolve(msg("Started by hand")) + : resolve(msg("Starts on {triggers}", { triggers: section.triggers.join(", ") })); +} + +export type WorkflowListTab = "needs-you" | "running" | "all"; + +/** + * The three lists a person switches between. Each is whole pieces of work, newest change first: a + * run that another invoked is reached through that one. + */ +export function workflowRunLists( + groups: WorkflowRunGroups, +): Readonly>> { + const byChange = (nodes: ReadonlyArray) => + [...nodes].sort((left, right) => right.run.updatedAt.localeCompare(left.run.updatedAt)); + const running = groups.workflows.flatMap((section) => section.active); + const finished = groups.workflows.flatMap((section) => section.finished); + return { + "needs-you": byChange(groups.needsYou), + running: byChange(running), + all: [...byChange(groups.needsYou), ...byChange(running), ...byChange(finished)], + }; +} + +/** Whether a run is of this workflow or invoked one, so a workflow that only runs inside others is found. */ +export function workflowRunInvolves(node: WorkflowRunNode, workflow: string): boolean { + return ( + node.run.workflow === workflow || + node.children.some((child) => workflowRunInvolves(child, workflow)) + ); +} + +/** The list to open on: what waits on a person, else what is under way, else everything. */ +export function defaultWorkflowListTab(groups: WorkflowRunGroups): WorkflowListTab { + if (groups.needsYou.length > 0) return "needs-you"; + return groups.workflows.some((section) => section.active.length > 0) ? "running" : "all"; +} + +const CHIP_TONES = 5; + +/** A workflow's mark in the list: two letters and one of a few colours, the same every time. */ +export function workflowChip(name: string): { readonly letters: string; readonly tone: number } { + const parts = name.split(/[^\p{L}\p{N}]+/u).filter((part) => part !== ""); + const letters = + parts.length > 1 ? `${parts[0]![0]}${parts[1]![0]}` : (parts[0] ?? name).slice(0, 2); + let hash = 0; + for (const char of name) hash = (hash * 31 + char.codePointAt(0)!) % 9973; + return { letters: letters.toUpperCase(), tone: hash % CHIP_TONES }; +} + +export type WorkflowRunTone = "input" | "failed" | "working" | "quiet" | "done"; + +/** A run's state as the one word the thread list would use for it. */ +export function workflowRunState( + node: WorkflowRunNode, + resolve: MFunctionType = mFallback, +): { + readonly word: string; + readonly tone: WorkflowRunTone; +} { + const { run } = node; + const input = { + word: resolve(msg("Needs you", { $context: "workflow run status: it waits on a person" })), + tone: "input", + } as const; + const working = { + word: resolve(msg("Working", { $context: "workflow run status" })), + tone: "working", + } as const; + if (node.questions.length > 0) return input; + switch (run.status) { + case "paused": + return { + word: resolve(msg("Paused", { $context: "workflow run status" })), + tone: "failed", + }; + case "running": + return working; + case "waiting": { + const detail = run.detail ?? ""; + if (detail.startsWith("agent ")) return working; + if (detail.startsWith("sleep ")) { + return { + word: resolve(msg("Sleeping", { $context: "workflow run status" })), + tone: "quiet", + }; + } + // Something below it holds it up; say that, not that it idles. + if (node.children.some(needsPerson)) return input; + return { word: resolve(msg("Waiting", { $context: "workflow run status" })), tone: "quiet" }; + } + case "completed": + return { word: resolve(msg("Done", { $context: "workflow run status" })), tone: "done" }; + case "stopped": + return { word: resolve(msg("Stopped", { $context: "workflow run status" })), tone: "quiet" }; + case "skipped": + return { word: resolve(msg("Skipped", { $context: "workflow run status" })), tone: "quiet" }; + case "cancelled": + return { + word: resolve(msg("Cancelled", { $context: "workflow run status" })), + tone: "quiet", + }; + } +} + +const firstLine = (text: string) => text.trim().split("\n", 1)[0]!.trim(); + +/** What a run is at right now, as the line under its title. */ +export function workflowRunNow(node: WorkflowRunNode, resolve: MFunctionType = mFallback): string { + const { run } = node; + const detail = run.detail?.trim() ?? ""; + const asked = node.questions[0]; + if (asked !== undefined) { + const more = node.questions.length - 1; + const question = readWorkflowQuestion(asked).title; + return more > 0 + ? resolve(msg("Asks: {question} and {more} more", { question, more })) + : resolve(msg("Asks: {question}", { question })); + } + const below = flattenWorkflowRunNodes(node.children); + const holding = below.find( + (child) => child.questions.length > 0 || child.run.status === "paused", + ); + switch (run.status) { + case "paused": + return detail === "" ? resolve(msg("A step failed")) : firstLine(detail); + case "running": + return resolve(msg("Running its own steps")); + case "waiting": + if (holding !== undefined) { + return `${holding.run.title}: ${workflowRunNow(holding, resolve)}`; + } + if (detail.startsWith("agent ")) { + return resolve(msg("{step} is working", { step: detail.slice(6) })); + } + if (detail.startsWith("sleep ")) { + return resolve(msg("Sleeping at {step}", { step: detail.slice(6) })); + } + if (below.some((child) => child.run.endedAt === null)) { + const open = below.filter((child) => child.run.endedAt === null); + return open.length === 1 + ? resolve(msg("Runs {run}", { run: open[0]!.run.title })) + : resolve(msg("{count} runs under way", { count: open.length })); + } + return detail === "" + ? resolve(msg("Waiting", { $context: "what a workflow run is doing now" })) + : resolve(msg("Waiting for {step}", { step: detail })); + case "completed": { + const line = workflowResultLines(run.result)[0]; + if (line === undefined) { + return resolve(msg("Finished", { $context: "what a workflow run is doing now" })); + } + return firstLine(line.label === null ? line.value : `${line.label}: ${line.value}`); + } + case "stopped": + case "skipped": + case "cancelled": + return detail === "" ? resolve(msg("Ended early")) : firstLine(detail); + } +} + +/** A run's result as lines a person can read: a sentence, or the fields of an object. */ +export function workflowResultLines( + result: WorkflowRun["result"], +): ReadonlyArray<{ readonly label: string | null; readonly value: string }> { + if (result === null) return []; + if (typeof result !== "object") return [{ label: null, value: String(result) }]; + if (Array.isArray(result)) return [{ label: null, value: JSON.stringify(result) }]; + return Object.entries(result).map(([label, value]) => ({ + label, + value: typeof value === "string" ? value : JSON.stringify(value), + })); +} + +// A step this short is bookkeeping between the parts of a run that take time. +const QUICK_STEP_MS = 1_000; + +export interface WorkflowBeat { + readonly kind: WorkflowStep["kind"] | "run"; + readonly name: string; + readonly status: WorkflowStep["status"]; + readonly attempts: number; + /** A failure's reason, or when a sleep wakes. */ + readonly detail: string | null; + /** What it produced: a value, an agent's data or reply, the answer to a question. */ + readonly result: WorkflowStep["result"]; + /** What an agent said in closing, when its result is data. */ + readonly said: string | null; + readonly startMs: number; + /** When it ended, or `nowMs` while it is under way. */ + readonly endMs: number; + readonly thread: { readonly threadId: string; readonly environmentId: string | null } | null; + /** The run this step invoked and waited for. */ + readonly childRun: WorkflowRun | null; + /** Another beat was under way at the same time. */ + readonly parallel: boolean; +} + +export interface WorkflowQuickSteps { + readonly kind: "quick"; + readonly steps: ReadonlyArray; + readonly startMs: number; + readonly endMs: number; +} + +export type WorkflowTimelineRow = WorkflowBeat | WorkflowQuickSteps; + +export interface WorkflowTimeline { + readonly rows: ReadonlyArray; + readonly startMs: number; + readonly endMs: number; +} + +/** + * A run's steps as the story of the run: what took time or involved someone is a beat, and the + * quick steps between two beats fold into one row, since a journal of them hides where the run + * is. An invoked run takes the place of the two steps that started and awaited it. + */ +export function buildWorkflowTimeline(input: { + readonly run: Pick; + readonly steps: ReadonlyArray; + readonly children: ReadonlyArray; + readonly nowMs: number; +}): WorkflowTimeline { + const childByStep = new Map( + input.children + .filter((child) => child.parentRunId === input.run.runId && child.parentStep !== null) + .map((child) => [child.parentStep, child] as const), + ); + const startMs = Date.parse(input.run.startedAt); + // A caller's clock can be a minute old. Now is never before anything the run has done. + const nowMs = Math.max( + input.nowMs, + startMs, + ...input.steps.map((step) => Date.parse(step.endedAt ?? step.startedAt)), + ); + const endMs = input.run.endedAt === null ? nowMs : Date.parse(input.run.endedAt); + const rows: WorkflowTimelineRow[] = []; + const beats: WorkflowBeat[] = []; + let quick: WorkflowStep[] = []; + const flush = () => { + if (quick.length === 0) return; + rows.push({ + kind: "quick", + steps: quick, + startMs: Date.parse(quick[0]!.startedAt), + endMs: Date.parse(quick.at(-1)!.endedAt ?? quick.at(-1)!.startedAt), + }); + quick = []; + }; + for (const step of input.steps) { + // The step that started an invoked run is told by the wait that follows it. + if (step.kind === "step" && step.name.endsWith("/start")) { + if (childByStep.has(step.name.slice(0, -"/start".length))) continue; + } + const stepStart = Date.parse(step.startedAt); + const stepEnd = step.endedAt === null ? nowMs : Date.parse(step.endedAt); + const childRun = step.kind === "wait" ? (childByStep.get(step.name) ?? null) : null; + const isBeat = + step.kind !== "step" || + step.status !== "completed" || + step.attempts > 1 || + stepEnd - stepStart >= QUICK_STEP_MS; + if (!isBeat) { + quick.push(step); + continue; + } + flush(); + const beat: WorkflowBeat = { + kind: childRun === null ? step.kind : "run", + name: step.name, + status: step.status, + attempts: step.attempts, + detail: step.detail, + result: step.result, + said: step.said, + startMs: stepStart, + endMs: Math.max(stepStart, stepEnd), + thread: + step.threadId === null + ? null + : { threadId: step.threadId, environmentId: step.environmentId }, + childRun, + parallel: false, + }; + beats.push(beat); + rows.push(beat); + } + flush(); + const overlaps = (left: WorkflowBeat, right: WorkflowBeat) => + left !== right && left.startMs < openEnd(right) && right.startMs < openEnd(left); + return { + rows: rows.map((row) => + row.kind === "quick" + ? row + : { ...row, parallel: beats.some((other) => overlaps(row, other)) }, + ), + startMs, + endMs: Math.max(endMs, ...beats.map((beat) => beat.endMs), startMs + 1), + }; +} + +/** When a beat stops overlapping what starts after it: one still under way never does. */ +const openEnd = (beat: WorkflowBeat) => + beat.status === "running" ? Number.POSITIVE_INFINITY : beat.endMs; + +/** What a person answered a question with, when a step's result is such an answer. */ +export function workflowAnswer( + result: WorkflowStep["result"], +): { readonly choice: string; readonly reason: string | null } | null { + const choice = field(result, "choice"); + const reason = field(result, "reason"); + return typeof choice === "string" + ? { choice, reason: typeof reason === "string" && reason.trim() !== "" ? reason : null } + : null; +} + +/** Steps that were under way at the same time, shown side by side. */ +export interface WorkflowTogether { + readonly kind: "together"; + readonly beats: ReadonlyArray; +} + +export type WorkflowFeedRow = WorkflowTimelineRow | WorkflowTogether; + +/** + * The timeline as it is read: beats that overlapped become one row, so two reviewers at once look + * like two reviewers at once and not like one after the other. + */ +export function buildWorkflowFeed(timeline: WorkflowTimeline): ReadonlyArray { + const rows: WorkflowFeedRow[] = []; + let together: WorkflowBeat[] = []; + let until = 0; + const flush = () => { + if (together.length === 1) rows.push(together[0]!); + else if (together.length > 1) rows.push({ kind: "together", beats: together }); + together = []; + }; + for (const row of timeline.rows) { + if (row.kind === "quick") { + flush(); + rows.push(row); + continue; + } + if (together.length > 0 && row.parallel && row.startMs < until) { + together.push(row); + until = Math.max(until, openEnd(row)); + continue; + } + flush(); + together = [row]; + until = openEnd(row); + } + flush(); + return rows; +} + +/** The steps of a feed that take a place in the run's flow: every beat, in order. */ +const beatsOf = (rows: ReadonlyArray) => + rows.flatMap((row) => (row.kind === "quick" ? [] : row.kind === "together" ? row.beats : [row])); + +/** + * The step a paused run stopped at: the last that failed, unless the run went on after it, since + * then the workflow caught that failure. Null when the run is not paused at a step. + */ +export function workflowPausedBeat( + rows: ReadonlyArray, + status: WorkflowRun["status"], +): WorkflowBeat | null { + if (status !== "paused") return null; + const failed = beatsOf(rows).findLast((beat) => beat.status === "failed"); + if (failed === undefined) return null; + const wentOn = rows.some((row) => + row.kind === "together" + ? row.beats.some((beat) => beat !== failed && beat.startMs >= failed.endMs) + : row !== failed && row.startMs >= failed.endMs, + ); + return wentOn ? null : failed; +} + +/** + * Which part of a run's flow to open on: what waits on a person, then where it failed, then how + * it ended, then what is under way. Keys are `step:`, `question:`, `pause` and `end`. + */ +export function workflowFlowFocus(input: { + readonly rows: ReadonlyArray; + readonly status: WorkflowRun["status"]; + readonly ended: boolean; + /** The names of the questions that wait on a person. */ + readonly questions: ReadonlyArray; +}): string | null { + const beats = beatsOf(input.rows); + const asked = input.questions[0]; + if (asked !== undefined) { + const at = beats.find( + (beat) => + beat.kind === "ask" && beat.status === "running" && input.questions.includes(beat.name), + ); + return at === undefined ? `question:${asked}` : `step:${at.name}`; + } + if (input.status === "paused") { + const failed = workflowPausedBeat(input.rows, input.status); + return failed === null ? "pause" : `step:${failed.name}`; + } + if (input.ended) return "end"; + const last = beats.findLast((beat) => beat.status === "running") ?? beats.at(-1); + return last === undefined ? null : `step:${last.name}`; +} + +const FACT_LENGTH = 48; +const FACTS_SHOWN = 6; +// A string this long is the agent talking, not a fact about its work. +const PROSE_LENGTH = 80; + +const words = (key: string) => + key + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .replace(/[_-]+/g, " ") + .toLowerCase(); + +function factValue(value: unknown): string | null { + if (typeof value === "boolean") return value ? "yes" : "no"; + if (typeof value === "number") return String(value); + if (typeof value === "string") { + const text = value.trim(); + return text !== "" && text.length <= FACT_LENGTH && !text.includes("\n") ? text : null; + } + if (Array.isArray(value) && value.length > 0 && value.length <= 4) { + const parts = value.map(factValue); + const joined = parts.join(", "); + return parts.every((part) => part !== null) && joined.length <= FACT_LENGTH ? joined : null; + } + return null; +} + +/** + * What an agent step has to say for itself: its words, and the short facts of its result. With no + * closing words kept, the longest piece of prose in the result stands in for them. + */ +export function workflowAgentSummary(beat: Pick): { + readonly said: string | null; + readonly facts: ReadonlyArray<{ readonly label: string; readonly value: string }>; +} { + const { result } = beat; + const kept = beat.said?.trim() ?? ""; + if (typeof result === "string") { + return { said: kept !== "" ? kept : result.trim() === "" ? null : result.trim(), facts: [] }; + } + if (result === null || typeof result !== "object" || Array.isArray(result)) { + return { said: kept === "" ? null : kept, facts: [] }; + } + const entries = Object.entries(result); + const prose = + kept !== "" + ? null + : (entries + .filter( + (entry): entry is [string, string] => + typeof entry[1] === "string" && entry[1].trim().length >= PROSE_LENGTH, + ) + .slice() + .sort((left, right) => right[1].length - left[1].length)[0] ?? null); + return { + said: kept !== "" ? kept : (prose?.[1].trim() ?? null), + facts: entries + .flatMap(([key, value]) => { + const text = factValue(value); + return text === null ? [] : [{ label: words(key), value: text }]; + }) + .slice(0, FACTS_SHOWN), + }; +} + +/** + * The start of what an agent said, cut where a paragraph ends so no markup is left half open. + * Null when all of it fits. + */ +export function workflowSaidStart(said: string, limit: number): string | null { + if (said.length <= limit) return null; + const paragraphs = said.split(/\n{2,}/); + let kept = paragraphs[0]!; + for (const paragraph of paragraphs.slice(1)) { + if (kept.length + paragraph.length + 2 > limit) break; + kept = `${kept}\n\n${paragraph}`; + } + // One paragraph that runs on is cut at a word, which can still split markup but not a word. + if (kept.length > limit * 2) kept = `${kept.slice(0, kept.lastIndexOf(" ", limit))}…`; + return kept === said ? null : kept; +} + +const decodeIssueAddress = Schema.decodeUnknownOption(WorkflowIssueAddress); +const decodePullRequestAddress = Schema.decodeUnknownOption(WorkflowPullRequestAddress); + +/** A reference's issue, when it is one and its address reads as one. */ +export function workflowReferenceIssue(reference: WorkflowRunReference): IssueRef | null { + return reference.kind === WorkflowReferenceKind.issue + ? Option.getOrNull(decodeIssueAddress(reference.address)) + : null; +} + +/** A reference's pull request, when it is one and its address reads as one. */ +export function workflowReferencePullRequest( + reference: WorkflowRunReference, +): PullRequestRef | null { + return reference.kind === WorkflowReferenceKind.pullRequest + ? Option.getOrNull(decodePullRequestAddress(reference.address)) + : null; +} + +/** + * What a reference is called in a chip: `#412` for an issue or pull request on a git host, a + * tracker's own key such as `ENG-12`, and the title for a kind this client does not know. + */ +export function workflowReferenceLabel(reference: WorkflowRunReference): string { + const pullRequest = workflowReferencePullRequest(reference); + if (pullRequest !== null) return `#${pullRequest.number}`; + const issue = workflowReferenceIssue(reference); + if (issue !== null) return /^\d+$/.test(issue.key) ? `#${issue.key}` : issue.key; + return reference.title === "" ? reference.kind : reference.title; +} + +/** The references a step touched, in the order the run first touched them. */ +export function workflowStepReferences( + references: ReadonlyArray, + step: string, +): ReadonlyArray { + return references.filter((reference) => reference.steps.includes(step)); +} + +/** A step's time in one shape down a column: 0.3s, 9.7s, 12s, then minutes. */ +export function workflowStepTime(ms: number): string { + if (ms < 10_000 && ms % 1000 !== 0) return `${(Math.max(ms, 100) / 1000).toFixed(1)}s`; + if (ms < 60_000) return `${Math.round(ms / 1000)}s`; + return formatDuration(ms); +} + +/** + * The first sentence of a reply, as one line of plain text: a heading, list mark, inline code, + * emphasis or link reads as its words. + */ +export function workflowOneLine(text: string): string { + const line = + text + .split("\n") + .map((candidate) => candidate.trim()) + .find((candidate) => candidate !== "" && !/^(#|```|\|)/.test(candidate)) + ?.replace(/^([-*>]|\d+\.)\s+/, "") ?? ""; + const plain = line + .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/`([^`]*)`/g, "$1") + .replace(/(\*\*|__|\*|_)(\S(?:.*?\S)?)\1/g, "$2"); + const end = plain.search(/[.!?](\s|$)/); + return end === -1 ? plain : plain.slice(0, end + 1); +} From f29c824614c424327ea50abcf945f734db8c130f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 18:07:10 -0800 Subject: [PATCH 142/162] fix(server): Full access Codex no longer asks before dangerous commands (#40773) --- .../Adapters/CodexAdapterV2.test.ts | 90 +++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 13 +++ docs/user/permission-modes.md | 4 + 3 files changed, 107 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index d30748a0df77c..330524c99ad3b 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -2010,6 +2010,96 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect.each([ + { name: "dangerous command", networkApprovalContext: undefined, asks: false }, + { + name: "managed-network command", + networkApprovalContext: { host: "example.com", protocol: "https" }, + asks: true, + }, + ] as const)("full access asks about a $name: $asks", ({ networkApprovalContext, asks }) => + Effect.gen(function* () { + const nativeThreadId = "command-approval-thread"; + const nativeTurnId = "command-approval-turn"; + const prompt = "Clean node_modules."; + const pending = yield* Queue.unbounded(); + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "full-access-command-approval", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }), + { + type: "emit_inbound", + frame: { + id: 0, + method: "item/commandExecution/requestApproval", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + itemId: "exec-rm", + command: "/bin/bash -lc 'rm -rf ./node_modules'", + startedAtMs: 0, + ...(networkApprovalContext === undefined ? {} : { networkApprovalContext }), + }, + }, + }, + ...(asks + ? [] + : ([ + { type: "expect_outbound", frame: { id: 0, result: { decision: "accept" } } }, + { + type: "emit_inbound", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ] as const)), + ], + }), + (event) => + event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending" + ? Queue.offer(pending, event.runtimeRequest) + : Effect.void, + ); + const turnInput = makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("command-approval-attempt"), + text: prompt, + }); + yield* harness.runtime.startTurn({ + ...turnInput, + runtimePolicy: { ...turnInput.runtimePolicy, runtimeMode: "full-access" }, + }); + const request = yield* Effect.raceFirst( + harness.firstTerminal.pipe(Effect.as(undefined)), + Queue.take(pending), + ); + assert.equal(request?.kind, asks ? "command" : undefined); + if (!asks) { + assert.deepEqual( + harness.terminalEvents().map((event) => event.status), + ["completed"], + ); + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect.each(["native", "ordinary"] as const)( "resumes Codex without a prompt only for an existing conversation (%s)", (mode) => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 49c153f30be09..1c38aaebffc80 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -6062,6 +6062,19 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload, ); } + // T3's Full access policy is granular, under which Codex still asks before commands it + // deems dangerous. Managed-network asks enforce the user's allowlist, so they still ask. + if ( + context.input.runtimePolicy.runtimeMode === "full-access" && + context.input.runtimePolicy.approvalPolicy === undefined && + context.input.runtimePolicy.sandboxPolicy === undefined && + payload.networkApprovalContext == null && + (payload.proposedNetworkPolicyAmendments ?? []).length === 0 + ) { + return { + decision: "accept", + } satisfies CodexSchema.CommandExecutionRequestApprovalResponse; + } const allowance = sessionAllowance(payload.threadId, context); if (allowance.has("command")) { return { diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md index a8f1cf8391221..60c403e31979b 100644 --- a/docs/user/permission-modes.md +++ b/docs/user/permission-modes.md @@ -48,6 +48,10 @@ session-wide choice, because Grok would remember that command for the whole proj ACP Registry agents run their own tools in their own mode; T3 Code answers their approval requests by the permission mode. See [ACP Registry permissions](./providers-acp.md#permissions-and-terminals). +In **Full access**, commands that Codex's dangerous-command check would ask about run without +asking. Codex still asks before network access its managed network settings don't allow, unless +you already allowed commands for the session. + Claude can still ask in **Full access** when its settings disable bypass permissions or require approval for an action. Dangerous-removal safety checks in bypass mode reject the command with the original warning. Claude can use a safe rewrite when the warning supplies one; otherwise it From 2808e878de91aacc7fb82887f18414976be7ae34 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 22 Nov 2026 20:16:09 -0600 Subject: [PATCH 143/162] fix(usage): skipped-record warnings only count the selected dates (#41157) Co-authored-by: Cursor Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../src/provider/Drivers/codexUsage.test.ts | 48 +++++----- .../server/src/provider/Drivers/codexUsage.ts | 21 +++-- apps/server/src/usage/UsageService.test.ts | 94 ++++++++++++++++++- apps/server/src/usage/UsageService.ts | 39 +++++--- apps/server/src/usage/usageAggregation.ts | 16 ++++ apps/server/src/usage/usageScanCache.test.ts | 38 +++++--- apps/server/src/usage/usageScanCache.ts | 30 ++++-- .../src/usage/usageTranscriptReader.test.ts | 20 ++-- .../server/src/usage/usageTranscriptReader.ts | 6 +- packages/provider-core/src/server/usage.ts | 4 +- 10 files changed, 239 insertions(+), 77 deletions(-) diff --git a/apps/server/src/provider/Drivers/codexUsage.test.ts b/apps/server/src/provider/Drivers/codexUsage.test.ts index 1cdbe05d07669..2326b6749f4a6 100644 --- a/apps/server/src/provider/Drivers/codexUsage.test.ts +++ b/apps/server/src/provider/Drivers/codexUsage.test.ts @@ -98,7 +98,7 @@ describe("parseCodexLine", () => { parseCodexLine(line.replace("2026-08-01T05:17:49.919Z", "invalid"), cumulativeState), ).toBeNull(); expect(parseCodexLine(line, cumulativeState)?.totals.outputTokens).toBe(20); - expect(codexUsageFormat.readMalformedRecords?.(cumulativeState)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(cumulativeState).length).toBe(0); }); it("ignores stale changed requests but counts equal requests when totals advance across contexts", () => { @@ -141,7 +141,7 @@ describe("parseCodexLine", () => { totals: { uncachedInputTokens: 100, outputTokens: 20 }, }); } - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); it.each([false, true])( @@ -160,7 +160,7 @@ describe("parseCodexLine", () => { expect( parseCodexLine(counted(counters(10, 2), counters(130, 27)), state)?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }, ); @@ -187,10 +187,10 @@ describe("parseCodexLine", () => { total[field] += 1; if (field === "input_tokens" || field === "output_tokens") total.total_tokens += 1; expect(parseCodexLine(counted(request, total), state), field).toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length, field).toBe(1); for (const key of fields) total[key] += request[key]; expect(parseCodexLine(counted(request, total), state)?.totals.outputTokens, field).toBe(20); - expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length, field).toBe(1); } }); @@ -250,7 +250,7 @@ describe("parseCodexLine", () => { state, )?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }, ); @@ -307,7 +307,7 @@ describe("parseCodexLine", () => { reasoning_output_tokens: 5, }; expect(parseCodexLine(counted(request, cumulative), state)).toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(1); expect(state.lastCumulativeUsage).toEqual(cumulative); }); @@ -327,14 +327,14 @@ describe("parseCodexLine", () => { state, ), ).toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(1); expect( parseCodexLine( counted(request, malformed === "request" ? counters(300, 60) : counters(200, 40)), state, )?.totals.outputTokens, ).toBe(20); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(1); }); it("bills only the reported request when usage records sit between reconciling snapshots", () => { @@ -520,7 +520,7 @@ describe("parseCodexLine", () => { parseCodexLine(counted(counters(10, 2), { ...counters(10, 2), total_tokens: 1012 }), state) ?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); it.each([false, true])( @@ -536,7 +536,7 @@ describe("parseCodexLine", () => { expect( parseCodexLine(counted(counters(30, 5), counters(30, 5)), state)?.totals.outputTokens, ).toBe(5); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }, ); @@ -550,7 +550,7 @@ describe("parseCodexLine", () => { expect( parseCodexLine(counted(counters(10, 2), counters(40, 7)), state)?.totals.outputTokens, ).toBe(2); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); const later = (line: string) => line.replace("05:17:49.919Z", "07:17:49.919Z"); @@ -583,7 +583,10 @@ describe("parseCodexLine", () => { return record === null ? 0 : totalTokens(record.totals); }); - expect({ processed: billed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + expect({ + processed: billed, + skipped: codexUsageFormat.readMalformedRecords?.(state).length, + }).toEqual({ processed, skipped, }); @@ -675,7 +678,10 @@ describe("parseCodexLine", () => { return record === null ? 0 : totalTokens(record.totals); }); - expect({ processed: billed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + expect({ + processed: billed, + skipped: codexUsageFormat.readMalformedRecords?.(state).length, + }).toEqual({ processed, skipped, }); @@ -697,7 +703,7 @@ describe("parseCodexLine", () => { expect({ processed, - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [120, 120, 0, 120], skipped: 0 }); }); @@ -715,7 +721,7 @@ describe("parseCodexLine", () => { const record = parseCodexLine(line, state); return record === null ? 0 : totalTokens(record.totals); }); - expect({ processed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + expect({ processed, skipped: codexUsageFormat.readMalformedRecords?.(state).length }).toEqual({ processed: [120, 120, 120, 35], skipped: 0, }); @@ -756,7 +762,7 @@ describe("parseCodexLine", () => { expect({ processed: billed, - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed, skipped: 0 }); }, ); @@ -777,7 +783,7 @@ describe("parseCodexLine", () => { expect({ processed, - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [120, 0, 120, 35], skipped: 1 }); }); @@ -917,7 +923,7 @@ describe("parseCodexLine", () => { state, ); expect(next).not.toBeNull(); - expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + expect(codexUsageFormat.readMalformedRecords?.(state).length).toBe(0); }); it("recognizes subagent spawns without forked_from_id", () => { @@ -968,7 +974,7 @@ describe("parseCodexLine", () => { expect({ processed: [first, copied, afterBurst, next], - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [120, 0, 120, 35], skipped: 0 }); }); @@ -989,7 +995,7 @@ describe("parseCodexLine", () => { expect({ processed: billed.map((record) => totalTokens(record.totals)), - skipped: codexUsageFormat.readMalformedRecords?.(state), + skipped: codexUsageFormat.readMalformedRecords?.(state).length, }).toEqual({ processed: [160, 230], skipped: 0 }); }); }); diff --git a/apps/server/src/provider/Drivers/codexUsage.ts b/apps/server/src/provider/Drivers/codexUsage.ts index a2977d3080fee..7fafc555aac56 100644 --- a/apps/server/src/provider/Drivers/codexUsage.ts +++ b/apps/server/src/provider/Drivers/codexUsage.ts @@ -148,6 +148,9 @@ export const CodexScanState = Schema.Struct({ ), requestLedgerActive: Schema.mutableKey(Schema.optionalKey(Schema.Boolean)), malformedRecords: Schema.mutableKey(TokenCount), + malformedRecordTimestamps: Schema.mutableKey( + Schema.optionalKey(Schema.mutable(Schema.Array(Schema.Finite))), + ), sawSessionMeta: Schema.mutableKey(Schema.Boolean), modelProvider: Schema.mutableKey(Schema.String), turnId: Schema.mutableKey(Schema.String), @@ -331,7 +334,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag // A valid snapshot remains the next baseline even when its paired request is malformed. if (cumulative !== null) rebaseCodexUsage(state, cumulative, timestampMs); if (last === null || (hasCumulative && cumulative === null)) { - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } @@ -351,7 +354,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag } if (last.total_tokens !== last.input_tokens + last.output_tokens) { - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } @@ -397,12 +400,12 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag state.lastCumulativeUsage = previous; if (pending !== undefined) state.unreportedRequests = pending; } - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } unreported = bridged; } else if (!restarted && rewound) { - state.malformedRecords += discardedRequests(pending, last); + noteMalformedRecord(state, timestampMs, discardedRequests(pending, last)); } if (restarted) state.sequenceStartSignature = sequenceStart; } else { @@ -410,7 +413,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag // Advance expected totals for billed legacy requests so a cumulative re-emission is stale. const advanced = advanceCodexUsage(previous, last); if (advanced === null) { - state.malformedRecords += 1; + noteMalformedRecord(state, timestampMs); return []; } state.lastCumulativeUsage = advanced; @@ -424,6 +427,12 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag ]; } +function noteMalformedRecord(state: CodexScanState, timestampMs: number, count = 1) { + state.malformedRecords += count; + const timestamps = (state.malformedRecordTimestamps ??= []); + for (let index = 0; index < count; index++) timestamps.push(timestampMs); +} + function codexAttribution(state: CodexScanState, timestampMs: number): CodexRequestAttribution { return { timestampMs, @@ -509,7 +518,7 @@ export const codexUsageFormat: TranscriptUsageFormat = { parseLine: parseCodexLine, parseProjected: parseCodexRecord, state: { initial: initialCodexScanState, schema: CodexScanState }, - readMalformedRecords: (state) => state.malformedRecords, + readMalformedRecords: (state) => state.malformedRecordTimestamps ?? [], // A rollout that moved after it was read leaves a copy in both places. sharedSessionsAcrossFiles: true, }; diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 237f0740c7d19..d2bc0c296fbc1 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -3298,6 +3298,72 @@ describe("UsageService", () => { }), ); + it.effect("limits cached transcript work and diagnostics to the requested dates", () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const dir = NodePath.join(home, "codex", "sessions"); + const transcript = NodePath.join(dir, "rollout.jsonl"); + const line = (timestamp: string, input: number, total: number) => + JSON.stringify({ + type: "event_msg", + timestamp, + payload: { + type: "token_count", + info: { + last_token_usage: { input_tokens: input, output_tokens: 1 }, + total_token_usage: { input_tokens: total, output_tokens: total / 10 }, + }, + }, + }); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(dir, { recursive: true }); + await NodeFSP.writeFile( + transcript, + [ + JSON.stringify({ type: "turn_context", payload: { model: "gpt-6-astra" } }), + line("2026-08-01T10:00:00Z", 10, 10), + line("2026-08-01T11:00:00Z", 10, 40), + ].join("\n") + "\n", + ); + }); + yield* Effect.gen(function* () { + const first = yield* UsageService.make; + const source = (summary: UsageSummary) => + summary.sources.find((s) => s.fingerprint.provider === "codex")!; + assert.strictEqual(source(yield* first.readSummary(WINDOW)).malformedRecords, 1); + const hour = { + ...WINDOW, + resolution: "hour" as const, + sinceTime: "2026-08-01T10:00:00Z", + untilTime: "2026-08-01T11:00:00Z", + }; + assert.strictEqual(source(yield* first.readSummary(hour)).malformedRecords, 0); + + yield* first.awaitPersisted; + const restarted = yield* UsageService.make; + const nextDay = { + ...WINDOW, + sinceDay: UsageDay.make("2026-08-02"), + untilDay: UsageDay.make("2026-08-02"), + }; + const outside = source(yield* restarted.readSummary(nextDay)); + assert.strictEqual(outside.malformedRecords, 0); + assert.strictEqual(outside.scannedFiles, 0); + assert.strictEqual(outside.message, null); + yield* Effect.promise(() => + NodeFSP.appendFile(transcript, line("2026-08-02T10:00:00Z", 10, 10)), + ); + const mixed = yield* restarted.readSummary(nextDay); + assert.strictEqual(totalOutputTokens(mixed), 1); + assert.strictEqual(source(mixed).malformedRecords, 0); + yield* restarted.awaitPersisted; + const saved = yield* UsageService.make; + assert.strictEqual(source(yield* saved.readSummary(nextDay)).malformedRecords, 0); + assert.strictEqual(source(yield* saved.readSummary(WINDOW)).malformedRecords, 1); + }).pipe(Effect.provide(layerService({ prefix: "usage-window-diagnostics", home, settings }))); + }), + ); + it.effect( "merges partial Claude copies through tail replacement, newline completion and restart", () => @@ -3892,6 +3958,32 @@ describe("UsageService", () => { }), ); + it.effect("leaves a duplicate uncounted when its first copy is before the window", () => + Effect.gen(function* () { + const { transcript, settings, home } = yield* setup; + const dir = NodePath.dirname(transcript); + yield* Effect.promise(async () => { + await NodeFSP.writeFile(NodePath.join(dir, "a.jsonl"), ""); + await NodeFSP.writeFile(NodePath.join(dir, "b.jsonl"), ""); + const [first = "", second = ""] = (await NodeFSP.readdir(dir)).map((name) => + NodePath.join(dir, name), + ); + const nextDay = (line: string) => line.replace("2026-08-01", "2026-08-02"); + await NodeFSP.writeFile(first, claudeLine(1, 5)); + await NodeFSP.writeFile(second, nextDay(claudeLine(1, 5)) + nextDay(claudeLine(2, 7))); + }); + yield* Effect.gen(function* () { + const summary = yield* (yield* UsageService.make).readSummary({ + ...WINDOW, + sinceDay: UsageDay.make("2026-08-02"), + }); + assert.strictEqual(totalOutputTokens(summary), 7); + }).pipe( + Effect.provide(layerService({ prefix: "usage-service-early-copy-test", home, settings })), + ); + }), + ); + it.effect("credits the same copy of a duplicate from the last scan as an exact read does", () => Effect.gen(function* () { yield* TestClock.setTime(Date.parse("2026-08-15T00:00:00Z")); @@ -4002,7 +4094,7 @@ describe("UsageService", () => { provider: "claude" as const, records: [], tailRecords: [], - malformedRecords: 2, + malformedRecords: [mtimeMs, mtimeMs], position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }, ], diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 30edc903a580f..3ff2004266651 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -39,7 +39,12 @@ import type { TranscriptUsageFormat, UsageRecord, } from "@t3tools/provider-core/server/usage"; -import { canonicalModelFilter, resolveModelAliases, UsageAggregator } from "./usageAggregation.ts"; +import { + canonicalModelFilter, + resolveModelAliases, + usageTimestampFilter, + UsageAggregator, +} from "./usageAggregation.ts"; import { createOverrideRateTable, isUnlistedModel, @@ -419,7 +424,8 @@ export const make = Effect.gen(function* () { ([filePath, entry]) => entry.provider === provider && entry.mtimeMs >= retentionCutoffMs && - (entry.records.length + entry.tailRecords.length > 0 || entry.malformedRecords > 0) && + (entry.records.length + entry.tailRecords.length > 0 || + entry.malformedRecords.length > 0) && isWithinDirectory(filePath, dir), ); const volumeId = @@ -564,7 +570,7 @@ export const make = Effect.gen(function* () { format: TranscriptUsageFormat, ): Effect.fn.Return<{ readonly records: readonly UsageRecord[]; - readonly malformedRecords: number; + readonly malformedRecords: readonly number[]; readonly failed?: true; readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined }; }> { @@ -599,7 +605,7 @@ export const make = Effect.gen(function* () { if (parsed === null) return { records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [], - malformedRecords: cached?.provider === provider ? cached.malformedRecords : 0, + malformedRecords: cached?.provider === provider ? cached.malformedRecords : [], failed: true, }; @@ -687,7 +693,7 @@ export const make = Effect.gen(function* () { | readonly { readonly path: string; readonly records: readonly UsageRecord[]; - readonly malformedRecords: number; + readonly malformedRecords: readonly number[]; }[] | null; /** Every transcript path the walk listed, in walk order, whatever its mtime. */ @@ -800,7 +806,7 @@ export const make = Effect.gen(function* () { : Effect.succeed<[string, string | undefined]>([volumeId, undefined]), ([resolved, sourceId]): ScannedDir => ({ ...source, - files: source.files?.map((file) => ({ ...file, malformedRecords: 0 })) ?? null, + files: source.files?.map((file) => ({ ...file, malformedRecords: [] })) ?? null, provider: reader.provider, volumeId: resolved, ...(sourceId === undefined ? {} : { physicalSourceId: sourceId }), @@ -876,6 +882,11 @@ export const make = Effect.gen(function* () { ? 0 : Math.max(0, startedAtMs - settings.usageHistoryRetentionDays * 24 * 60 * 60 * 1000); + const inWindow = usageTimestampFilter({ ...input, ...hourlyWindow }); + const windowEndMs = + hourlyWindow?.untilTimeMs ?? + Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS; + const awaitRefresh = input.awaitRefresh === true; const collect = Effect.gen(function* () { const resolved = yield* resolveTranscriptDirs(settings, retentionCutoffMs, awaitRefresh).pipe( @@ -951,7 +962,16 @@ export const make = Effect.gen(function* () { malformedRecords: entry.malformedRecords, }); } - return retainedFiles; + return retainedFiles.flatMap((file) => { + // A keyed copy outside the window still claims its key, so a later copy is not counted. + const records = file.records.filter( + (record) => record.dedupeKey !== null || inWindow(record.timestampMs), + ); + const malformedRecords = file.malformedRecords.filter(inWindow); + return records.length === 0 && malformedRecords.length === 0 + ? [] + : [{ ...file, records, malformedRecords }]; + }); }); // Usage two transcripts share counts in the first one, so saved files take the order an exact // scan reads them in: walked files in walk order, then the directory's deleted files. @@ -1009,9 +1029,6 @@ export const make = Effect.gen(function* () { ...(input.modelFilter === undefined ? {} : { modelFilter: input.modelFilter }), }); - const windowEndMs = - hourlyWindow?.untilTimeMs ?? - Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS; let resolvedAny = false; for (const { reader } of transcriptReaders) { if (reader.resolveServiceTiers === undefined || fromMemory) continue; @@ -1077,7 +1094,7 @@ export const make = Effect.gen(function* () { let counted = false; for (const file of filesByDir[index] ?? []) { - malformedRecords += file.malformedRecords; + malformedRecords += file.malformedRecords.length; if (file.records.length === 0) { skippedFiles += 1; continue; diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index f4c39753548fd..9ba0a22fd7a32 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -77,6 +77,22 @@ export interface AggregateOptions { readonly untilTimeMs?: number; } +export function usageTimestampFilter( + options: Pick< + AggregateOptions, + "timeZone" | "sinceDay" | "untilDay" | "sinceTimeMs" | "untilTimeMs" + >, +) { + const toDay = makeDayFormatter(options.timeZone); + return (timestampMs: number) => { + if (options.sinceTimeMs !== undefined && options.untilTimeMs !== undefined) { + return timestampMs >= options.sinceTimeMs && timestampMs < options.untilTimeMs; + } + const day = toDay(timestampMs); + return day >= options.sinceDay && day <= options.untilDay; + }; +} + export function resolveModelAliases( aliases: Readonly>, ): ReadonlyMap { diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index 36864768eb525..6acc49e0657cf 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -52,7 +52,7 @@ function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][]) provider: "claude", records, tailRecords: [], - malformedRecords: 0, + malformedRecords: [], position: position(), }); } @@ -95,7 +95,7 @@ describe("scan cache round trip", () => { ]); original.set("/grok.jsonl", { size: 40, - malformedRecords: 2, + malformedRecords: [1, 2], mtimeMs: 300, provider: "grok", records: [ @@ -131,7 +131,7 @@ describe("scan cache round trip", () => { const pendingTail = { ...pending, unresolvedServiceTierTurnId: "native-tail" }; original.set("/codex.jsonl", { size: 80, - malformedRecords: 3, + malformedRecords: [1, 2, 3], mtimeMs: 400, provider: "codex", records: [ @@ -166,6 +166,16 @@ describe("scan cache round trip", () => { expect(restored.size).toBe(4); expect(restored).toEqual(original); + const encoded = parse(makeScanCacheWriter()(original, {})); + const { mt: _dates, ...undated } = encoded.files["/codex.jsonl"]!; + const reparsed = decodeScanCache( + { ...encoded, files: { ...encoded.files, "/codex.jsonl": undated } }, + TEST_FORMAT_MAP, + ).get("/codex.jsonl")!; + expect(reparsed.size).toBe(-1); + expect(reparsed.position.resumeOffset).toBe(0); + expect(reparsed.records).toEqual(original.get("/codex.jsonl")!.records); + expect(reparsed.malformedRecords).toEqual([]); }); it.each([5, 6, 7, 8, 10, 11, 12, 13])( @@ -175,7 +185,7 @@ describe("scan cache round trip", () => { original.set("/gone-codex.jsonl", { ...original.get("/gone.jsonl")!, provider: "codex", - malformedRecords: 1, + malformedRecords: [1], records: [record({ provider: "codex", speed: "fast", dedupeKey: null })], position: position({ state: { @@ -195,12 +205,12 @@ describe("scan cache round trip", () => { size: 256, provider: "pi", records: [record({ provider: "pi", model: "anthropic/claude-fable-5" })], - malformedRecords: 3, + malformedRecords: [1, 2, 3], position: position({ state: { sessionId: "session-a" } }), }); const cleanCodex = { ...original.get("/gone-codex.jsonl")!, - malformedRecords: 0, + malformedRecords: [], }; original.set("/clean-codex.jsonl", cleanCodex); const encoded = parse(makeScanCacheWriter()(original, {})); @@ -257,7 +267,7 @@ describe("scan cache round trip", () => { ); it("re-parses a v14 Codex entry that skipped records and restarts a clean one when it grows", () => { - const codex = (malformedRecords: number): CachedFile => ({ + const codex = (malformedRecords: readonly number[]): CachedFile => ({ size: 10, mtimeMs: 100, provider: "codex", @@ -269,20 +279,20 @@ describe("scan cache round trip", () => { }), }); const original: ScanCache = new Map([ - ["/skipped-codex.jsonl", codex(1)], - ["/clean-codex.jsonl", codex(0)], + ["/skipped-codex.jsonl", codex([1])], + ["/clean-codex.jsonl", codex([])], ]); const v14 = { ...parse(makeScanCacheWriter()(original, {})), version: 14 }; const restored = decodeScanCache(JSON.parse(JSON.stringify(v14)), TEST_FORMAT_MAP); expect(restored.get("/skipped-codex.jsonl")).toEqual({ - ...codex(1), + ...codex([1]), size: -1, position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }); // Served while unchanged, but its state predates the latest snapshot time, so it cannot resume. expect(restored.get("/clean-codex.jsonl")).toEqual({ - ...codex(0), + ...codex([]), position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }); // The migrated entries persist without a state and load again under the current version. @@ -306,7 +316,7 @@ describe("scan cache round trip", () => { provider: "codex", records: [record({ provider: "codex", model: "gpt-6-astra", dedupeKey: null })], tailRecords: [], - malformedRecords: 0, + malformedRecords: [], position: position({ state: { ...initialCodexScanState(), @@ -368,14 +378,14 @@ describe("scan cache round trip", () => { ["/a.jsonl", 100, [record()]], ["/b.jsonl", 200, [record({ sessionId: "session-b" })]], ]); - cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, malformedRecords: 2 }); + cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, malformedRecords: [1, 2] }); const sources = { "claude\u0000/projects": { dir: "/projects", volumeId: "1:2" } }; expect(decodeScanCache(parse(write(cache, { sources })), TEST_FORMAT_MAP)).toEqual(cache); cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, size: 30, - malformedRecords: 4, + malformedRecords: [1, 2, 3, 4], records: [record({ sessionId: "session-c", model: "claude-opus-5-5", dedupeKey: "msg_3:" })], }); const document = parse(write(cache, { sources })); diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index 843b414b97f32..cc6068b72f164 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -44,8 +44,8 @@ export interface CachedFile { readonly records: readonly UsageRecord[]; /** Unterminated tail records stay separate because incremental parsing rereads them. */ readonly tailRecords: readonly UsageRecord[]; - /** Whole-file count, including diagnostics from the tentative tail. */ - readonly malformedRecords: number; + /** Whole-file timestamps, including diagnostics from the tentative tail. */ + readonly malformedRecords: readonly number[]; readonly position: TranscriptParsePosition; } @@ -75,6 +75,7 @@ interface SerializedFile { readonly r: readonly SerializedRecord[]; readonly t: readonly SerializedRecord[]; readonly mr: number; + readonly mt?: readonly number[]; readonly o: number; readonly gl: number; readonly gh: number; @@ -136,7 +137,8 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile p: entry.provider, r: entry.records.map(serializeRecord), t: entry.tailRecords.map(serializeRecord), - mr: entry.malformedRecords, + mr: entry.malformedRecords.length, + ...(entry.malformedRecords.length === 0 ? {} : { mt: entry.malformedRecords }), o: entry.position.resumeOffset, gl: entry.position.guardLength, gh: entry.position.guardHash, @@ -288,8 +290,18 @@ export function decodeScanCache( const format = formats.get(entry.p); if (format === undefined) continue; if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue; - const malformedRecords = entry.mr === undefined ? 0 : entry.mr; - if (!Number.isSafeInteger(malformedRecords) || malformedRecords < 0) continue; + const malformedCount = entry.mr === undefined ? 0 : entry.mr; + if (!Number.isSafeInteger(malformedCount) || malformedCount < 0) continue; + const malformedRecords = entry.mt ?? (malformedCount === 0 ? [] : undefined); + if ( + malformedRecords !== undefined && + (!Array.isArray(malformedRecords) || + malformedRecords.length !== malformedCount || + !malformedRecords.every(Number.isFinite)) + ) + continue; + // A count saved without dates cannot be limited to a window, so the file re-parses whole. + const undated = malformedRecords === undefined; // Position fields feed byte offsets and a Buffer allocation in the reader, // so anything outside their real ranges must reject the entry: a bogus // guard length would otherwise fail every parse of the file, silently @@ -317,14 +329,14 @@ export function decodeScanCache( (entry.p === "grok" && version < 17) || (format.state !== undefined && (version < 6 || - (entry.p === "codex" && (version < 14 || (version < 15 && malformedRecords > 0))))); + (entry.p === "codex" && (version < 14 || (version < 15 && malformedCount > 0))))); // A corrupt state disqualifies the entry: resuming with it would attach // appended usage to the wrong model or replay fork-copied history. if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue; // Before v16 a Codex baseline can lack the time of its latest move, or carry an older one, // and that time keeps a re-emitted older snapshot from billing twice. A grown file re-parses // whole instead of resuming. - const resumable = !legacy && !(entry.p === "codex" && version < 16); + const resumable = !legacy && !undated && !(entry.p === "codex" && version < 16); const provider = entry.p; const records = decodeRecords(entry.r, provider); @@ -332,12 +344,12 @@ export function decodeScanCache( if (records === null || tailRecords === null) continue; cache.set(path, { - size: legacy ? -1 : entry.s, + size: legacy || undated ? -1 : entry.s, mtimeMs: entry.m, provider, records, tailRecords, - malformedRecords, + malformedRecords: malformedRecords ?? [], position: resumable ? { resumeOffset: entry.o, diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.ts index ca994dd3ac5b2..1896991a9b835 100644 --- a/apps/server/src/usage/usageTranscriptReader.test.ts +++ b/apps/server/src/usage/usageTranscriptReader.test.ts @@ -162,8 +162,8 @@ describe("compressed transcripts", () => { assert.strictEqual(expected.tailRecords.length, 1); assert.deepStrictEqual(actual.records, expected.records); assert.deepStrictEqual(actual.tailRecords, expected.tailRecords); - assert.strictEqual(expected.malformedRecords, 1); - assert.strictEqual(actual.malformedRecords, expected.malformedRecords); + assert.strictEqual(expected.malformedRecords.length, 1); + assert.deepStrictEqual(actual.malformedRecords, expected.malformedRecords); assert.strictEqual(actual.records[0]?.speed, "ultrafast"); assert.isFalse(actual.resumed); assert.strictEqual(actual.position.resumeOffset, 0); @@ -226,7 +226,7 @@ describe("readTranscriptRecords resume", () => { } return TEST_FORMATS.claude.parseProjected(value, undefined); }, - readMalformedRecords: (state: { errors: number }) => state.errors, + readMalformedRecords: (state: { errors: number }) => Array(state.errors).fill(0), }; const path = NodePath.join(dir, "diagnostics.jsonl"); const malformed = JSON.stringify({ usage: "malformed" }); @@ -243,7 +243,7 @@ describe("readTranscriptRecords resume", () => { assert.deepStrictEqual(first.tailRecords, []); assert.strictEqual(first.position.resumeOffset, Buffer.byteLength(committed)); assert.deepStrictEqual(first.position.state, { errors: 1 }); - assert.strictEqual(first.malformedRecords, 2); + assert.strictEqual(first.malformedRecords.length, 2); const savedPosition = JSON.parse(JSON.stringify(first.position)); await NodeFSP.appendFile(path, `\n${claudeLine(2, 7)}${malformed}\n`); @@ -255,14 +255,14 @@ describe("readTranscriptRecords resume", () => { [7], ); assert.deepStrictEqual(resumed.position.state, { errors: 3 }); - assert.strictEqual(resumed.malformedRecords, 3); + assert.strictEqual(resumed.malformedRecords.length, 3); const full = await readTranscriptRecords(path, format, undefined, options); assert.isNotNull(full); assert.deepStrictEqual([...first.records, ...resumed.records], full.records); assert.deepStrictEqual(resumed.tailRecords, full.tailRecords); assert.deepStrictEqual(resumed.position, full.position); - assert.strictEqual(resumed.malformedRecords, full.malformedRecords); + assert.deepStrictEqual(resumed.malformedRecords, full.malformedRecords); }); it("parses only appended lines when resuming a grown file", async () => { @@ -272,7 +272,7 @@ describe("readTranscriptRecords resume", () => { assert.isNotNull(first); assert.strictEqual(first.records.length, 2); assert.isFalse(first.resumed); - assert.strictEqual(first.malformedRecords, 0); + assert.deepStrictEqual(first.malformedRecords, []); await NodeFSP.appendFile(path, claudeLine(3, 11)); const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position); @@ -380,7 +380,7 @@ describe("readTranscriptRecords resume", () => { first.tailRecords.map((r) => [r.totals.outputTokens, r.speed]), [[20, "ultrafast"]], ); - assert.strictEqual(first.malformedRecords, 0); + assert.deepStrictEqual(first.malformedRecords, []); await NodeFSP.appendFile(path, `\n${firstLine}\n${event(usage(10, 2), usage(510, 62))}\n`); const resumed = await readTranscriptRecords( @@ -402,7 +402,7 @@ describe("readTranscriptRecords resume", () => { ], ); assert.deepStrictEqual(resumed.tailRecords, []); - assert.strictEqual(resumed.malformedRecords, 0); + assert.deepStrictEqual(resumed.malformedRecords, []); assert.deepStrictEqual(resumed.position, full.position); }, ); @@ -476,7 +476,7 @@ describe("readTranscriptRecords resume", () => { { billedTokens: requests.reduce((sum, tokens) => sum + tokens, 0), requests, - malformedRecords: result.malformedRecords, + malformedRecords: result.malformedRecords.length, }, { billedTokens: 510, requests: [120, 160, 230], malformedRecords: 0 }, ); diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts index 43597513e5240..263f6701a47c0 100644 --- a/apps/server/src/usage/usageTranscriptReader.ts +++ b/apps/server/src/usage/usageTranscriptReader.ts @@ -36,8 +36,8 @@ export interface TranscriptParseResult { readonly records: readonly UsageRecord[]; /** Unterminated tail records stay outside records/position so the next scan rereads them. */ readonly tailRecords: readonly UsageRecord[]; - /** Includes tentative tail diagnostics; position.state only includes committed lines. */ - readonly malformedRecords: number; + /** Timestamps, including tentative tail diagnostics; position.state only includes committed lines. */ + readonly malformedRecords: readonly number[]; readonly position: TranscriptParsePosition; readonly resumed: boolean; } @@ -464,7 +464,7 @@ export async function readTranscriptRecords( return { records, tailRecords, - malformedRecords: format.readMalformedRecords?.(tailState) ?? 0, + malformedRecords: format.readMalformedRecords?.(tailState) ?? [], position: { resumeOffset: compressed ? 0 : resumeOffset, guardLength, diff --git a/packages/provider-core/src/server/usage.ts b/packages/provider-core/src/server/usage.ts index ff4c14dfefe00..260f160421f33 100644 --- a/packages/provider-core/src/server/usage.ts +++ b/packages/provider-core/src/server/usage.ts @@ -62,8 +62,8 @@ export interface TranscriptUsageFormat { readonly usageMarkers: readonly [string, ...string[]]; parseLine(line: string, state: State): readonly UsageRecord[]; parseProjected(projected: unknown, state: State): readonly UsageRecord[]; - /** Cumulative malformed or inconsistent usage records, including skipped records. */ - readMalformedRecords?(state: State): number; + /** Timestamps of malformed or inconsistent usage records, including skipped records. */ + readMalformedRecords?(state: State): readonly number[]; /** * Present for formats whose records depend on earlier lines. The state at a * resume point is persisted in the scan cache through `schema`, so a grown From 8cc8bcbf6b4041cadffb54f627a6476ee87ef819 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 18:55:40 -0800 Subject: [PATCH 144/162] feat(server): outside agents receive milestones by MCP Events webhooks (#41141) --- apps/server/src/mcp/McpHttpServer.ts | 53 +- .../src/mcp/McpWebhookTransport.test.ts | 66 + apps/server/src/mcp/McpWebhookTransport.ts | 127 ++ .../src/milestones/MilestoneEvents.test.ts | 501 ++++- apps/server/src/milestones/MilestoneEvents.ts | 116 +- docs/user/outside-agents.md | 21 +- patches/effect@4.1.5.patch | 1723 ++++++++++++++++- pnpm-lock.yaml | 518 ++--- 8 files changed, 2752 insertions(+), 373 deletions(-) create mode 100644 apps/server/src/mcp/McpWebhookTransport.test.ts create mode 100644 apps/server/src/mcp/McpWebhookTransport.ts diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 5bf97d42a2461..ab1f7b003c566 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -55,6 +55,7 @@ import { advertisedJsonSchema } from "./advertisedJsonSchema.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; import * as McpToolExposure from "./McpToolExposure.ts"; +import * as McpWebhookTransport from "./McpWebhookTransport.ts"; import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts"; @@ -296,14 +297,17 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { const pullRequests = yield* Effect.serviceOption(PullRequestService.PullRequestService); const projections = yield* Effect.serviceOption(ProjectionStore.ProjectionStoreV2); const sessions = yield* Effect.serviceOption(SessionStore.SessionStore); - // Auth runs once per request, so a response that streams on, such as `events/stream`, ends - // when the outside client's session is revoked or expires. + // Auth runs once per request, so a response that streams on ends when the outside client's + // session is revoked or expires. `events/stream` ends itself first with + // `notifications/events/terminated`, which cutting the body here would lose. const endWithSession = ( response: HttpServerResponse.HttpServerResponse, + request: HttpServerRequest.HttpServerRequest, client: McpInvocationContext.McpClientCaller | undefined, ) => { const body = response.body; if (client === undefined || Option.isNone(sessions) || body._tag !== "Stream") return response; + if (request.headers["mcp-method"] === "events/stream") return response; const invalidated = sessions.value .awaitInvalidation(AuthSessionId.make(client.sessionId)) .pipe(Effect.ignore); @@ -389,7 +393,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { return yield* httpEffect.pipe( Effect.provideService(McpInvocationContext.McpInvocationContext, admitted), Effect.map(normalizeMcpHttpResponse), - Effect.map((response) => endWithSession(response, admitted.client)), + Effect.map((response) => endWithSession(response, request, admitted.client)), Effect.map((response) => linkExpiresAt === undefined ? response @@ -1499,8 +1503,44 @@ export const layerToolSearch = Layer.mergeAll( ).pipe(Layer.provide(layerToolExposure)); /** - * Milestones as MCP events (SEP-3415) for outside clients to poll or stream. Protocol-level, so no - * thread lists them. + * A webhook subscription belongs to the outside client's session. Its id is the same for the + * session's whole life, and a client signs in again rather than refreshing a token, so a new + * sign-in is a new principal whose subscriptions the old session's end does not touch. + */ +const webhookPrincipal = Effect.serviceOption(McpInvocationContext.McpInvocationContext).pipe( + Effect.flatMap((scope) => { + const client = Option.getOrUndefined(scope)?.client; + return client === undefined + ? Effect.fail( + new McpSchema.Forbidden({ + message: "Webhook delivery needs an outside client's sign-in", + }), + ) + : Effect.succeed(client.sessionId); + }), +); + +/** Webhooks reach public addresses only, through a client pinned to the address it checked. */ +const layerWebhookTransport = Layer.unwrap( + Effect.gen(function* () { + const transport = McpWebhookTransport.make(yield* McpWebhookTransport.allowedHosts); + return Layer.merge( + Layer.succeed(McpServer.CallbackGuard, { + allowsPlaintext: transport.allowsPlaintext, + check: Effect.fn("McpHttpServer.webhookCallbackCheck")(function* (url: URL) { + return yield* transport + .check(url) + .pipe(Effect.mapError((error) => new McpServer.CallbackRejected(error))); + }), + }), + transport.layerClient, + ); + }).pipe(Effect.orDie), +); + +/** + * Milestones as MCP events (SEP-3415) for outside clients to poll, stream or receive by webhook. + * Protocol-level, so no thread lists them. */ export const layerMilestoneEvents = Layer.effectDiscard( Effect.gen(function* () { @@ -1513,6 +1553,9 @@ export const layerMilestoneEvents = Layer.effectDiscard( yield* McpServer.registerEvent({ ...options, annotations }); } }), +).pipe( + Layer.provide(McpServer.layerEventWebhooks({ principal: webhookPrincipal })), + Layer.provide(layerWebhookTransport), ); export const layer = layerMcpTransport( diff --git a/apps/server/src/mcp/McpWebhookTransport.test.ts b/apps/server/src/mcp/McpWebhookTransport.test.ts new file mode 100644 index 0000000000000..0afbfa0b8c5c7 --- /dev/null +++ b/apps/server/src/mcp/McpWebhookTransport.test.ts @@ -0,0 +1,66 @@ +import { NodeHttpServer } from "@effect/platform-node"; +import { expect, it } from "@effect/vitest"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { HttpClient, HttpRouter, HttpServer, HttpServerResponse } from "effect/http"; + +import * as McpWebhookTransport from "./McpWebhookTransport.ts"; + +it.each([ + ["127.0.0.1", false], + ["10.1.2.3", false], + ["172.16.0.1", false], + ["192.168.1.1", false], + ["169.254.169.254", false], + ["100.64.0.1", false], + ["0.0.0.0", false], + ["::1", false], + ["fc00::1", false], + ["fe80::1", false], + ["::ffff:127.0.0.1", false], + ["fec0::1", false], + ["5f00::1", false], + ["::ffff:0:102:304", false], + ["8.8.8.8", true], + ["2606:4700:4700::1111", true], +])("treats %s as globally routable: %s", (address, routable) => { + expect(McpWebhookTransport.isGloballyRoutable(address)).toBe(routable); +}); + +it.effect("refuses private callbacks unless allowlisted, and the client never reaches them", () => + Effect.gen(function* () { + yield* HttpRouter.serve( + Layer.mergeAll( + HttpRouter.add("POST", "/redirect", HttpServerResponse.redirect("/target")), + HttpRouter.add("POST", "/target", HttpServerResponse.text("reached")), + ), + { disableListenLog: true, disableLogger: true }, + ).pipe(Layer.build); + const port = new URL(HttpServer.formatAddress((yield* HttpServer.HttpServer).address)).port; + const guard = McpWebhookTransport.make(["127.0.0.1"]); + const client = Context.get(yield* Layer.build(guard.layerClient), HttpClient.HttpClient); + + const refused = (url: string) => + guard.check(new URL(url)).pipe( + Effect.flip, + Effect.map((error) => error._tag), + ); + expect(yield* refused("https://10.0.0.1/hook")).toBe("WebhookAddressRejected"); + expect(yield* refused("https://[::1]/hook")).toBe("WebhookAddressRejected"); + expect(yield* refused("https://localhost/hook")).toBe("WebhookAddressRejected"); + yield* guard.check(new URL(`http://127.0.0.1:${port}/hook`)); + expect(guard.allowsPlaintext(new URL("http://127.0.0.1/hook"))).toBe(true); + expect(guard.allowsPlaintext(new URL("http://localhost/hook"))).toBe(false); + + // A redirect comes back as it is, never followed. + const redirected = yield* client.post(`http://127.0.0.1:${port}/redirect`); + expect(redirected.status).toBe(302); + // The client resolves again when it connects, so a name for a private address fails there. + const pinned = yield* Effect.flip(client.post(`http://localhost:${port}/target`)); + expect(pinned.reason._tag).toBe("TransportError"); + expect(String((pinned.reason as { readonly cause?: unknown }).cause)).toContain( + "localhost is not a public address", + ); + }).pipe(Effect.scoped, Effect.provide(NodeHttpServer.layerTest)), +); diff --git a/apps/server/src/mcp/McpWebhookTransport.ts b/apps/server/src/mcp/McpWebhookTransport.ts new file mode 100644 index 0000000000000..8bdde7b1184da --- /dev/null +++ b/apps/server/src/mcp/McpWebhookTransport.ts @@ -0,0 +1,127 @@ +import * as NodeDns from "node:dns"; +import * as NodeNet from "node:net"; + +import { NodeHttpClient } from "@effect/platform-node"; +import * as Config from "effect/Config"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +/** + * Hosts that may receive webhooks although they are private or plain `http:`, for testing + * against a local receiver. Comma-separated host names or addresses; unset denies them all. + */ +export const ALLOWED_HOSTS_ENV = "T3CODE_MCP_WEBHOOK_ALLOWED_HOSTS"; + +export const allowedHosts = Config.String(ALLOWED_HOSTS_ENV).pipe( + Config.withDefault(""), + Config.map((value) => value.split(",").filter((host) => host.trim() !== "")), +); + +export class WebhookAddressRejected extends Schema.TaggedError()( + "WebhookAddressRejected", + { message: Schema.String }, +) {} + +// The IANA special-purpose ranges that are not globally reachable. An IPv6 address must also be +// in global unicast (2000::/3), which leaves out every form that embeds an IPv4 address. Two +// lists, because a list checks an IPv4 address against its IPv4-mapped IPv6 rules too. +const notGlobalV4 = new NodeNet.BlockList(); +for (const [network, prefix] of [ + ["0.0.0.0", 8], + ["10.0.0.0", 8], + ["100.64.0.0", 10], + ["127.0.0.0", 8], + ["169.254.0.0", 16], + ["172.16.0.0", 12], + ["192.0.0.0", 24], + ["192.0.2.0", 24], + ["192.88.99.0", 24], + ["192.168.0.0", 16], + ["198.18.0.0", 15], + ["198.51.100.0", 24], + ["203.0.113.0", 24], + ["224.0.0.0", 4], + ["240.0.0.0", 4], +] as const) { + notGlobalV4.addSubnet(network, prefix, "ipv4"); +} +const globalUnicastV6 = new NodeNet.BlockList(); +globalUnicastV6.addSubnet("2000::", 3, "ipv6"); +const notGlobalV6 = new NodeNet.BlockList(); +for (const [network, prefix] of [ + ["2001::", 23], + ["2001:db8::", 32], + ["2002::", 16], + ["3fff::", 20], +] as const) { + notGlobalV6.addSubnet(network, prefix, "ipv6"); +} + +export const isGloballyRoutable = (address: string): boolean => { + const family = NodeNet.isIP(address); + if (family === 4) return !notGlobalV4.check(address, "ipv4"); + return ( + family === 6 && globalUnicastV6.check(address, "ipv6") && !notGlobalV6.check(address, "ipv6") + ); +}; + +const hostOf = (url: URL) => url.hostname.replace(/^\[(.*)\]$/, "$1").toLowerCase(); + +const resolveAll = (host: string) => + Effect.callback, Error>((resume) => { + NodeDns.lookup(host, { all: true }, (error, addresses) => + resume(error === null ? Effect.succeed(addresses) : Effect.fail(error)), + ); + }); + +/** + * The webhook address check and the client deliveries go through. The client resolves again + * as it connects, to the address it checks, so DNS rebinding cannot reach a private address; + * TLS still sees the host name. Undici's dispatcher never follows redirects. + */ +export const make = (hosts: ReadonlyArray) => { + const allowed = new Set(hosts.map((host) => host.trim().toLowerCase())); + const check = Effect.fn("McpWebhookTransport.check")(function* (url: URL) { + const host = hostOf(url); + if (allowed.has(host)) return; + const addresses = + NodeNet.isIP(host) !== 0 + ? [host] + : (yield* resolveAll(host).pipe( + // A subscribe holds its slot while this runs, and a delivery's request timeout + // does not cover it, so a slow resolver counts as no answer. + Effect.timeout("5 seconds"), + Effect.mapError( + () => new WebhookAddressRejected({ message: `${host} could not be resolved` }), + ), + )).map((resolved) => resolved.address); + if (addresses.length === 0 || !addresses.every(isGloballyRoutable)) { + return yield* new WebhookAddressRejected({ message: `${host} is not a public address` }); + } + }); + const lookup: NodeNet.LookupFunction = (hostname, lookupOptions, callback) => { + NodeDns.lookup(hostname, { ...lookupOptions, all: true }, (error, addresses) => { + if (error !== null) return callback(error, ""); + if ( + !allowed.has(hostname.toLowerCase()) && + (addresses.length === 0 || + addresses.some((address) => !isGloballyRoutable(address.address))) + ) { + return callback( + Object.assign(new Error(`${hostname} is not a public address`), { + code: "ECONNREFUSED", + }), + "", + ); + } + if (lookupOptions.all === true) return callback(null, addresses); + const [first] = addresses; + return callback(null, first!.address, first!.family); + }); + }; + return { + check, + allowsPlaintext: (url: URL) => allowed.has(hostOf(url)), + layerClient: NodeHttpClient.layerUndiciOptions({ connect: { lookup } }), + }; +}; diff --git a/apps/server/src/milestones/MilestoneEvents.test.ts b/apps/server/src/milestones/MilestoneEvents.test.ts index 44896477fa670..06e7763023841 100644 --- a/apps/server/src/milestones/MilestoneEvents.test.ts +++ b/apps/server/src/milestones/MilestoneEvents.test.ts @@ -9,24 +9,38 @@ import { RunId, ThreadId, } from "@t3tools/contracts"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Mac from "effect/crypto/Mac"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Base64 from "effect/encoding/Base64"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; -import { HttpBody, HttpClient, HttpRouter } from "effect/http"; +import { + HttpBody, + HttpClient, + HttpRouter, + HttpServer, + type HttpServerRequest, + HttpServerResponse, +} from "effect/http"; import * as SessionStore from "../auth/SessionStore.ts"; import * as McpHttpServer from "../mcp/McpHttpServer.ts"; import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts"; +import * as McpWebhookTransport from "../mcp/McpWebhookTransport.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as MilestoneHub from "./MilestoneHub.ts"; const environmentId = EnvironmentId.make("environment-milestone-events-test"); const clientToken = "clientTokenWithoutDots"; const threadToken = "threadTokenWithoutDots"; +const hostToken = "hostTokenWithoutDots"; const scopes: Record = { [clientToken]: { environmentId, @@ -48,8 +62,51 @@ const scopes: Record = { capabilities: new Set(["orchestration"]), issuedAt: 1, }, + // A script on the host: signed in as no outside client. + [hostToken]: { + environmentId, + requestNamespace: "host", + thread: undefined, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }, }; +// The Standard Webhooks example secret: base64 of 24 bytes. +const secret = "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw"; + +/** The Standard Webhooks check a receiver runs: any `v1,` signature over id, timestamp and body. */ +const signedBy = Effect.fnUntraced(function* ( + secretValue: string, + headers: Readonly>, + body: string, +) { + const mac = yield* Mac.Mac; + const bytes = Base64.decode(secretValue.slice("whsec_".length)); + if (bytes._tag === "Failure") return false; + const key = yield* Mac.key(Mac.hmacSha256, bytes.success); + const tag = yield* mac.sign( + key, + new TextEncoder().encode(`${headers["webhook-id"]}.${headers["webhook-timestamp"]}.${body}`), + ); + return (headers["webhook-signature"] ?? "").split(" ").includes(`v1,${Base64.encode(tag)}`); +}, Effect.orDie); + +interface Delivery { + readonly headers: Readonly>; + readonly raw: string; + readonly body: Record; + readonly reply: Deferred.Deferred; +} + +/** `open` sends the body and never ends it. */ +interface Answer { + readonly status: number; + readonly body?: string; + readonly open?: boolean; +} + const settled = ( id: string, options: { readonly project?: string; readonly at?: string } = {}, @@ -73,8 +130,40 @@ type JsonRpcResponse = { const serve = Effect.gen(function* () { const revoked = yield* Deferred.make(); + const deliveries = yield* Queue.unbounded(); + const replies = new Set(); + // The webhook receiver: each POST waits for the test to answer it. + const receiver = HttpRouter.add( + "POST", + "/hook", + Effect.fnUntraced(function* (request: HttpServerRequest.HttpServerRequest) { + const raw = yield* request.text; + const reply = yield* Deferred.make(); + replies.add(reply); + yield* Queue.offer(deliveries, { + headers: request.headers, + raw, + body: JSON.parse(raw), + reply, + }); + const answer = yield* Deferred.await(reply); + return answer.open === true + ? HttpServerResponse.stream( + Stream.make(new TextEncoder().encode(answer.body)).pipe(Stream.concat(Stream.never)), + { status: answer.status, contentType: "application/json" }, + ) + : HttpServerResponse.text(answer.body ?? "", { status: answer.status }); + }, Effect.orDie), + ); yield* HttpRouter.serve( - McpHttpServer.layerMcpTransport(McpHttpServer.layerMilestoneEvents).pipe( + Layer.merge(McpHttpServer.layerMcpTransport(McpHttpServer.layerMilestoneEvents), receiver).pipe( + Layer.provide( + ConfigProvider.layer( + ConfigProvider.fromEnv({ + env: { [McpWebhookTransport.ALLOWED_HOSTS_ENV]: "127.0.0.1" }, + }), + ), + ), Layer.provide(ServerSettings.layerTest()), Layer.provide( Layer.mock(SessionStore.SessionStore)({ @@ -139,7 +228,9 @@ const serve = Effect.gen(function* () { cursor: result!.cursor as string, truncated: result!.truncated as boolean, hasMore: result!.hasMore as boolean, - ids: (result!.events as ReadonlyArray<{ eventId: string }>).map((event) => event.eventId), + ids: (result!.events as ReadonlyArray<{ data: { id: string } }>).map( + (event) => event.data.id, + ), })), ); const stream = (args: Record, id = 7) => @@ -160,10 +251,46 @@ const serve = Effect.gen(function* () { ), ), ); - return { post, call, poll, stream, revoke: Deferred.succeed(revoked, undefined) }; + // Shutting the server down waits for open requests, so a test that stops early answers them. + yield* Effect.addFinalizer(() => + Effect.forEach(replies, (reply) => Deferred.succeed(reply, { status: 503 }), { discard: true }), + ); + const hookUrl = `${HttpServer.formatAddress((yield* HttpServer.HttpServer).address)}/hook`; + const answer = (delivery: Delivery, status: number, body?: string, open = false) => + Deferred.succeed(delivery.reply, body === undefined ? { status } : { status, body, open }); + const subscribeParams = (params: Record = {}) => ({ + name: "thread.run_settled", + delivery: { mode: "webhook", url: hookUrl, secret }, + cursor: null, + ...params, + }); + // Subscribes; a first subscription to the URL is verified, so this echoes the challenge. + const subscribe = Effect.fnUntraced(function* (params: Record = {}) { + const pending = yield* Effect.forkChild(call("events/subscribe", subscribeParams(params))); + const verification = yield* Queue.take(deliveries); + expect(verification.body.type).toBe("verification"); + expect(yield* signedBy(secret, verification.headers, verification.raw)).toBe(true); + yield* answer(verification, 200, JSON.stringify({ challenge: verification.body.challenge })); + return { verification, response: yield* Fiber.join(pending) }; + }); + return { + post, + call, + poll, + stream, + revoke: Deferred.succeed(revoked, undefined), + deliveries, + answer, + subscribeParams, + subscribe, + }; }); -const layerTest = Layer.mergeAll(MilestoneHub.layer, NodeHttpServer.layerTest); +const layerTest = Layer.mergeAll( + MilestoneHub.layer, + NodeHttpServer.layerTest, + Mac.layerWebCrypto.pipe(Layer.provide(SecureRandom.layerWebCrypto)), +); it.effect("advertises the extension and lists each milestone type to outside clients only", () => Effect.gen(function* () { @@ -172,13 +299,17 @@ it.effect("advertises the extension and lists each milestone type to outside cli expect(discovered.result!.capabilities.extensions).toEqual({ "io.modelcontextprotocol/events": {}, }); + // TODO(#41158): drop with the bridge for clients predating SEP-3415. + expect(discovered.result!.capabilities.events).toEqual({}); const { events } = (yield* call("events/list")).result!; expect(events).toHaveLength(12); const settledType = events.find( (event: { name: string }) => event.name === "thread.run_settled", ); - expect(settledType.delivery).toEqual(["poll", "push"]); + for (const event of events) { + expect(event.delivery).toEqual(["poll", "push", "webhook"]); + } expect(Object.keys(settledType.inputSchema.properties)).toEqual([ "projectIds", "threadIds", @@ -236,26 +367,69 @@ it.effect("polls from now, then pages forward and says when a cursor fell behind }).pipe(Effect.scoped, Effect.provide(layerTest)), ); -it.effect("rejects a mismatched Mcp-Name, an unknown event and webhook delivery", () => +it.effect("rejects a mismatched Mcp-Name, an unknown event and a bad webhook callback", () => Effect.gen(function* () { - const { post, call } = yield* serve; + const { post, call, deliveries, answer, subscribeParams } = yield* serve; const params = { name: "thread.run_settled", cursor: null }; const missing = yield* post("events/poll", params, { name: null }); expect(missing.status).toBe(400); expect(((yield* missing.json) as JsonRpcResponse).error?.code).toBe(-32020); const mismatched = yield* post("events/poll", params, { name: "thread.needs_input" }); expect(mismatched.status).toBe(400); + // TODO(#41158): drop with the bridge for clients predating SEP-3415. Subscribing needs no Mcp-Name, + // but one that is sent must match. + const wrongName = yield* post("events/subscribe", subscribeParams(), { + name: "thread.needs_input", + }); + expect(((yield* wrongName.json) as JsonRpcResponse).error?.code).toBe(-32020); + // Arguments are checked before the endpoint hears anything. + const badArguments = yield* call( + "events/subscribe", + subscribeParams({ arguments: { projectIds: "project:a" } }), + ).pipe(Effect.forkChild); + expect( + yield* Effect.raceFirst( + Effect.map(Fiber.join(badArguments), (response) => ({ answered: response.error })), + Effect.map(Queue.take(deliveries), (delivery) => ({ posted: delivery.body })), + ), + ).toMatchObject({ answered: { code: -32602 } }); + const unnamed = yield* post("events/subscribe", subscribeParams(), { name: null }).pipe( + Effect.flatMap((response) => response.json), + Effect.forkChild, + ); + const verification = yield* Queue.take(deliveries); + yield* answer(verification, 200, JSON.stringify({ challenge: verification.body.challenge })); + expect(((yield* Fiber.join(unnamed)) as JsonRpcResponse).result?.id).toMatch(/^sub_/); expect((yield* call("events/poll", { name: "nope", cursor: null })).error).toMatchObject({ code: -32023, data: { kind: "event" }, }); + + const subscribe = (delivery: Record, token = clientToken) => + call("events/subscribe", { name: "thread.run_settled", delivery }, { token }).pipe( + Effect.map((response) => response.error), + ); + const valid = { mode: "webhook", url: "https://example.com/hook", secret }; + // Webhooks need an outside client's sign-in; threads cannot see events at all. + expect(yield* subscribe(valid, hostToken)).toMatchObject({ code: -32024 }); + expect(yield* subscribe(valid, threadToken)).toMatchObject({ code: -32023 }); + expect(yield* subscribe({ ...valid, secret: "whsec_c2hvcnQ=" })).toMatchObject({ + code: -32602, + }); + expect(yield* subscribe({ ...valid, secret: { toString: 1 } })).toMatchObject({ + code: -32602, + }); + // Plain http and private addresses are refused unless allowlisted. + expect(yield* subscribe({ ...valid, url: "http://example.com/hook" })).toMatchObject({ + code: -32602, + }); + expect(yield* subscribe({ ...valid, url: "https://10.0.0.1/hook" })).toMatchObject({ + code: -32602, + }); expect( - (yield* call("events/subscribe", { - name: "thread.run_settled", - delivery: { mode: "webhook", url: "https://example.com/hook", secret: "whsec_x" }, - })).error, - ).toMatchObject({ code: -32026, data: { feature: "deliveryMode", value: "webhook" } }); + (yield* call("events/unsubscribe", { name: "thread.run_settled", delivery: valid })).error, + ).toMatchObject({ code: -32023, data: { kind: "subscription" } }); }).pipe(Effect.scoped, Effect.provide(layerTest)), ); @@ -278,7 +452,7 @@ it.effect("streams live milestones after active, replays from a cursor and sends expect(event).toMatchObject({ method: "notifications/events/event", params: { - eventId: "b", + eventId: expect.stringMatching(/^evt_[\w-]{22}$/), name: "thread.run_settled", data: { id: "b", projectId: "project:b" }, _meta: { "io.modelcontextprotocol/subscriptionId": 7 }, @@ -295,8 +469,8 @@ it.effect("streams live milestones after active, replays from a cursor and sends const replay = yield* stream({ cursor: "previous-boot.1" }, 8); expect(yield* Queue.takeN(replay, 3)).toMatchObject([ { method: "notifications/events/active", params: { truncated: true } }, - { method: "notifications/events/event", params: { eventId: "a" } }, - { method: "notifications/events/event", params: { eventId: "b" } }, + { method: "notifications/events/event", params: { data: { id: "a" } } }, + { method: "notifications/events/event", params: { data: { id: "b" } } }, ]); }).pipe(Effect.scoped, Effect.provide(layerTest)), ); @@ -308,6 +482,299 @@ it.effect("ends an open stream when the client's session is revoked", () => expect(yield* Queue.take(live)).toMatchObject({ method: "notifications/events/active" }); yield* revoke; - expect((yield* Effect.exit(Queue.take(live)))._tag).toBe("Failure"); + // It says why, then closes. + expect(yield* Queue.take(live)).toMatchObject({ + method: "notifications/events/terminated", + params: { error: { code: -32024 } }, + }); + while ((yield* Effect.exit(Queue.take(live)))._tag === "Success") { + // The request's own response follows the notice. + } + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("signs like the Standard Webhooks reference", () => + Effect.gen(function* () { + expect( + yield* signedBy( + secret, + { + "webhook-id": "msg_p5jXN8AQM9LWM0D4loKWxJek", + "webhook-timestamp": "1614265330", + "webhook-signature": "v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=", + }, + '{"test": 2432232314}', + ), + ).toBe(true); + }).pipe(Effect.provide(layerTest)), +); + +it.effect("verifies a webhook endpoint and refuses one that does not echo the challenge", () => + Effect.gen(function* () { + const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve; + const at = (url: string) => + call( + "events/subscribe", + subscribeParams({ delivery: { mode: "webhook", url, secret } }), + ).pipe(Effect.forkChild); + const wrongUrl = `${subscribeParams().delivery.url}?wrong`; + const failing = yield* at(wrongUrl); + const wrong = yield* Queue.take(deliveries); + yield* answer(wrong, 200, JSON.stringify({ challenge: "not-it" })); + expect((yield* Fiber.join(failing)).error).toMatchObject({ + code: -32027, + data: { reason: "challenge_failed" }, + }); + // A failure is remembered, so subscribing again answers without another POST. + const again = yield* at(wrongUrl); + const repeated = yield* Effect.raceFirst( + Effect.map(Fiber.join(again), (response) => ({ cached: response.error })), + Effect.map(Queue.take(deliveries), (delivery) => ({ posted: delivery.body })), + ); + expect(repeated).toMatchObject({ + cached: { code: -32027, data: { reason: "challenge_failed" } }, + }); + + // At most 8 KiB of the answer is read: exactly that passes, and one byte more fails at + // once, even from an endpoint that never ends its answer. + const echoOfLength = (challenge: string, length: number) => { + const bare = JSON.stringify({ challenge, padding: "" }); + return JSON.stringify({ challenge, padding: "x".repeat(length - bare.length) }); + }; + const exact = yield* at(`${subscribeParams().delivery.url}?exact`); + const fits = yield* Queue.take(deliveries); + yield* answer(fits, 200, echoOfLength(fits.body.challenge, 8_192)); + expect((yield* Fiber.join(exact)).error).toBeUndefined(); + const long = yield* at(`${subscribeParams().delivery.url}?long`); + const padded = yield* Queue.take(deliveries); + yield* answer(padded, 200, echoOfLength(padded.body.challenge, 8_193), true); + expect((yield* Fiber.join(long)).error).toMatchObject({ + code: -32027, + data: { reason: "challenge_failed" }, + }); + + const { verification, response } = yield* subscribe(); + expect(verification.headers["webhook-id"]).toMatch(/^msg_verification_[\w-]+$/); + expect(verification.headers["x-mcp-subscription-id"]).toBe(response.result!.id); + expect(response.result).toMatchObject({ + id: expect.stringMatching(/^sub_[0-9a-f]{32}$/), + truncated: false, + }); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("delivers one signed event at a time and advances the cursor once each resolves", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve; + const { response } = yield* subscribe({ ttlMs: 600_000 }); + const subscribed = response.result!; + const refresh = (params: Record = {}) => + call("events/subscribe", subscribeParams({ ttlMs: 600_000, ...params })).pipe( + Effect.map((refreshed) => refreshed.result!), + ); + + yield* hub.publish(settled("a")); + yield* hub.publish(settled("b")); + const first = yield* Queue.take(deliveries); + expect(first.body).toMatchObject({ data: { id: "a" }, name: "thread.run_settled" }); + // TODO(#41158): drop with the bridge for clients predating SEP-3415. An event's webhook-id is its eventId. + expect(first.body.eventId).toMatch(/^[A-Za-z0-9_-]+$/); + expect(first.headers["webhook-id"]).toBe(first.body.eventId); + expect(first.headers["x-mcp-subscription-id"]).toBe(subscribed.id); + expect(yield* signedBy(secret, first.headers, first.raw)).toBe(true); + yield* answer(first, 500); + // Unresolved, so the refresh still reports where the subscription started. + expect(yield* refresh()).toMatchObject({ + id: subscribed.id, + cursor: subscribed.cursor, + deliveryStatus: { active: true, lastError: "http_5xx" }, + }); + + // "b" waits for "a": the next POST is its retry, which keeps its webhook-id with a fresh + // timestamp and signature. + yield* TestClock.adjust("30 seconds"); + const retry = yield* Queue.take(deliveries); + expect(retry.body.data.id).toBe("a"); + expect(retry.headers["webhook-id"]).toBe(first.headers["webhook-id"]); + expect(retry.headers["webhook-timestamp"]).not.toBe(first.headers["webhook-timestamp"]); + expect(yield* signedBy(secret, retry.headers, retry.raw)).toBe(true); + yield* answer(retry, 200); + + // Only after "a" resolved does "b" go out; a 410 gives it up without a retry. + const second = yield* Queue.take(deliveries); + expect(second.body.data.id).toBe("b"); + expect(yield* refresh()).toMatchObject({ + cursor: first.body.cursor, + deliveryStatus: { lastError: null, lastDeliveryAt: expect.any(String) }, + }); + yield* answer(second, 410); + // A new secret signs alongside the old one for a grace period. + const rotated = "whsec_" + Buffer.alloc(32, 7).toString("base64"); + yield* refresh({ + delivery: { mode: "webhook", url: subscribeParams().delivery.url, secret: rotated }, + }); + yield* hub.publish(settled("c")); + const third = yield* Queue.take(deliveries); + expect(third.body.data.id).toBe("c"); + expect(yield* signedBy(secret, third.headers, third.raw)).toBe(true); + expect(yield* signedBy(rotated, third.headers, third.raw)).toBe(true); + expect( + (yield* refresh({ + delivery: { mode: "webhook", url: subscribeParams().delivery.url, secret: rotated }, + })).cursor, + ).toBe(second.body.cursor); + yield* answer(third, 200); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("reports a gap the endpoint never took on the next refresh", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve; + const filter = { arguments: { projectIds: ["project:a"] } }; + yield* subscribe(filter); + yield* hub.publish(settled("a")); + const first = yield* Queue.take(deliveries); + // While "a" is out, more milestones than the subscription's backlog go by elsewhere. + for (let index = 0; index < 300; index++) { + yield* hub.publish(settled(`elsewhere-${index}`, { project: "project:b" })); + } + yield* answer(first, 200); + const gap = yield* Queue.take(deliveries); + expect(gap.body).toMatchObject({ type: "gap" }); + yield* answer(gap, 410); + // "c" goes out only after the gap was given up on. + yield* hub.publish(settled("c")); + const next = yield* Queue.take(deliveries); + expect(next.body.data.id).toBe("c"); + const refresh = (cursor: string) => + call("events/subscribe", subscribeParams({ ...filter, cursor })).pipe( + Effect.map(({ result }) => result!), + ); + // Until the client shows a cursor from past the gap, as if each answer were lost. + const refreshed = yield* refresh(first.body.cursor); + expect(refreshed.truncated).toBe(true); + expect(refreshed.cursor).not.toBe(first.body.cursor); + expect((yield* refresh(first.body.cursor)).truncated).toBe(true); + expect((yield* refresh(refreshed.cursor)).truncated).toBe(false); + yield* answer(next, 200); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("gives each subscription to one URL its own delivery id for an event", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { call, deliveries, answer, subscribe, subscribeParams } = yield* serve; + yield* subscribe(); + yield* call("events/subscribe", subscribeParams({ arguments: { projectIds: ["project:a"] } })); + yield* hub.publish(settled("a")); + const both = [yield* Queue.take(deliveries), yield* Queue.take(deliveries)]; + for (const delivery of both) { + expect(delivery.body.data.id).toBe("a"); + expect(delivery.headers["webhook-id"]).toBe(delivery.body.eventId); + yield* answer(delivery, 200); + } + expect(both[0]!.headers["webhook-id"]).not.toBe(both[1]!.headers["webhook-id"]); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("gives an event up after five attempts", () => + Effect.gen(function* () { + const hub = yield* MilestoneHub.MilestoneHub; + const { deliveries, answer, subscribe } = yield* serve; + yield* subscribe(); + yield* hub.publish(settled("a")); + for (const wait of ["30 seconds", "1 minute", "2 minutes", "4 minutes"] as const) { + yield* answer(yield* Queue.take(deliveries), 503); + yield* TestClock.adjust(wait); + } + const last = yield* Queue.take(deliveries); + expect(last.body.data.id).toBe("a"); + yield* answer(last, 503); + yield* hub.publish(settled("b")); + const next = yield* Queue.take(deliveries); + expect(next.body.data.id).toBe("b"); + yield* answer(next, 200); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("grants a finite TTL and keeps one id for the same subscription", () => + Effect.gen(function* () { + const { call, subscribe, subscribeParams } = yield* serve; + const { response } = yield* subscribe({ ttlMs: 1_000 }); + // The test clock starts at the epoch; a grant is clamped to between a minute and an hour. + const hour = "1970-01-01T01:00:00.000Z"; + expect(response.result!.refreshBefore).toBe("1970-01-01T00:01:00.000Z"); + const grant = (params: Record) => + call("events/subscribe", subscribeParams(params)).pipe(Effect.map(({ result }) => result!)); + expect((yield* grant({ ttlMs: null })).refreshBefore).toBe(hour); + expect((yield* grant({ ttlMs: 86_400_000 })).refreshBefore).toBe(hour); + expect((yield* grant({})).refreshBefore).toBe("1970-01-01T00:15:00.000Z"); + + // Arguments compare as canonical JSON; a different filter is another subscription. + const ordered = yield* grant({ + arguments: { projectIds: ["project:a"], includeSubagentChildren: true }, + }); + const reordered = yield* grant({ + arguments: { includeSubagentChildren: true, projectIds: ["project:a"] }, + }); + expect(reordered.id).toBe(ordered.id); + expect(reordered.deliveryStatus).toBeDefined(); + expect(ordered.id).not.toBe(response.result!.id); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("ends a subscription at a deadline a refresh brought forward", () => + Effect.gen(function* () { + const { call, subscribe, subscribeParams } = yield* serve; + yield* subscribe({ ttlMs: 3_600_000 }); + const grant = (ttlMs: number) => + call("events/subscribe", subscribeParams({ ttlMs })).pipe( + Effect.map(({ result }) => result!), + ); + expect(yield* grant(60_000)).toMatchObject({ + refreshBefore: "1970-01-01T00:01:00.000Z", + deliveryStatus: { active: true }, + }); + yield* TestClock.adjust("1 minute"); + // Gone, so subscribing again starts a new subscription rather than refreshing a live one. + expect((yield* grant(3_600_000)).deliveryStatus).toBeUndefined(); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("refuses subscribes past the per-client cap even when they arrive together", () => + Effect.gen(function* () { + const { call, deliveries, answer, subscribeParams } = yield* serve; + const fibers = yield* Effect.forEach( + Array.from({ length: 101 }, (_, index) => index), + (index) => + call( + "events/subscribe", + subscribeParams({ arguments: { threadIds: [`thread:${index}`] } }), + ).pipe(Effect.forkChild), + ); + // They share one verification; while it is pending each holds a slot, so one is refused now. + const verification = yield* Queue.take(deliveries); + const refused = yield* Effect.raceAll(fibers.map(Fiber.join)); + expect(refused.error).toMatchObject({ + code: -32025, + data: { limit: "subscriptions", max: 100 }, + }); + yield* answer(verification, 200, JSON.stringify({ challenge: verification.body.challenge })); + const responses = yield* Effect.forEach(fibers, Fiber.join); + expect(responses.filter((response) => response.result !== undefined)).toHaveLength(100); + }).pipe(Effect.scoped, Effect.provide(layerTest)), +); + +it.effect("ends a webhook subscription with terminated when the client's session is revoked", () => + Effect.gen(function* () { + const { deliveries, answer, subscribe, revoke } = yield* serve; + yield* subscribe(); + yield* revoke; + const terminated = yield* Queue.take(deliveries); + expect(terminated.headers["webhook-id"]).toMatch(/^msg_terminated_/); + expect(terminated.body).toMatchObject({ type: "terminated", error: { code: -32024 } }); + yield* answer(terminated, 200); }).pipe(Effect.scoped, Effect.provide(layerTest)), ); diff --git a/apps/server/src/milestones/MilestoneEvents.ts b/apps/server/src/milestones/MilestoneEvents.ts index 9c0f2edd0ae55..51d04b2fa1e83 100644 --- a/apps/server/src/milestones/MilestoneEvents.ts +++ b/apps/server/src/milestones/MilestoneEvents.ts @@ -1,4 +1,5 @@ import { + AuthSessionId, type MilestoneEvent as MilestoneEventValue, MilestoneEvent, type MilestoneFilter, @@ -6,11 +7,16 @@ import { ThreadId, TrimmedNonEmptyString, } from "@t3tools/contracts"; +import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -import type { McpServer } from "effect/ai"; +import { McpSchema, type McpServer } from "effect/ai"; +import * as SessionStore from "../auth/SessionStore.ts"; +import * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; import * as MilestoneHub from "./MilestoneHub.ts"; // Matches the hub's buffer, so a poll can drain everything it keeps at once. @@ -59,33 +65,72 @@ const DESCRIPTIONS: Record = { "workflow.run_ended": "A workflow run ended: completed, stopped, skipped or cancelled.", }; -const occurrence = ({ event }: MilestoneHub.PositionedMilestone) => ({ - eventId: event.id, - timestamp: event.occurredAt, - data: event, -}); - /** - * Each milestone type as an MCP event type (SEP-3415), for outside clients to poll or stream. - * Cursors are the hub's, so a client that was away catches up on what the hub still keeps. - * Workflow runs have no project or thread, so their types are narrowed by workflow and run. + * Each milestone type as an MCP event type (SEP-3415), for outside clients to poll, stream or + * receive by webhook. Cursors are the hub's, so a client that was away catches up on what the + * hub still keeps. Workflow runs have no project or thread, so their types are narrowed by + * workflow and run. */ export const make = Effect.gen(function* () { const hub = yield* MilestoneHub.MilestoneHub; + const sessions = yield* Effect.serviceOption(SessionStore.SessionStore); + // A webhook subscription outlives its request, so it ends itself when the client's session does. + const untilRevoked = Effect.fnUntraced(function* (items: Stream.Stream) { + const scope = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext); + const sessionId = Option.getOrUndefined(scope)?.client?.sessionId; + if (sessionId === undefined || Option.isNone(sessions)) return items; + const revoked = sessions.value.awaitInvalidation(AuthSessionId.make(sessionId)).pipe( + Effect.ignore, + Effect.andThen( + Effect.fail( + new McpSchema.Forbidden({ + message: "Access revoked", + data: { reason: "Access revoked" }, + }), + ), + ), + ); + return items.pipe(Stream.interruptWhen(revoked)); + }); + const digest = yield* Effect.service(Digest.Digest).pipe(Effect.provide(Digest.layerWebCrypto)); + // TODO(#41158): drop this bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp). + // They take an event's eventId as its webhook-id, which allows only [A-Za-z0-9_-], so the + // eventId is a hash of the milestone id, the same in every delivery mode. + const occurrence = ({ event }: MilestoneHub.PositionedMilestone) => + Effect.map(digest.digest(Digest.sha256, new TextEncoder().encode(event.id)), (hash) => ({ + eventId: `evt_${Base64Url.encode(hash).slice(0, 22)}`, + timestamp: event.occurredAt, + data: event, + })); + const context = { hub, untilRevoked, occurrence }; const isWorkflow = (payload: (typeof MilestoneEvent.members)[number]) => payload.fields.type.literal.startsWith("workflow."); return { threads: MilestoneEvent.members .filter((payload) => !isWorkflow(payload)) - .map((payload) => eventOf(hub, payload, Parameters)), + .map((payload) => eventOf(context, payload, Parameters)), workflows: MilestoneEvent.members .filter(isWorkflow) - .map((payload) => eventOf(hub, payload, WorkflowParameters)), + .map((payload) => eventOf(context, payload, WorkflowParameters)), }; }); const eventOf =

    ( - hub: MilestoneHub.MilestoneHub["Service"], + { + hub, + untilRevoked, + occurrence, + }: { + readonly hub: MilestoneHub.MilestoneHub["Service"]; + readonly occurrence: (milestone: MilestoneHub.PositionedMilestone) => Effect.Effect<{ + readonly eventId: string; + readonly timestamp: string; + readonly data: MilestoneEventValue; + }>; + readonly untilRevoked: ( + items: Stream.Stream, + ) => Effect.Effect>; + }, payload: (typeof MilestoneEvent.members)[number], parameters: P, ) => { @@ -104,22 +149,41 @@ const eventOf =

    ( filter: filterOf(args), limit: Math.min(request.maxEvents ?? DEFAULT_EVENTS, MAX_EVENTS), }) - .pipe(Effect.map((page) => ({ ...page, events: page.events.map(occurrence) }))), - stream: (args, request) => - hub - .follow({ cursor: request.cursor, maxAgeMs: request.maxAgeMs, filter: filterOf(args) }) .pipe( - Effect.map(({ cursor, truncated, items }) => ({ - cursor, - truncated, - items: items.pipe( - Stream.map((item): McpServer.EventStreamItem => + Effect.flatMap((page) => + Effect.map(Effect.forEach(page.events, occurrence), (events) => ({ + ...page, + events, + })), + ), + ), + stream: Effect.fn("MilestoneEvents.stream")(function* ( + args: P["Type"], + request: McpServer.EventStreamRequest, + ) { + const { cursor, truncated, items } = yield* hub.follow({ + cursor: request.cursor, + maxAgeMs: request.maxAgeMs, + filter: filterOf(args), + }); + return { + cursor, + truncated, + items: yield* untilRevoked( + items.pipe( + Stream.mapEffect( + (item): Effect.Effect> => item._tag === "Milestone" - ? { _tag: "Event", cursor: item.cursor, ...occurrence(item) } - : item, - ), + ? Effect.map(occurrence(item), (event) => ({ + _tag: "Event" as const, + cursor: item.cursor, + ...event, + })) + : Effect.succeed(item), ), - })), + ), ), + }; + }), } satisfies McpServer.EventOptions; }; diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index 8a2f790905f75..30c8aba13ffb1 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -138,14 +138,19 @@ Agents without OAuth support cannot connect. A bot that supports MCP Events (`io.modelcontextprotocol/events`) can learn when something happens without reading threads over and over: a turn ended, an agent waits on a person, a guest asked something, a watched pull request woke -its thread. Each of these is an event type it can poll or stream, narrowed to -projects or threads. [Workflow runs](workflows.md) have their own event types, -narrowed to workflows or runs: a run started, paused, resumed or ended, and a -question it asks was raised or settled. Runs that another run started are left -out unless asked for, as subagent threads are, and narrowing thread events to a -run also picks out the threads that are its agent steps. The environment keeps its latest 1,000 milestones in -memory, so a bot that was away longer, or reconnects after a restart, is told -some may be missing and should reread the threads it cares about. +its thread. [Workflow runs](workflows.md) are events too: a run started, paused, +resumed or ended, or waits on a person. A bot can poll, stream, or receive each +event type by webhook, narrowed to projects and threads or to workflows and +runs; runs another run started are left out unless asked for, as subagent +threads are, and narrowing thread events to a run picks out its agent steps. +The environment keeps its latest 1,000 milestones in memory, so a bot that was +away longer, or reconnects after a restart, is told some may be missing and +should reread what it cares about. Webhooks go only to public `https` addresses, +a subscription lasts at most an hour before the bot must renew it, and signing +the bot out ends its subscriptions. To test with a receiver on your own machine +or network, start the environment with `T3CODE_MCP_WEBHOOK_ALLOWED_HOSTS` set to +its host names, for example `localhost,127.0.0.1`; those hosts may also use +plain `http`. ## Scripts on the host diff --git a/patches/effect@4.1.5.patch b/patches/effect@4.1.5.patch index 6d1bf0a6a9fa8..91026f0d15bd7 100644 --- a/patches/effect@4.1.5.patch +++ b/patches/effect@4.1.5.patch @@ -381,10 +381,18 @@ index bff6370..0a6962c 100644 // ============================================================================= /** diff --git a/dist/ai/McpServer.d.ts b/dist/ai/McpServer.d.ts -index fe6f18e..b641e20 100644 +index fe6f18e..c67169e 100644 --- a/dist/ai/McpServer.d.ts +++ b/dist/ai/McpServer.d.ts -@@ -26,6 +26,7 @@ import * as RpcServer from "../rpc/RpcServer.ts"; +@@ -17,6 +17,7 @@ import * as Context from "../Context.ts"; + import * as Duration from "../Duration.ts"; + import * as Effect from "../Effect.ts"; + import * as Headers from "../http/Headers.ts"; ++import * as HttpClient from "../http/HttpClient.ts"; + import * as HttpRouter from "../http/HttpRouter.ts"; + import * as HttpServerRequest from "../http/HttpServerRequest.ts"; + import * as Layer from "../Layer.ts"; +@@ -26,6 +27,7 @@ import * as RpcServer from "../rpc/RpcServer.ts"; import * as Schema from "../Schema.ts"; import * as Scope from "../Scope.ts"; import type { Stdio } from "../Stdio.ts"; @@ -392,7 +400,7 @@ index fe6f18e..b641e20 100644 import type * as Types from "../Types.ts"; import type * as McpProtocol from "./McpProtocol.ts"; import * as McpSchema from "./McpSchema.ts"; -@@ -113,7 +114,7 @@ export interface MiddlewareSuccess { +@@ -113,7 +115,7 @@ export interface MiddlewareSuccess { * @category middleware * @since 4.0.0 */ @@ -401,7 +409,7 @@ index fe6f18e..b641e20 100644 /** * Request metadata passed to MCP middleware. * -@@ -1276,6 +1277,177 @@ export declare const registerSkill: (options: SkillOptions) => Effect.Effect Effect.Effect Layer.Layer; @@ -520,8 +528,8 @@ index fe6f18e..b641e20 100644 + * `parameters` types the subscription arguments, an empty object by default, + * and `payload` the occurrences' `data`; both are advertised as JSON Schema + * by `events/list`. `poll` offers poll delivery and `stream` push delivery, -+ * and at least one is required. Webhook delivery is not supported, so -+ * `events/subscribe` answers `Unsupported`. ++ * and at least one is required. With {@link EventWebhooks} provided where the ++ * event is registered, `stream` also backs webhook delivery. + * + * @stability unstable + * @category events @@ -576,14 +584,128 @@ index fe6f18e..b641e20 100644 + * @since 4.1.4 + */ +export declare const event: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Layer.Layer>; ++declare const CallbackRejected_base: new = {}>(args: import("../Types.ts").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("../Cause.ts").YieldableError & { ++ readonly _tag: "CallbackRejected"; ++} & Readonly; ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare class CallbackRejected extends CallbackRejected_base<{ ++ readonly message: string; ++}> { ++} ++/** ++ * Decides which webhook callback URLs may be reached. ++ * ++ * **Details** ++ * ++ * `check` runs when a subscription is created and again before every POST. ++ * Resolving a host name needs the platform, so the default refuses every URL: ++ * a server that offers webhooks provides a guard that resolves the host and ++ * refuses addresses that are not globally routable. That check alone cannot ++ * stop DNS rebinding, so the `HttpClient` given to {@link layerEventWebhooks} ++ * must connect only to the address it validated, sending the original host ++ * name in `Host` and TLS SNI, and must not follow redirects. `allowsPlaintext` ++ * admits an `http:` URL, which only a local test setup should do. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const CallbackGuard: Context.Reference<{ ++ readonly check: (url: URL) => Effect.Effect; ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined; ++}>; ++declare const EventWebhooks_base: Context.ServiceClass; ++}>; ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * Event types registered with a `stream` where this service is present also ++ * offer webhook delivery. `events/subscribe` validates the callback, verifies ++ * the endpoint with a challenge, and runs the event's `stream` for the ++ * subscription's lifetime, POSTing each occurrence with Standard Webhooks ++ * signatures, one at a time, retrying with backoff. Subscriptions live in ++ * memory: every grant is finite, between a minute and an hour, so a client ++ * refreshing from its cursor recreates what a restart lost. A failure of the ++ * stream, such as `Forbidden` when access is revoked, ends the subscription ++ * with a `terminated` envelope. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare class EventWebhooks extends EventWebhooks_base { ++} ++/** ++ * Options for {@link layerEventWebhooks}. ++ * ++ * **Details** ++ * ++ * `principal` names the authenticated subject of an `events/subscribe` or ++ * `events/unsubscribe` request, read from the request's services. It fails ++ * with `Forbidden` for a caller that may not subscribe; webhook delivery ++ * requires an authenticated principal. A subscription's identity is its ++ * principal, callback URL, event name and arguments, so the principal must ++ * stay the same across token refreshes. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventWebhooksOptions { ++ readonly principal: Effect.Effect; ++} ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const layerEventWebhooks: (options: EventWebhooksOptions) => Layer.Layer; /** * Registers an MCP prompt from an Effect program. * diff --git a/dist/ai/McpServer.js b/dist/ai/McpServer.js -index 4bf6bca..0973460 100644 +index 4bf6bca..5ad258e 100644 --- a/dist/ai/McpServer.js +++ b/dist/ai/McpServer.js -@@ -413,6 +413,9 @@ const notFound = (method, target) => { +@@ -16,6 +16,8 @@ import * as Cause from "../Cause.js"; + import * as Clock from "../Clock.js"; + import * as Context from "../Context.js"; + import * as Digest from "../crypto/Digest.js"; ++import * as Mac from "../crypto/Mac.js"; ++import * as SecureRandom from "../crypto/SecureRandom.js"; + import * as Data from "../Data.js"; + import * as Deferred from "../Deferred.js"; + import * as Duration from "../Duration.js"; +@@ -26,6 +28,7 @@ import * as Exit from "../Exit.js"; + import * as Fiber from "../Fiber.js"; + import * as FindMyWay from "../http/FindMyWay.js"; + import * as Headers from "../http/Headers.js"; ++import * as HttpClient from "../http/HttpClient.js"; + import { appendPreResponseHandlerUnsafe } from "../http/HttpEffect.js"; + import * as HttpRouter from "../http/HttpRouter.js"; + import * as HttpServerRequest from "../http/HttpServerRequest.js"; +@@ -55,6 +58,7 @@ import * as McpCore from "./internal/mcpCore.js"; + import * as McpProtocolInternal from "./internal/mcpProtocol.js"; + import * as McpRuntime from "./internal/mcpRuntime.js"; + import * as McpSkills from "./internal/mcpSkills.js"; ++import * as McpWebhooks from "./internal/mcpWebhooks.js"; + import * as InternalStructuredOutput from "./internal/structured-output.js"; + import * as McpSchema from "./McpSchema.js"; + import { CallToolResult, ElicitationDeclined, EnabledWhen, GetPromptResult, InternalError, InvalidParams, InvalidRequest, isParam, McpRequestContext, McpServerClient, McpServerClientMiddleware, MethodNotFound, Prompt, Resource, ResourceTemplate, ServerNotificationRpcs, TextContent, Tool as McpTool, ToolJson } from "./McpSchema.js"; +@@ -413,6 +417,9 @@ const notFound = (method, target) => { return new McpCore.SkillNotFound({ uri: target }); @@ -593,7 +715,7 @@ index 4bf6bca..0973460 100644 } }; const isHidden = error => error instanceof Hidden; -@@ -2637,6 +2640,96 @@ export const registerSkill = /*#__PURE__*/Effect.fnUntraced(function* (options) +@@ -2637,6 +2644,155 @@ export const registerSkill = /*#__PURE__*/Effect.fnUntraced(function* (options) * @since 4.1.1 */ export const skill = options => Layer.effectDiscard(registerSkill(options)); @@ -608,7 +730,8 @@ index 4bf6bca..0973460 100644 +* +* The server declares `io.modelcontextprotocol/events` on revision +* `2026-07-28` once any event type is registered, and answers `events/list`, -+* `events/poll` and `events/stream`. A push stream runs `stream` for its ++* `events/poll`, `events/stream`, and with {@link EventWebhooks} ++* `events/subscribe` and `events/unsubscribe`. A push stream runs `stream` for its +* lifetime inside the request's middleware, sends heartbeats carrying the +* last cursor, and ends when the client goes away. Services read by `poll` +* and `stream` are request-level, as for tools. @@ -627,6 +750,9 @@ index 4bf6bca..0973460 100644 + const services = yield* Effect.context(); + const annotations = options.annotations ?? Context.empty(); + const { invoke, visible } = makeInvoke(services, globalMiddleware); ++ const webhooks = stream === undefined ++ ? undefined ++ : Option.getOrUndefined(Option.map(Context.getOption(services, EventWebhooks), (service) => webhooksState.get(service))); + const parameters = options.parameters ?? Schema.Struct({}); + const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)); + const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)); @@ -641,13 +767,19 @@ index 4bf6bca..0973460 100644 + descriptor: { + name, + ...(options.description === undefined ? {} : { description: options.description }), -+ delivery: [...(poll === undefined ? [] : ["poll"]), ...(stream === undefined ? [] : ["push"])], ++ delivery: [ ++ ...(poll === undefined ? [] : ["poll"]), ++ ...(stream === undefined ? [] : ["push"]), ++ ...(webhooks === undefined ? [] : ["webhook"]) ++ ], + inputSchema: toolJsonSchema(parameters, false), + payloadSchema: toolJsonSchema(options.payload, false), + ...(options._meta === undefined ? {} : { _meta: options._meta }) + }, + isVisible: isEnabled(annotations), + visible: visible("events/list", name), ++ webhooks, ++ decodeArguments: argumentsOf, + poll: poll === undefined ? undefined : (request, invocation) => invoke(Effect.gen(function* () { + const result = yield* poll(yield* argumentsOf(request.arguments), { + cursor: request.cursor, @@ -663,7 +795,8 @@ index 4bf6bca..0973460 100644 + }; + }), invocation, { method: "events/poll", target: name, payload: request }), + stream: stream === undefined ? undefined : (request, invocation, deliver) => invoke(Effect.scoped(Effect.gen(function* () { -+ const subscription = yield* stream(yield* argumentsOf(request.arguments), { ++ const args = request.decoded !== undefined ? request.decoded.value : yield* argumentsOf(request.arguments); ++ const subscription = yield* stream(args, { + cursor: request.cursor, + maxAgeMs: request.maxAgeMs + }); @@ -687,6 +820,54 @@ index 4bf6bca..0973460 100644 +* @since 4.1.4 +*/ +export const event = (options) => Layer.effectDiscard(registerEvent(options)); ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class CallbackRejected extends /*#__PURE__*/Data.TaggedError("CallbackRejected") {} ++/** ++ * Decides which webhook callback URLs may be reached. The default refuses ++ * every URL; see the source for the contract a platform guard keeps. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const CallbackGuard = /*#__PURE__*/Context.Reference("effect/ai/McpServer/CallbackGuard", { ++ defaultValue: () => ({ ++ check: (url) => Effect.fail(new CallbackRejected({ message: `No callback guard admits ${url.host}` })) ++ }) ++}); ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class EventWebhooks extends /*#__PURE__*/Context.Service()("effect/ai/McpServer/EventWebhooks") {} ++const webhooksState = /*#__PURE__*/new WeakMap(); ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const layerEventWebhooks = (options) => Layer.effect(EventWebhooks, Effect.gen(function* () { ++ const webhooks = yield* McpWebhooks.make({ ++ principal: options.principal, ++ guard: yield* CallbackGuard, ++ client: yield* HttpClient.HttpClient ++ }); ++ const service = EventWebhooks.of({ size: webhooks.size }); ++ webhooksState.set(service, webhooks); ++ return service; ++}).pipe(Effect.provide(Layer.mergeAll(Mac.layerWebCrypto, Digest.layerWebCrypto).pipe(Layer.provideMerge(SecureRandom.layerWebCrypto))))); /** * Registers an MCP prompt from an Effect program. * @@ -1029,7 +1210,7 @@ index 0000000..d875046 + } +}, Effect.scoped); diff --git a/dist/ai/internal/mcpProtocol/v2026_07_28.js b/dist/ai/internal/mcpProtocol/v2026_07_28.js -index af1ceed..467dd8a 100644 +index af1ceed..ea29279 100644 --- a/dist/ai/internal/mcpProtocol/v2026_07_28.js +++ b/dist/ai/internal/mcpProtocol/v2026_07_28.js @@ -17,6 +17,7 @@ import * as Schema from "../../../Schema.js"; @@ -1049,25 +1230,31 @@ index af1ceed..467dd8a 100644 /** * @internal */ -@@ -260,6 +261,8 @@ export const makeHandlers = (core, _lifecycle, context) => { +@@ -260,6 +261,10 @@ export const makeHandlers = (core, _lifecycle, context) => { const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult); const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult); const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult); + const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult); + const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult); ++ const decodeSubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.SubscribeEvents.successSchema); ++ const decodeUnsubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.UnsubscribeEvents.successSchema); const sendNotification = context.sendNotification; const supportsSubscriptions = sendNotification !== undefined; // Older adapters accept arbitrary JSON; this binding requires extension settings objects. -@@ -277,7 +280,7 @@ export const makeHandlers = (core, _lifecycle, context) => { +@@ -277,8 +282,11 @@ export const makeHandlers = (core, _lifecycle, context) => { completions: {}, logging: {} }; - const declared = McpSkills.declareExtension(extensions, presence.skills); + const declared = McpEvents.declareExtension(McpSkills.declareExtension(extensions, presence.skills), presence.events); if (declared !== undefined) capabilities.extensions = declared; ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They look for a top-level `events` capability instead of the extension. ++ if (presence.events) capabilities.events = {}; if (presence.tools) capabilities.tools = { listChanged: supportsSubscriptions -@@ -297,6 +300,20 @@ export const makeHandlers = (core, _lifecycle, context) => { + }; +@@ -297,6 +305,26 @@ export const makeHandlers = (core, _lifecycle, context) => { serverInfo: context.serverInfo }; }); @@ -1079,16 +1266,22 @@ index af1ceed..467dd8a 100644 + yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers); + } + }); -+ // Webhook delivery is not implemented, so subscribing refuses every event type. -+ const refuseWebhook = Effect.fnUntraced(function* (method, name) { ++ // Webhook delivery runs the event's push stream, so it needs both. ++ const webhookRegistration = Effect.fnUntraced(function* (method, name, args) { + yield* requireEvents(method); -+ yield* core.events.get(name, yield* getInvocation); -+ return yield* McpEvents.unsupportedDelivery("webhook"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(name, invocation); ++ const { stream, webhooks } = registration; ++ if (webhooks === undefined || stream === undefined) { ++ return yield* McpEvents.unsupportedDelivery("webhook"); ++ } ++ yield* validateEventHeaders(registration, args); ++ return { invocation, stream, webhooks, decodeArguments: registration.decodeArguments }; + }); const requireSkills = method => McpSkills.requireSkills(core, method).pipe(Effect.catch(error => failWithHttpStatus(404, error))); const getInvocation = PublicMcpSchema.McpRequestContext.useSync(McpProtocol.invocationFromRequestContext); const getInputInvocation = Effect.fnUntraced(function* (request) { -@@ -592,6 +609,77 @@ export const makeHandlers = (core, _lifecycle, context) => { +@@ -592,6 +620,97 @@ export const makeHandlers = (core, _lifecycle, context) => { }, context.serverInfo); return yield* decodeReadResourceDirectoryResult(result); }, Effect.mapError(projectError)), @@ -1158,15 +1351,35 @@ index af1ceed..467dd8a 100644 + }); + }, Effect.mapError(projectError)), + "events/subscribe": Effect.fnUntraced(function* (request) { -+ return yield* refuseWebhook("events/subscribe", request.name); ++ const { decodeArguments, invocation, stream, webhooks } = yield* webhookRegistration("events/subscribe", request.name, request.arguments); ++ const args = request.arguments ?? {}; ++ const cursor = request.cursor ?? null; ++ const subscribed = yield* webhooks.subscribe({ ++ name: request.name, ++ arguments: args, ++ delivery: request.delivery, ++ cursor, ++ ttlMs: request.ttlMs, ++ decode: decodeArguments(args), ++ open: (decoded, deliver) => stream({ arguments: args, decoded: { value: decoded }, cursor, maxAgeMs: request.maxAgeMs }, invocation, deliver) ++ }); ++ const result = yield* projectCompleteResult(omitUndefined({ ...subscribed }), context.serverInfo); ++ return yield* decodeSubscribeEventsResult(result); + }, Effect.mapError(projectError)), + "events/unsubscribe": Effect.fnUntraced(function* (request) { -+ return yield* refuseWebhook("events/unsubscribe", request.name); ++ const { webhooks } = yield* webhookRegistration("events/unsubscribe", request.name, request.arguments); ++ yield* webhooks.unsubscribe({ ++ name: request.name, ++ arguments: request.arguments ?? {}, ++ delivery: request.delivery ++ }); ++ const result = yield* projectCompleteResult({}, context.serverInfo); ++ return yield* decodeUnsubscribeEventsResult(result); + }, Effect.mapError(projectError)), "notifications/cancelled": Effect.fnUntraced(function* (_request) { return yield* Effect.void; }) -@@ -613,10 +701,10 @@ const runtime = { +@@ -613,10 +732,10 @@ const runtime = { export const protocol = /*#__PURE__*/McpProtocol.make({ protocolVersion: McpSchema.protocolVersion, runtime, @@ -1180,7 +1393,7 @@ index af1ceed..467dd8a 100644 makeHandlers, toReverseClient: () => ({ diff --git a/dist/ai/internal/mcpRuntime.js b/dist/ai/internal/mcpRuntime.js -index 88238ff..274e513 100644 +index 88238ff..721ff28 100644 --- a/dist/ai/internal/mcpRuntime.js +++ b/dist/ai/internal/mcpRuntime.js @@ -39,6 +39,10 @@ const routingNameKey = method => { @@ -1194,7 +1407,19 @@ index 88238ff..274e513 100644 return "name"; case "resources/read": return "uri"; -@@ -340,7 +344,8 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { +@@ -178,7 +182,10 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { + if (nameKey !== undefined) { + const name = asRecord(inputRecord?.params)?.[nameKey]; + const header = headers[MCP_NAME_HEADER]; +- if (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) { ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They send no Mcp-Name on these; one they do send must still match. ++ const optional = header === undefined && (method === "events/subscribe" || method === "events/unsubscribe"); ++ if (!optional && (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name)) { + return headerMismatch("Mcp-Name header does not match request parameters"); + } + } +@@ -340,7 +347,8 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { return { _tag: "Accepted", acknowledge: !isRequest || !hasId, @@ -1204,6 +1429,475 @@ index 88238ff..274e513 100644 }; }, effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/dist/ai/internal/mcpWebhooks.d.ts b/dist/ai/internal/mcpWebhooks.d.ts +new file mode 100644 +index 0000000..cb0ff5c +--- /dev/null ++++ b/dist/ai/internal/mcpWebhooks.d.ts +@@ -0,0 +1 @@ ++export {}; +diff --git a/dist/ai/internal/mcpWebhooks.js b/dist/ai/internal/mcpWebhooks.js +new file mode 100644 +index 0000000..4e2871a +--- /dev/null ++++ b/dist/ai/internal/mcpWebhooks.js +@@ -0,0 +1,456 @@ ++import * as Clock from "../../Clock.js"; ++import * as Digest from "../../crypto/Digest.js"; ++import * as Mac from "../../crypto/Mac.js"; ++import * as SecureRandom from "../../crypto/SecureRandom.js"; ++import * as Deferred from "../../Deferred.js"; ++import * as Duration from "../../Duration.js"; ++import * as Effect from "../../Effect.js"; ++import * as Base64 from "../../encoding/Base64.js"; ++import * as Base64Url from "../../encoding/Base64Url.js"; ++import * as Fiber from "../../Fiber.js"; ++import * as FetchHttpClient from "../../http/FetchHttpClient.js"; ++import * as HttpClient from "../../http/HttpClient.js"; ++import * as HttpClientRequest from "../../http/HttpClientRequest.js"; ++import * as Option from "../../Option.js"; ++import * as Result from "../../Result.js"; ++import * as Stream from "../../Stream.js"; ++import * as PublicMcpSchema from "../McpSchema.js"; ++import { wireError } from "./mcpEvents.js"; ++const MINUTE_MS = 6e4; ++const MIN_TTL_MS = MINUTE_MS; ++const MAX_TTL_MS = 60 * MINUTE_MS; ++const DEFAULT_TTL_MS = 15 * MINUTE_MS; ++const MAX_ATTEMPTS = 5; ++const FIRST_RETRY_MS = 3e4; ++const REQUEST_TIMEOUT_MS = 1e4; ++const ROTATION_GRACE_MS = 5 * MINUTE_MS; ++const VERIFIED_FOR_MS = MAX_TTL_MS; ++const FAILED_FOR_MS = 5 * MINUTE_MS; ++const VERIFICATIONS_PER_HOST_PER_MINUTE = 10; ++const MAX_SUBSCRIPTIONS_PER_PRINCIPAL = 100; ++const MAX_CHALLENGE_RESPONSE_BYTES = 8192; ++const SECRET_PREFIX = "whsec_"; ++const invalid = (message) => new PublicMcpSchema.InvalidParams({ message }); ++const grantTtl = (suggested) => suggested === void 0 ? DEFAULT_TTL_MS : suggested === null ? MAX_TTL_MS : Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, suggested)); ++const canonicalJson = (value) => { ++ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; ++ if (typeof value === "object" && value !== null) { ++ const entries = Object.entries(value).filter(([, entry]) => entry !== void 0); ++ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); ++ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`; ++ } ++ return JSON.stringify(value) ?? "null"; ++}; ++const encoder = new TextEncoder(); ++const parseUrl = (value, guard) => { ++ if (typeof value !== "string") return Effect.fail(invalid("delivery.url is required")); ++ let url; ++ try { ++ url = new URL(value); ++ } catch { ++ return Effect.fail(invalid("delivery.url is not a valid URL")); ++ } ++ if (url.protocol !== "https:" && !(url.protocol === "http:" && guard.allowsPlaintext?.(url) === true)) { ++ return Effect.fail(invalid("delivery.url must use https")); ++ } ++ if (url.username !== "" || url.password !== "") { ++ return Effect.fail(invalid("delivery.url must not carry credentials")); ++ } ++ url.hash = ""; ++ return Effect.succeed(url); ++}; ++const parseSecret = (value) => { ++ const fail = Effect.fail(invalid("delivery.secret must be whsec_ and the base64 of 24 to 64 random bytes")); ++ if (typeof value !== "string" || !value.startsWith(SECRET_PREFIX)) return fail; ++ const bytes = Base64.decode(value.slice(SECRET_PREFIX.length)); ++ if (Result.isFailure(bytes) || bytes.success.length < 24 || bytes.success.length > 64) return fail; ++ return Mac.key(Mac.hmacSha256, bytes.success).pipe(Effect.orDie, Effect.map((key) => ({ text: value, key }))); ++}; ++const statusCategory = (status) => status >= 500 ? "http_5xx" : "http_4xx"; ++const transportCategory = (error) => { ++ let current = error; ++ for (let depth = 0; depth < 8 && typeof current === "object" && current !== null; depth++) { ++ const code = current.code; ++ if (typeof code === "string" && /CERT|TLS|SSL/.test(code)) return "tls_error"; ++ current = current.cause ?? current.reason; ++ } ++ return "connection_refused"; ++}; ++const readCapped = (response) => Effect.suspend(() => { ++ const chunks = []; ++ let total = 0; ++ let oversized = false; ++ return response.stream.pipe( ++ Stream.takeWhile((chunk) => { ++ if (total + chunk.length > MAX_CHALLENGE_RESPONSE_BYTES) { ++ oversized = true; ++ return false; ++ } ++ total += chunk.length; ++ chunks.push(chunk); ++ return true; ++ }), ++ Stream.runDrain, ++ Effect.map(() => { ++ if (oversized) return void 0; ++ const bytes = new Uint8Array(total); ++ let offset = 0; ++ for (const chunk of chunks) { ++ bytes.set(chunk, offset); ++ offset += chunk.length; ++ } ++ return new TextDecoder().decode(bytes); ++ }) ++ ); ++}); ++const echoedChallenge = (body) => { ++ try { ++ const parsed = JSON.parse(body); ++ const challenge = typeof parsed === "object" && parsed !== null ? parsed.challenge : void 0; ++ return typeof challenge === "string" ? challenge : void 0; ++ } catch { ++ return void 0; ++ } ++}; ++const callbackError = (category) => new PublicMcpSchema.CallbackEndpointError({ ++ message: `The callback endpoint failed verification: ${category}`, ++ data: { reason: category } ++}); ++const iso = (millis) => new Date(millis).toISOString(); ++const make = Effect.fnUntraced(function* (options) { ++ const scope = yield* Effect.scope; ++ const mac = yield* Mac.Mac; ++ const digest = yield* Digest.Digest; ++ const random = yield* SecureRandom.SecureRandom; ++ const { guard } = options; ++ const client = HttpClient.withScope(options.client); ++ const subscriptions = /* @__PURE__ */ new Map(); ++ const pending = /* @__PURE__ */ new Map(); ++ const verified = /* @__PURE__ */ new Map(); ++ const failedVerifications = /* @__PURE__ */ new Map(); ++ const verifying = /* @__PURE__ */ new Map(); ++ const verificationsByHost = /* @__PURE__ */ new Map(); ++ const forget = (subscription) => { ++ if (subscriptions.get(subscription.id) === subscription) subscriptions.delete(subscription.id); ++ }; ++ const subscriptionId = (principal, url, name, args) => digest.digestHex(Digest.sha256, encoder.encode(canonicalJson([principal, url.href, name, args]))).pipe( ++ Effect.map((hex) => `sub_${hex.slice(0, 32)}`) ++ ); ++ const messageId = (prefix) => Effect.map(random.randomBytes(18), (bytes) => `${prefix}_${Base64Url.encode(bytes)}`); ++ const deliveryId = (subscription, eventId) => Effect.map( ++ digest.digest(Digest.sha256, encoder.encode(`${subscription.id}\0${eventId}`)), ++ (hash) => `evt_${Base64Url.encode(hash).slice(0, 22)}` ++ ); ++ const MAX_CURSORS_SINCE_GAP = 1024; ++ const advance = (subscription, cursor) => { ++ subscription.watermark = cursor; ++ const since = subscription.cursorsSinceGap; ++ if (since === void 0) return; ++ since.add(cursor); ++ if (since.size > MAX_CURSORS_SINCE_GAP) since.delete(since.values().next().value); ++ }; ++ const sign = (keys, webhookId, timestamp, body) => Effect.forEach(keys, (key) => mac.sign(key, encoder.encode(`${webhookId}.${timestamp}.${body}`))).pipe( ++ Effect.orDie, ++ Effect.map((tags) => tags.map((tag) => `v1,${Base64.encode(tag)}`).join(" ")) ++ ); ++ const send = Effect.fnUntraced(function* (subscription, body, webhookId, readBody) { ++ const admitted = yield* Effect.result(guard.check(subscription.url)); ++ if (Result.isFailure(admitted)) { ++ return { _tag: "Failed", category: "connection_refused", retryable: true }; ++ } ++ const now = yield* Clock.currentTimeMillis; ++ const timestamp = Math.floor(now / 1e3); ++ const previous = subscription.previous; ++ const keys = previous !== void 0 && now < previous.until ? [subscription.key, previous.key] : [subscription.key]; ++ const request = HttpClientRequest.post(subscription.url).pipe( ++ HttpClientRequest.setHeaders({ ++ "webhook-id": webhookId, ++ "webhook-timestamp": String(timestamp), ++ "webhook-signature": yield* sign(keys, webhookId, timestamp, body), ++ "x-mcp-subscription-id": subscription.id ++ }), ++ HttpClientRequest.bodyText(body, "application/json") ++ ); ++ const outcome = yield* client.execute(request).pipe( ++ Effect.flatMap((response) => { ++ if (response.status < 200 || response.status >= 300) { ++ return Effect.succeed({ ++ _tag: "Failed", ++ category: statusCategory(response.status), ++ retryable: response.status !== 410 && response.status !== 413 ++ }); ++ } ++ return readBody ? Effect.map(readCapped(response), (text) => ({ _tag: "Delivered", body: text })) : Effect.succeed({ _tag: "Delivered", body: void 0 }); ++ }), ++ Effect.timeoutOption(Duration.millis(REQUEST_TIMEOUT_MS)), ++ Effect.scoped, ++ // `fetch` would follow a redirect itself; webhook delivery never does. ++ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), ++ // Trace ids stay inside: the endpoint belongs to someone else. ++ Effect.provideService(HttpClient.TracerPropagationEnabled, false), ++ Effect.catch( ++ (error) => Effect.succeed(Option.some({ _tag: "Failed", category: transportCategory(error), retryable: true })) ++ ) ++ ); ++ return Option.getOrElse(outcome, () => ({ _tag: "Failed", category: "timeout", retryable: true })); ++ }); ++ const deliver = Effect.fnUntraced(function* (subscription, body, webhookId) { ++ for (let attempt = 1; ; attempt++) { ++ const current = subscriptions.get(subscription.id); ++ if (current !== void 0 && current !== subscription) return false; ++ const startedAt = yield* Clock.currentTimeMillis; ++ const outcome = yield* send(subscription, body, webhookId, false); ++ if (outcome._tag === "Delivered") { ++ subscription.lastDeliveryAt = yield* Clock.currentTimeMillis; ++ subscription.lastError = void 0; ++ return true; ++ } ++ subscription.lastError = outcome.category; ++ if (!outcome.retryable || attempt >= MAX_ATTEMPTS) return false; ++ const wait = startedAt + FIRST_RETRY_MS * 2 ** (attempt - 1) - (yield* Clock.currentTimeMillis); ++ if (wait > 0) yield* Effect.sleep(Duration.millis(wait)); ++ } ++ }); ++ const control = (subscription, type, fields) => Effect.flatMap( ++ messageId(`msg_${type}`), ++ (webhookId) => deliver(subscription, JSON.stringify({ type, ...fields }), webhookId) ++ ); ++ const run = (subscription, name, events) => events.items.pipe( ++ Stream.runForEach((item) => { ++ switch (item._tag) { ++ case "Event": ++ return Effect.flatMap(deliveryId(subscription, item.eventId), (webhookId) => { ++ const body = JSON.stringify({ ++ eventId: webhookId, ++ name, ++ timestamp: item.timestamp, ++ data: item.data, ++ cursor: item.cursor, ++ ...item._meta === void 0 ? {} : { _meta: item._meta } ++ }); ++ return deliver(subscription, body, webhookId); ++ }).pipe(Effect.andThen(Effect.sync(() => advance(subscription, item.cursor)))); ++ case "Position": ++ return Effect.sync(() => advance(subscription, item.cursor)); ++ case "Gap": ++ return control(subscription, "gap", { cursor: item.cursor }).pipe( ++ Effect.map((delivered) => { ++ if (!delivered) subscription.cursorsSinceGap = /* @__PURE__ */ new Set(); ++ advance(subscription, item.cursor); ++ }) ++ ); ++ case "Error": ++ return Effect.void; ++ } ++ }), ++ // Ended before it says so, so a refresh meanwhile starts afresh instead of reporting it live. ++ Effect.catch( ++ (failure) => Effect.suspend(() => { ++ forget(subscription); ++ return control(subscription, "terminated", { error: wireError(failure) }); ++ }) ++ ) ++ ); ++ const expiry = (subscription) => Effect.gen(function* () { ++ while (true) { ++ const left = subscription.expiresAt - (yield* Clock.currentTimeMillis); ++ if (left <= 0) return forget(subscription); ++ yield* Effect.raceFirst(Effect.sleep(Duration.millis(left)), Deferred.await(subscription.deadlineMoved)); ++ } ++ }); ++ const handshake = Effect.fnUntraced(function* (subscription) { ++ const challenge = Base64Url.encode(yield* random.randomBytes(32)); ++ const outcome = yield* send( ++ subscription, ++ JSON.stringify({ type: "verification", challenge }), ++ yield* messageId("msg_verification"), ++ true ++ ); ++ if (outcome._tag === "Failed") return yield* Effect.fail(outcome.category); ++ const echoed = outcome.body === void 0 ? void 0 : echoedChallenge(outcome.body); ++ if (echoed === void 0 || !Mac.timingSafeEqual(encoder.encode(echoed), encoder.encode(challenge))) { ++ return yield* Effect.fail("challenge_failed"); ++ } ++ }); ++ const verify = Effect.fnUntraced(function* (subscription) { ++ const key = JSON.stringify([subscription.principal, subscription.url.href]); ++ const now = yield* Clock.currentTimeMillis; ++ for (const [entry, until] of verified) if (until <= now) verified.delete(entry); ++ for (const [entry, failure2] of failedVerifications) if (failure2.until <= now) failedVerifications.delete(entry); ++ if (verified.has(key)) return; ++ const failure = failedVerifications.get(key); ++ if (failure !== void 0) return yield* callbackError(failure.category); ++ const inFlight = verifying.get(key); ++ if (inFlight !== void 0) return yield* Deferred.await(inFlight); ++ const host = subscription.url.hostname; ++ const recent = (verificationsByHost.get(host) ?? []).filter((at) => at > now - MINUTE_MS); ++ if (recent.length >= VERIFICATIONS_PER_HOST_PER_MINUTE) { ++ verificationsByHost.set(host, recent); ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many callback verifications for this host", ++ data: { limit: "verifications", max: VERIFICATIONS_PER_HOST_PER_MINUTE } ++ }); ++ } ++ for (const [entry, times] of verificationsByHost) { ++ if (times.every((at) => at <= now - MINUTE_MS)) verificationsByHost.delete(entry); ++ } ++ verificationsByHost.set(host, [...recent, now]); ++ const done = Deferred.makeUnsafe(); ++ verifying.set(key, done); ++ return yield* handshake(subscription).pipe( ++ Effect.tap( ++ () => Effect.map(Clock.currentTimeMillis, (at) => { ++ verified.set(key, at + VERIFIED_FOR_MS); ++ }) ++ ), ++ Effect.tapError( ++ (category) => Effect.map(Clock.currentTimeMillis, (at) => { ++ failedVerifications.set(key, { until: at + FAILED_FOR_MS, category }); ++ }) ++ ), ++ Effect.mapError(callbackError), ++ Effect.onExit( ++ (exit) => Effect.sync(() => { ++ verifying.delete(key); ++ Deferred.doneUnsafe(done, exit); ++ }) ++ ) ++ ); ++ }); ++ const refresh = Effect.fnUntraced(function* (request, subscription, secret, expiresAt, now) { ++ const opening = !Deferred.isDoneUnsafe(subscription.accepted); ++ const start = yield* Deferred.await(subscription.accepted); ++ if (subscriptions.get(subscription.id) !== subscription) return yield* subscribe(request); ++ if (subscription.secret !== secret.text) { ++ subscription.previous = { key: subscription.key, until: now + ROTATION_GRACE_MS }; ++ subscription.secret = secret.text; ++ subscription.key = secret.key; ++ } ++ subscription.expiresAt = expiresAt; ++ const moved = subscription.deadlineMoved; ++ subscription.deadlineMoved = Deferred.makeUnsafe(); ++ Deferred.doneUnsafe(moved, Effect.void); ++ if (opening) return { id: subscription.id, refreshBefore: iso(expiresAt), ...start }; ++ const since = subscription.cursorsSinceGap; ++ if (since !== void 0 && since.has(request.cursor)) subscription.cursorsSinceGap = void 0; ++ const truncated = subscription.cursorsSinceGap !== void 0; ++ return { ++ id: subscription.id, ++ refreshBefore: iso(expiresAt), ++ cursor: subscription.watermark, ++ truncated, ++ deliveryStatus: { ++ active: true, ++ lastDeliveryAt: subscription.lastDeliveryAt === void 0 ? null : iso(subscription.lastDeliveryAt), ++ lastError: subscription.lastError ?? null ++ } ++ }; ++ }); ++ const subscribe = Effect.fnUntraced(function* (request) { ++ const principal = yield* options.principal; ++ const mode = request.delivery.mode; ++ if (mode !== void 0 && mode !== "webhook") return yield* invalid("delivery.mode must be 'webhook'"); ++ const url = yield* parseUrl(request.delivery.url, guard); ++ const secret = yield* parseSecret(request.delivery.secret); ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments); ++ const now = yield* Clock.currentTimeMillis; ++ const expiresAt = now + grantTtl(request.ttlMs); ++ const live = subscriptions.get(id); ++ if (live !== void 0) return yield* refresh(request, live, secret, expiresAt, now); ++ let held = pending.get(principal) ?? 0; ++ for (const subscription of subscriptions.values()) if (subscription.principal === principal) held++; ++ if (held >= MAX_SUBSCRIPTIONS_PER_PRINCIPAL) { ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many webhook subscriptions", ++ data: { limit: "subscriptions", max: MAX_SUBSCRIPTIONS_PER_PRINCIPAL } ++ }); ++ } ++ pending.set(principal, (pending.get(principal) ?? 0) + 1); ++ let reserved = true; ++ const release = () => { ++ if (!reserved) return; ++ reserved = false; ++ const left = (pending.get(principal) ?? 1) - 1; ++ if (left === 0) pending.delete(principal); ++ else pending.set(principal, left); ++ }; ++ return yield* create(request, { principal, url, secret, id, expiresAt, now, release }).pipe( ++ Effect.ensuring(Effect.sync(release)) ++ ); ++ }); ++ const create = Effect.fnUntraced(function* (request, { expiresAt, id, now, principal, release, secret, url }) { ++ yield* Effect.mapError(guard.check(url), () => invalid("delivery.url is not allowed")); ++ const subscription = { ++ id, ++ principal, ++ url, ++ secret: secret.text, ++ key: secret.key, ++ previous: void 0, ++ expiresAt, ++ watermark: request.cursor, ++ lastDeliveryAt: void 0, ++ lastError: void 0, ++ fiber: void 0, ++ deadlineMoved: Deferred.makeUnsafe(), ++ accepted: Deferred.makeUnsafe(), ++ cursorsSinceGap: void 0 ++ }; ++ const decoded = yield* request.decode; ++ yield* verify(subscription); ++ const raced = subscriptions.get(id); ++ if (raced !== void 0) { ++ release(); ++ return yield* refresh(request, raced, secret, expiresAt, now); ++ } ++ release(); ++ subscriptions.set(id, subscription); ++ const { accepted } = subscription; ++ const lifetime = request.open( ++ decoded, ++ (events) => Effect.suspend(() => { ++ subscription.watermark = events.cursor; ++ return Deferred.succeed(accepted, { cursor: events.cursor, truncated: events.truncated }); ++ }).pipe(Effect.andThen(run(subscription, request.name, events))) ++ ).pipe( ++ Effect.tapError((failure) => Deferred.fail(accepted, failure)), ++ Effect.raceFirst(expiry(subscription)), ++ Effect.ignore, ++ Effect.ensuring(Effect.suspend(() => { ++ forget(subscription); ++ return Deferred.fail(accepted, new PublicMcpSchema.InternalError({ message: "The subscription ended" })); ++ })) ++ ); ++ subscription.fiber = yield* Effect.forkIn(lifetime, scope); ++ const start = yield* Deferred.await(accepted); ++ return { id, refreshBefore: iso(expiresAt), cursor: start.cursor, truncated: start.truncated }; ++ }); ++ const unsubscribe = Effect.fnUntraced(function* (request) { ++ const principal = yield* options.principal; ++ const url = yield* parseUrl(request.delivery.url, guard); ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments); ++ const subscription = subscriptions.get(id); ++ if (subscription === void 0) { ++ return yield* new PublicMcpSchema.NotFound({ ++ message: "No webhook subscription matches", ++ data: { kind: "subscription" } ++ }); ++ } ++ subscriptions.delete(id); ++ if (subscription.fiber !== void 0) yield* Fiber.interrupt(subscription.fiber); ++ }); ++ return { ++ subscribe, ++ unsubscribe, ++ size: Effect.sync(() => subscriptions.size) ++ }; ++}); ++export { ++ DEFAULT_TTL_MS, ++ MAX_ATTEMPTS, ++ MAX_TTL_MS, ++ MIN_TTL_MS, ++ canonicalJson, ++ grantTtl, ++ make ++}; diff --git a/src/ai/McpSchema.ts b/src/ai/McpSchema.ts index ba6c830..1e58fb9 100644 --- a/src/ai/McpSchema.ts @@ -1419,10 +2113,35 @@ index ba6c830..1e58fb9 100644 // Prompts // ============================================================================= diff --git a/src/ai/McpServer.ts b/src/ai/McpServer.ts -index 4c2e191..3bf4321 100644 +index 4c2e191..bedd064 100644 --- a/src/ai/McpServer.ts +++ b/src/ai/McpServer.ts -@@ -344,6 +344,9 @@ export type MiddlewareMethod = +@@ -16,6 +16,8 @@ import * as Cause from "../Cause.ts" + import * as Clock from "../Clock.ts" + import * as Context from "../Context.ts" + import * as Digest from "../crypto/Digest.ts" ++import * as Mac from "../crypto/Mac.ts" ++import * as SecureRandom from "../crypto/SecureRandom.ts" + import * as Data from "../Data.ts" + import * as Deferred from "../Deferred.ts" + import * as Duration from "../Duration.ts" +@@ -26,6 +28,7 @@ import * as Exit from "../Exit.ts" + import * as Fiber from "../Fiber.ts" + import * as FindMyWay from "../http/FindMyWay.ts" + import * as Headers from "../http/Headers.ts" ++import * as HttpClient from "../http/HttpClient.ts" + import { appendPreResponseHandlerUnsafe } from "../http/HttpEffect.ts" + import * as HttpRouter from "../http/HttpRouter.ts" + import * as HttpServerRequest from "../http/HttpServerRequest.ts" +@@ -59,6 +62,7 @@ import * as McpCore from "./internal/mcpCore.ts" + import * as McpProtocolInternal from "./internal/mcpProtocol.ts" + import * as McpRuntime from "./internal/mcpRuntime.ts" + import * as McpSkills from "./internal/mcpSkills.ts" ++import * as McpWebhooks from "./internal/mcpWebhooks.ts" + import * as InternalStructuredOutput from "./internal/structured-output.ts" + import type * as McpProtocol from "./McpProtocol.ts" + import * as McpSchema from "./McpSchema.ts" +@@ -344,6 +348,9 @@ export type MiddlewareMethod = | "skills/list" | "skills/get" | "resources/directory/read" @@ -1432,7 +2151,7 @@ index 4c2e191..3bf4321 100644 /** * Request metadata passed to MCP middleware. -@@ -819,7 +822,14 @@ const internalError = new InternalError({ message: "Internal error" }) +@@ -819,7 +826,14 @@ const internalError = new InternalError({ message: "Internal error" }) const rejectWith = (error: McpErrorBase) => Effect.fail(new McpCore.RequestRejected({ code: error.code, message: error.message, data: error.data, error })) @@ -1448,7 +2167,7 @@ index 4c2e191..3bf4321 100644 type ListMethod = Exclude -@@ -829,6 +839,8 @@ interface NotFoundErrors { +@@ -829,6 +843,8 @@ interface NotFoundErrors { readonly "prompts/get": McpCore.PromptNotFound readonly "completion/complete": InvalidParams readonly "skills/get": McpCore.SkillNotFound @@ -1457,7 +2176,7 @@ index 4c2e191..3bf4321 100644 } const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod] => { -@@ -843,6 +855,9 @@ const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod +@@ -843,6 +859,9 @@ const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod return new InvalidParams({ message: "Unknown completion reference or argument" }) case "skills/get": return new McpCore.SkillNotFound({ uri: target }) @@ -1467,7 +2186,7 @@ index 4c2e191..3bf4321 100644 } } -@@ -4134,6 +4149,276 @@ export const registerSkill: (options: SkillOptions) => Effect.Effect Effect.Effect => Layer.effectDiscard(registerSkill(options)) @@ -1589,8 +2308,8 @@ index 4c2e191..3bf4321 100644 + * `parameters` types the subscription arguments, an empty object by default, + * and `payload` the occurrences' `data`; both are advertised as JSON Schema + * by `events/list`. `poll` offers poll delivery and `stream` push delivery, -+ * and at least one is required. Webhook delivery is not supported, so -+ * `events/subscribe` answers `Unsupported`. ++ * and at least one is required. With {@link EventWebhooks} provided where the ++ * event is registered, `stream` also backs webhook delivery. + * + * @stability unstable + * @category events @@ -1626,7 +2345,8 @@ index 4c2e191..3bf4321 100644 + * + * The server declares `io.modelcontextprotocol/events` on revision + * `2026-07-28` once any event type is registered, and answers `events/list`, -+ * `events/poll` and `events/stream`. A push stream runs `stream` for its ++ * `events/poll`, `events/stream`, and with {@link EventWebhooks} ++ * `events/subscribe` and `events/unsubscribe`. A push stream runs `stream` for its + * lifetime inside the request's middleware, sends heartbeats carrying the + * last cursor, and ends when the client goes away. Services read by `poll` + * and `stream` are request-level, as for tools. @@ -1650,6 +2370,9 @@ index 4c2e191..3bf4321 100644 + const services = yield* Effect.context() + const annotations = options.annotations ?? Context.empty() + const { invoke, visible } = makeInvoke(services, globalMiddleware) ++ const webhooks = stream === undefined ++ ? undefined ++ : Option.getOrUndefined(Option.map(Context.getOption(services, EventWebhooks), (service) => webhooksState.get(service))) + const parameters = options.parameters ?? Schema.Struct({}) + const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)) + const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)) @@ -1670,13 +2393,19 @@ index 4c2e191..3bf4321 100644 + descriptor: { + name, + ...(options.description === undefined ? {} : { description: options.description }), -+ delivery: [...(poll === undefined ? [] : ["poll" as const]), ...(stream === undefined ? [] : ["push" as const])], ++ delivery: [ ++ ...(poll === undefined ? [] : ["poll" as const]), ++ ...(stream === undefined ? [] : ["push" as const]), ++ ...(webhooks === undefined ? [] : ["webhook" as const]) ++ ], + inputSchema: toolJsonSchema(parameters, false) as Record, + payloadSchema: toolJsonSchema(options.payload, false) as Record, + ...(options._meta === undefined ? {} : { _meta: options._meta }) + }, + isVisible: isEnabled(annotations), + visible: visible("events/list", name), ++ webhooks, ++ decodeArguments: argumentsOf, + poll: poll === undefined ? undefined : (request, invocation) => + invoke( + Effect.gen(function*() { @@ -1699,7 +2428,10 @@ index 4c2e191..3bf4321 100644 + stream: stream === undefined ? undefined : (request, invocation, deliver) => + invoke( + Effect.scoped(Effect.gen(function*() { -+ const subscription = yield* stream(yield* argumentsOf(request.arguments), { ++ const args = request.decoded !== undefined ++ ? request.decoded.value ++ : yield* argumentsOf(request.arguments) ++ const subscription = yield* stream(args, { + cursor: request.cursor, + maxAgeMs: request.maxAgeMs + }) @@ -1740,23 +2472,139 @@ index 4c2e191..3bf4321 100644 + R = never +>(options: EventOptions): Layer.Layer> => + Layer.effectDiscard(registerEvent(options)) ++ ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class CallbackRejected extends Data.TaggedError("CallbackRejected")<{ ++ readonly message: string ++}> {} ++ ++/** ++ * Decides which webhook callback URLs may be reached. ++ * ++ * **Details** ++ * ++ * `check` runs when a subscription is created and again before every POST. ++ * Resolving a host name needs the platform, so the default refuses every URL: ++ * a server that offers webhooks provides a guard that resolves the host and ++ * refuses addresses that are not globally routable. That check alone cannot ++ * stop DNS rebinding, so the `HttpClient` given to {@link layerEventWebhooks} ++ * must connect only to the address it validated, sending the original host ++ * name in `Host` and TLS SNI, and must not follow redirects. `allowsPlaintext` ++ * admits an `http:` URL, which only a local test setup should do. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const CallbackGuard = Context.Reference<{ ++ readonly check: (url: URL) => Effect.Effect ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined ++}>("effect/ai/McpServer/CallbackGuard", { ++ defaultValue: () => ({ ++ check: (url) => Effect.fail(new CallbackRejected({ message: `No callback guard admits ${url.host}` })) ++ }) ++}) ++ ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * Event types registered with a `stream` where this service is present also ++ * offer webhook delivery. `events/subscribe` validates the callback, verifies ++ * the endpoint with a challenge, and runs the event's `stream` for the ++ * subscription's lifetime, POSTing each occurrence with Standard Webhooks ++ * signatures, one at a time, retrying with backoff. Subscriptions live in ++ * memory: every grant is finite, between a minute and an hour, so a client ++ * refreshing from its cursor recreates what a restart lost. A failure of the ++ * stream, such as `Forbidden` when access is revoked, ends the subscription ++ * with a `terminated` envelope. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class EventWebhooks extends Context.Service ++}>()("effect/ai/McpServer/EventWebhooks") {} ++ ++const webhooksState = new WeakMap() ++ ++/** ++ * Options for {@link layerEventWebhooks}. ++ * ++ * **Details** ++ * ++ * `principal` names the authenticated subject of an `events/subscribe` or ++ * `events/unsubscribe` request, read from the request's services. It fails ++ * with `Forbidden` for a caller that may not subscribe; webhook delivery ++ * requires an authenticated principal. A subscription's identity is its ++ * principal, callback URL, event name and arguments, so the principal must ++ * stay the same across token refreshes. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventWebhooksOptions { ++ readonly principal: Effect.Effect ++} ++ ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const layerEventWebhooks = ( ++ options: EventWebhooksOptions ++): Layer.Layer => ++ Layer.effect( ++ EventWebhooks, ++ Effect.gen(function*() { ++ const webhooks = yield* McpWebhooks.make({ ++ principal: options.principal, ++ guard: yield* CallbackGuard, ++ client: yield* HttpClient.HttpClient ++ }) ++ const service = EventWebhooks.of({ size: webhooks.size }) ++ webhooksState.set(service, webhooks) ++ return service ++ }).pipe( ++ Effect.provide( ++ Layer.mergeAll(Mac.layerWebCrypto, Digest.layerWebCrypto).pipe( ++ Layer.provideMerge(SecureRandom.layerWebCrypto) ++ ) ++ ) ++ ) ++ ) + /** * Registers an MCP prompt from an Effect program. * diff --git a/src/ai/internal/mcpCore.ts b/src/ai/internal/mcpCore.ts -index 643982d..597701f 100644 +index 643982d..d705160 100644 --- a/src/ai/internal/mcpCore.ts +++ b/src/ai/internal/mcpCore.ts -@@ -8,6 +8,7 @@ import * as Data from "../../Data.ts" +@@ -8,6 +8,8 @@ import * as Data from "../../Data.ts" import * as Effect from "../../Effect.ts" import type * as McpProtocol from "../McpProtocol.ts" import * as McpSchema from "../McpSchema.ts" +import type * as Stream from "../../Stream.ts" ++import type * as McpWebhooks from "./mcpWebhooks.ts" /** * @internal -@@ -330,6 +331,118 @@ export interface SkillRegistration { +@@ -330,6 +332,123 @@ export interface SkillRegistration { readonly directory: (uri: string) => ReadonlyArray | undefined } @@ -1810,6 +2658,8 @@ index 643982d..597701f 100644 + */ +export interface EventStreamRequest { + readonly arguments: Readonly> ++ // Set when the arguments were already decoded, as a webhook subscribe does first. ++ readonly decoded?: { readonly value: unknown } | undefined + readonly cursor: string | null + readonly maxAgeMs?: number | undefined +} @@ -1846,6 +2696,9 @@ index 643982d..597701f 100644 + readonly descriptor: McpSchema.EventDescriptor + readonly isVisible: (profile: NegotiatedProtocolProfile) => boolean + readonly visible?: Visible | undefined ++ // Set when webhook delivery is offered, which runs `stream`. ++ readonly webhooks?: McpWebhooks.Webhooks | undefined ++ readonly decodeArguments: (args: unknown) => Effect.Effect + readonly poll?: + | (( + request: EventPollRequest, @@ -1875,7 +2728,7 @@ index 643982d..597701f 100644 /** * @internal */ -@@ -507,11 +620,13 @@ export interface McpCore { +@@ -507,11 +626,13 @@ export interface McpCore { readonly prompts: Prompts readonly completions: Completions readonly skills: Skills @@ -1889,7 +2742,7 @@ index 643982d..597701f 100644 }> } -@@ -523,6 +638,12 @@ export interface McpCore { +@@ -523,6 +644,12 @@ export interface McpCore { */ export type Visible = (invocation: McpInvocation) => Effect.Effect @@ -1902,7 +2755,7 @@ index 643982d..597701f 100644 // Whether one skill directory contains the other, or both are the same. const skillsOverlap = (a: string, b: string): boolean => { const rootA = a.slice(0, -"/SKILL.md".length) -@@ -539,6 +660,7 @@ export const make: Effect.Effect = Effect.sync(() => { +@@ -539,6 +666,7 @@ export const make: Effect.Effect = Effect.sync(() => { const resourceTemplateRegistrations: Array = [] const promptRegistrations = new Map() const skillRegistrations = new Map() @@ -1910,7 +2763,7 @@ index 643982d..597701f 100644 const skillFiles = new Set() const completionRegistrations = new Map< string, -@@ -717,12 +839,28 @@ export const make: Effect.Effect = Effect.sync(() => { +@@ -717,12 +845,28 @@ export const make: Effect.Effect = Effect.sync(() => { }) } @@ -2275,7 +3128,7 @@ index 5393651..f40915b 100644 } diff --git a/src/ai/internal/mcpProtocol/v2026_07_28.ts b/src/ai/internal/mcpProtocol/v2026_07_28.ts -index a701ec8..9b9a6fd 100644 +index a701ec8..8e4b36a 100644 --- a/src/ai/internal/mcpProtocol/v2026_07_28.ts +++ b/src/ai/internal/mcpProtocol/v2026_07_28.ts @@ -22,6 +22,7 @@ import type * as Types from "../../../Types.ts" @@ -2299,16 +3152,18 @@ index a701ec8..9b9a6fd 100644 /** * @internal -@@ -370,6 +375,8 @@ export const makeHandlers = ( +@@ -370,6 +375,10 @@ export const makeHandlers = ( const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult) const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult) const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult) + const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult) + const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult) ++ const decodeSubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.SubscribeEvents.successSchema) ++ const decodeUnsubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.UnsubscribeEvents.successSchema) const sendNotification = context.sendNotification const supportsSubscriptions = sendNotification !== undefined // Older adapters accept arbitrary JSON; this binding requires extension settings objects. -@@ -384,7 +391,10 @@ export const makeHandlers = ( +@@ -384,8 +393,14 @@ export const makeHandlers = ( } const getDiscovery = Effect.map(context.registrationPresence, (presence) => { const capabilities: Types.Mutable = { completions: {}, logging: {} } @@ -2318,9 +3173,13 @@ index a701ec8..9b9a6fd 100644 + presence.events + ) if (declared !== undefined) capabilities.extensions = declared ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They look for a top-level `events` capability instead of the extension. ++ if (presence.events) capabilities.events = {} if (presence.tools) capabilities.tools = { listChanged: supportsSubscriptions } if (presence.resources) { -@@ -393,6 +403,24 @@ export const makeHandlers = ( + capabilities.resources = { listChanged: supportsSubscriptions, subscribe: supportsSubscriptions } +@@ -393,6 +408,30 @@ export const makeHandlers = ( if (presence.prompts) capabilities.prompts = { listChanged: supportsSubscriptions } return { supportedVersions: context.supportedVersions, capabilities, serverInfo: context.serverInfo } }) @@ -2336,16 +3195,22 @@ index a701ec8..9b9a6fd 100644 + yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers) + } + }) -+ // Webhook delivery is not implemented, so subscribing refuses every event type. -+ const refuseWebhook = Effect.fnUntraced(function*(method: string, name: string) { ++ // Webhook delivery runs the event's push stream, so it needs both. ++ const webhookRegistration = Effect.fnUntraced(function*(method: string, name: string, args: unknown) { + yield* requireEvents(method) -+ yield* core.events.get(name, yield* getInvocation) -+ return yield* McpEvents.unsupportedDelivery("webhook") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(name, invocation) ++ const { stream, webhooks } = registration ++ if (webhooks === undefined || stream === undefined) { ++ return yield* McpEvents.unsupportedDelivery("webhook") ++ } ++ yield* validateEventHeaders(registration, args) ++ return { invocation, stream, webhooks, decodeArguments: registration.decodeArguments } + }) const requireSkills = (method: string) => McpSkills.requireSkills(core, method).pipe( Effect.catch((error) => failWithHttpStatus(404, error)) -@@ -728,6 +756,92 @@ export const makeHandlers = ( +@@ -728,6 +767,121 @@ export const makeHandlers = ( const result = yield* projectCompleteResult({ ...cacheHint("skills"), resources }, context.serverInfo) return yield* decodeReadResourceDirectoryResult(result) }, Effect.mapError(projectError)), @@ -2428,17 +3293,46 @@ index a701ec8..9b9a6fd 100644 + }) + }, Effect.mapError(projectError)), + "events/subscribe": Effect.fnUntraced(function*(request: typeof McpEvents.SubscribeEvents.payloadSchema.Type) { -+ return yield* refuseWebhook("events/subscribe", request.name) ++ const { decodeArguments, invocation, stream, webhooks } = yield* webhookRegistration( ++ "events/subscribe", ++ request.name, ++ request.arguments ++ ) ++ const args = request.arguments ?? {} ++ const cursor = request.cursor ?? null ++ const subscribed = yield* webhooks.subscribe({ ++ name: request.name, ++ arguments: args, ++ delivery: request.delivery, ++ cursor, ++ ttlMs: request.ttlMs, ++ decode: decodeArguments(args), ++ open: (decoded, deliver) => ++ stream( ++ { arguments: args, decoded: { value: decoded }, cursor, maxAgeMs: request.maxAgeMs }, ++ invocation, ++ deliver ++ ) ++ }) ++ const result = yield* projectCompleteResult(omitUndefined({ ...subscribed }), context.serverInfo) ++ return yield* decodeSubscribeEventsResult(result) + }, Effect.mapError(projectError)), + "events/unsubscribe": Effect.fnUntraced(function*( + request: typeof McpEvents.UnsubscribeEvents.payloadSchema.Type + ) { -+ return yield* refuseWebhook("events/unsubscribe", request.name) ++ const { webhooks } = yield* webhookRegistration("events/unsubscribe", request.name, request.arguments) ++ yield* webhooks.unsubscribe({ ++ name: request.name, ++ arguments: request.arguments ?? {}, ++ delivery: request.delivery ++ }) ++ const result = yield* projectCompleteResult({}, context.serverInfo) ++ return yield* decodeUnsubscribeEventsResult(result) + }, Effect.mapError(projectError)), "notifications/cancelled": Effect.fnUntraced(function*( _request: typeof McpSchema.CancelledNotification.payloadSchema.Type ) { -@@ -751,10 +865,10 @@ const runtime = { +@@ -751,10 +905,10 @@ const runtime = { export const protocol = McpProtocol.make({ protocolVersion: McpSchema.protocolVersion, runtime, @@ -2452,7 +3346,7 @@ index a701ec8..9b9a6fd 100644 makeHandlers, toReverseClient: () => ({ diff --git a/src/ai/internal/mcpRuntime.ts b/src/ai/internal/mcpRuntime.ts -index 9d4c96e..eb0590c 100644 +index 9d4c96e..0afe3ed 100644 --- a/src/ai/internal/mcpRuntime.ts +++ b/src/ai/internal/mcpRuntime.ts @@ -53,6 +53,10 @@ const routingNameKey = (method: string): "name" | "uri" | undefined => { @@ -2466,7 +3360,22 @@ index 9d4c96e..eb0590c 100644 return "name" case "resources/read": return "uri" -@@ -479,7 +483,9 @@ export const make = Effect.fnUntraced(function*( +@@ -319,7 +323,13 @@ export const make = Effect.fnUntraced(function*( + if (nameKey !== undefined) { + const name = asRecord(inputRecord?.params)?.[nameKey] + const header = headers[MCP_NAME_HEADER] +- if (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) { ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They send no Mcp-Name on these; one they do send must still match. ++ const optional = header === undefined && (method === "events/subscribe" || method === "events/unsubscribe") ++ if ( ++ !optional && ++ (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) ++ ) { + return headerMismatch("Mcp-Name header does not match request parameters") + } + } +@@ -479,7 +489,9 @@ export const make = Effect.fnUntraced(function*( return { _tag: "Accepted", acknowledge: !isRequest || !hasId, @@ -2477,3 +3386,701 @@ index 9d4c96e..eb0590c 100644 } }, effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/src/ai/internal/mcpWebhooks.ts b/src/ai/internal/mcpWebhooks.ts +new file mode 100644 +index 0000000..5b53d08 +--- /dev/null ++++ b/src/ai/internal/mcpWebhooks.ts +@@ -0,0 +1,692 @@ ++/** ++ * Webhook delivery for the Events extension (SEP-3415): `events/subscribe` ++ * validation, subscription identity, Standard Webhooks signing, the endpoint ++ * verification handshake and the delivery loop. ++ * ++ * Subscriptions live in memory. Every grant is finite, so a subscription lost ++ * in a restart comes back on the client's next refresh, from its cursor. ++ */ ++import * as Clock from "../../Clock.ts" ++import * as Digest from "../../crypto/Digest.ts" ++import * as Mac from "../../crypto/Mac.ts" ++import * as SecureRandom from "../../crypto/SecureRandom.ts" ++import * as Deferred from "../../Deferred.ts" ++import * as Duration from "../../Duration.ts" ++import * as Effect from "../../Effect.ts" ++import * as Base64 from "../../encoding/Base64.ts" ++import * as Base64Url from "../../encoding/Base64Url.ts" ++import * as Fiber from "../../Fiber.ts" ++import * as FetchHttpClient from "../../http/FetchHttpClient.ts" ++import * as HttpClient from "../../http/HttpClient.ts" ++import * as HttpClientRequest from "../../http/HttpClientRequest.ts" ++import type * as HttpClientResponse from "../../http/HttpClientResponse.ts" ++import * as Option from "../../Option.ts" ++import * as Result from "../../Result.ts" ++import * as Stream from "../../Stream.ts" ++import * as PublicMcpSchema from "../McpSchema.ts" ++import type * as McpCore from "./mcpCore.ts" ++import { wireError } from "./mcpEvents.ts" ++ ++const MINUTE_MS = 60_000 ++/** @internal */ ++export const MIN_TTL_MS = MINUTE_MS ++// Short grants because subscriptions live in memory: a restart loses them until the next refresh. ++/** @internal */ ++export const MAX_TTL_MS = 60 * MINUTE_MS ++/** @internal */ ++export const DEFAULT_TTL_MS = 15 * MINUTE_MS ++/** @internal */ ++export const MAX_ATTEMPTS = 5 ++// Retries wait 30 s, 1, 2 and 4 minutes: about 7.5 minutes in all. ++const FIRST_RETRY_MS = 30_000 ++const REQUEST_TIMEOUT_MS = 10_000 ++// Deliveries signed with the old secret before a rotation still verify for this long. ++const ROTATION_GRACE_MS = 5 * MINUTE_MS ++const VERIFIED_FOR_MS = MAX_TTL_MS ++// A failed challenge is answered from here, so repeated subscribes cannot flood the endpoint. ++const FAILED_FOR_MS = 5 * MINUTE_MS ++// Verification POSTs one destination host receives per minute, across all principals. ++const VERIFICATIONS_PER_HOST_PER_MINUTE = 10 ++const MAX_SUBSCRIPTIONS_PER_PRINCIPAL = 100 ++// A verification reads this many bytes of the response at most; a delivery reads none. ++const MAX_CHALLENGE_RESPONSE_BYTES = 8_192 ++const SECRET_PREFIX = "whsec_" ++ ++/** ++ * The fixed categories `deliveryStatus.lastError` and `CallbackEndpointError` ++ * report; never the endpoint's own response. ++ * ++ * @internal ++ */ ++export type FailureCategory = ++ | "connection_refused" ++ | "timeout" ++ | "tls_error" ++ | "http_4xx" ++ | "http_5xx" ++ | "challenge_failed" ++ ++/** ++ * @internal ++ */ ++export interface Guard { ++ readonly check: (url: URL) => Effect.Effect ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface Options { ++ readonly principal: Effect.Effect ++ readonly guard: Guard ++ readonly client: HttpClient.HttpClient ++} ++ ++/** ++ * @internal ++ */ ++export interface SubscribeRequest { ++ readonly name: string ++ readonly arguments: Readonly> ++ readonly delivery: Readonly> ++ readonly cursor: string | null ++ readonly ttlMs?: number | null | undefined ++ // The event's argument decoder, run before the endpoint is contacted. ++ readonly decode: Effect.Effect ++ // Runs the event's stream for the subscription's lifetime, as push delivery does. ++ readonly open: ( ++ decoded: unknown, ++ deliver: (subscription: McpCore.EventSubscription) => Effect.Effect ++ ) => Effect.Effect ++} ++ ++/** ++ * @internal ++ */ ++export interface SubscribeResult { ++ readonly id: string ++ readonly refreshBefore: string ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly deliveryStatus?: { ++ readonly active: boolean ++ readonly lastDeliveryAt: string | null ++ readonly lastError: FailureCategory | null ++ } | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface UnsubscribeRequest { ++ readonly name: string ++ readonly arguments: Readonly> ++ readonly delivery: Readonly> ++} ++ ++/** ++ * @internal ++ */ ++export interface Webhooks { ++ readonly subscribe: ( ++ request: SubscribeRequest ++ ) => Effect.Effect ++ readonly unsubscribe: (request: UnsubscribeRequest) => Effect.Effect ++ readonly size: Effect.Effect ++} ++ ++interface Subscription { ++ readonly id: string ++ readonly principal: string ++ readonly url: URL ++ secret: string ++ key: Mac.Key ++ previous: { readonly key: Mac.Key; readonly until: number } | undefined ++ expiresAt: number ++ // Everything at or before it was acknowledged or given up on. ++ watermark: string | null ++ lastDeliveryAt: number | undefined ++ lastError: FailureCategory | undefined ++ fiber: Fiber.Fiber | undefined ++ // Completed when a refresh moves the deadline, so the expiry recomputes it. ++ deadlineMoved: Deferred.Deferred ++ // Where the event's stream started, or why it could not; a same-key refresh waits for it. ++ readonly accepted: Deferred.Deferred< ++ { readonly cursor: string | null; readonly truncated: boolean }, ++ McpCore.EventFailure | McpCore.RequestRejected ++ > ++ // After a gap whose envelope the endpoint never took: the cursors handed out since, any of ++ // which a refresh presents to say it saw past the gap. Until then every refresh is truncated. ++ cursorsSinceGap: Set | undefined ++} ++ ++type Outcome = ++ // `body` is read only for a verification, and is undefined when it was too long. ++ | { readonly _tag: "Delivered"; readonly body: string | undefined } ++ | { readonly _tag: "Failed"; readonly category: FailureCategory; readonly retryable: boolean } ++ ++const invalid = (message: string) => new PublicMcpSchema.InvalidParams({ message }) ++ ++/** ++ * The TTL granted for a suggested one: the default when none is suggested, and ++ * never unbounded, since subscriptions are not kept across restarts. ++ * ++ * @internal ++ */ ++export const grantTtl = (suggested: number | null | undefined): number => ++ suggested === undefined ++ ? DEFAULT_TTL_MS ++ : suggested === null ++ ? MAX_TTL_MS ++ : Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, suggested)) ++ ++/** ++ * JSON with object keys sorted, so equal arguments serialize equally. ++ * ++ * @internal ++ */ ++export const canonicalJson = (value: unknown): string => { ++ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]` ++ if (typeof value === "object" && value !== null) { ++ const entries = Object.entries(value).filter(([, entry]) => entry !== undefined) ++ entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) ++ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}` ++ } ++ return JSON.stringify(value) ?? "null" ++} ++ ++const encoder = new TextEncoder() ++ ++const parseUrl = (value: unknown, guard: Guard) => { ++ if (typeof value !== "string") return Effect.fail(invalid("delivery.url is required")) ++ let url: URL ++ try { ++ url = new URL(value) ++ } catch { ++ return Effect.fail(invalid("delivery.url is not a valid URL")) ++ } ++ if (url.protocol !== "https:" && !(url.protocol === "http:" && guard.allowsPlaintext?.(url) === true)) { ++ return Effect.fail(invalid("delivery.url must use https")) ++ } ++ if (url.username !== "" || url.password !== "") { ++ return Effect.fail(invalid("delivery.url must not carry credentials")) ++ } ++ url.hash = "" ++ return Effect.succeed(url) ++} ++ ++const parseSecret = (value: unknown) => { ++ const fail = Effect.fail(invalid("delivery.secret must be whsec_ and the base64 of 24 to 64 random bytes")) ++ if (typeof value !== "string" || !value.startsWith(SECRET_PREFIX)) return fail ++ const bytes = Base64.decode(value.slice(SECRET_PREFIX.length)) ++ if (Result.isFailure(bytes) || bytes.success.length < 24 || bytes.success.length > 64) return fail ++ return Mac.key(Mac.hmacSha256, bytes.success).pipe(Effect.orDie, Effect.map((key) => ({ text: value, key }))) ++} ++ ++const statusCategory = (status: number): FailureCategory => (status >= 500 ? "http_5xx" : "http_4xx") ++ ++// Only codes and names are read, never what the endpoint sent. ++const transportCategory = (error: unknown): FailureCategory => { ++ let current: unknown = error ++ for (let depth = 0; depth < 8 && typeof current === "object" && current !== null; depth++) { ++ const code = (current as { readonly code?: unknown }).code ++ if (typeof code === "string" && /CERT|TLS|SSL/.test(code)) return "tls_error" ++ current = (current as { readonly cause?: unknown }).cause ?? ++ (current as { readonly reason?: unknown }).reason ++ } ++ return "connection_refused" ++} ++ ++// Stops pulling past the cap; closing the request's scope then aborts the rest. ++const readCapped = (response: HttpClientResponse.HttpClientResponse) => ++ Effect.suspend(() => { ++ const chunks: Array = [] ++ let total = 0 ++ let oversized = false ++ return response.stream.pipe( ++ Stream.takeWhile((chunk) => { ++ if (total + chunk.length > MAX_CHALLENGE_RESPONSE_BYTES) { ++ oversized = true ++ return false ++ } ++ total += chunk.length ++ chunks.push(chunk) ++ return true ++ }), ++ Stream.runDrain, ++ Effect.map(() => { ++ if (oversized) return undefined ++ const bytes = new Uint8Array(total) ++ let offset = 0 ++ for (const chunk of chunks) { ++ bytes.set(chunk, offset) ++ offset += chunk.length ++ } ++ return new TextDecoder().decode(bytes) ++ }) ++ ) ++ }) ++ ++const echoedChallenge = (body: string): string | undefined => { ++ try { ++ const parsed: unknown = JSON.parse(body) ++ const challenge = typeof parsed === "object" && parsed !== null ++ ? (parsed as { readonly challenge?: unknown }).challenge ++ : undefined ++ return typeof challenge === "string" ? challenge : undefined ++ } catch { ++ return undefined ++ } ++} ++ ++const callbackError = (category: FailureCategory) => ++ new PublicMcpSchema.CallbackEndpointError({ ++ message: `The callback endpoint failed verification: ${category}`, ++ data: { reason: category } ++ }) ++ ++const iso = (millis: number) => new Date(millis).toISOString() ++ ++/** ++ * @internal ++ */ ++export const make = Effect.fnUntraced(function*(options: Options) { ++ const scope = yield* Effect.scope ++ const mac = yield* Mac.Mac ++ const digest = yield* Digest.Digest ++ const random = yield* SecureRandom.SecureRandom ++ const { guard } = options ++ // Closing a request's scope aborts its body, so a delivery never downloads what the endpoint sends. ++ const client = HttpClient.withScope(options.client) ++ const subscriptions = new Map() ++ // Subscribes past the principal check that have not created their subscription yet. ++ const pending = new Map() ++ const verified = new Map() ++ const failedVerifications = new Map() ++ const verifying = new Map>() ++ const verificationsByHost = new Map>() ++ ++ const forget = (subscription: Subscription) => { ++ if (subscriptions.get(subscription.id) === subscription) subscriptions.delete(subscription.id) ++ } ++ ++ const subscriptionId = (principal: string, url: URL, name: string, args: unknown) => ++ digest.digestHex(Digest.sha256, encoder.encode(canonicalJson([principal, url.href, name, args]))).pipe( ++ Effect.map((hex) => `sub_${hex.slice(0, 32)}`) ++ ) ++ ++ // High entropy and unrelated to the eventId; a retry reuses it. ++ const messageId = (prefix: string) => ++ Effect.map(random.randomBytes(18), (bytes) => `${prefix}_${Base64Url.encode(bytes)}`) ++ ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They require an event's webhook-id to equal its eventId. Both become this id, derived per ++ // subscription so two subscriptions to one URL never share it; poll and push keep the eventId. ++ const deliveryId = (subscription: Subscription, eventId: string) => ++ Effect.map( ++ digest.digest(Digest.sha256, encoder.encode(`${subscription.id}\0${eventId}`)), ++ (hash) => `evt_${Base64Url.encode(hash).slice(0, 22)}` ++ ) ++ ++ const MAX_CURSORS_SINCE_GAP = 1_024 ++ const advance = (subscription: Subscription, cursor: string | null) => { ++ subscription.watermark = cursor ++ const since = subscription.cursorsSinceGap ++ if (since === undefined) return ++ since.add(cursor) ++ if (since.size > MAX_CURSORS_SINCE_GAP) since.delete(since.values().next().value!) ++ } ++ ++ const sign = (keys: ReadonlyArray, webhookId: string, timestamp: number, body: string) => ++ Effect.forEach(keys, (key) => mac.sign(key, encoder.encode(`${webhookId}.${timestamp}.${body}`))).pipe( ++ Effect.orDie, ++ Effect.map((tags) => tags.map((tag) => `v1,${Base64.encode(tag)}`).join(" ")) ++ ) ++ ++ // One POST. The timestamp and signature are fresh on every attempt. ++ const send = Effect.fnUntraced(function*( ++ subscription: Subscription, ++ body: string, ++ webhookId: string, ++ readBody: boolean ++ ) { ++ const admitted = yield* Effect.result(guard.check(subscription.url)) ++ if (Result.isFailure(admitted)) { ++ return { _tag: "Failed", category: "connection_refused", retryable: true } satisfies Outcome ++ } ++ const now = yield* Clock.currentTimeMillis ++ const timestamp = Math.floor(now / 1000) ++ const previous = subscription.previous ++ const keys = previous !== undefined && now < previous.until ++ ? [subscription.key, previous.key] ++ : [subscription.key] ++ const request = HttpClientRequest.post(subscription.url).pipe( ++ HttpClientRequest.setHeaders({ ++ "webhook-id": webhookId, ++ "webhook-timestamp": String(timestamp), ++ "webhook-signature": yield* sign(keys, webhookId, timestamp, body), ++ "x-mcp-subscription-id": subscription.id ++ }), ++ HttpClientRequest.bodyText(body, "application/json") ++ ) ++ const outcome = yield* client.execute(request).pipe( ++ Effect.flatMap((response): Effect.Effect => { ++ if (response.status < 200 || response.status >= 300) { ++ return Effect.succeed({ ++ _tag: "Failed", ++ category: statusCategory(response.status), ++ retryable: response.status !== 410 && response.status !== 413 ++ }) ++ } ++ return readBody ++ ? Effect.map(readCapped(response), (text) => ({ _tag: "Delivered", body: text })) ++ : Effect.succeed({ _tag: "Delivered", body: undefined }) ++ }), ++ Effect.timeoutOption(Duration.millis(REQUEST_TIMEOUT_MS)), ++ Effect.scoped, ++ // `fetch` would follow a redirect itself; webhook delivery never does. ++ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), ++ // Trace ids stay inside: the endpoint belongs to someone else. ++ Effect.provideService(HttpClient.TracerPropagationEnabled, false), ++ Effect.catch((error) => ++ Effect.succeed(Option.some({ _tag: "Failed", category: transportCategory(error), retryable: true })) ++ ) ++ ) ++ return Option.getOrElse(outcome, (): Outcome => ({ _tag: "Failed", category: "timeout", retryable: true })) ++ }) ++ ++ // Retries with backoff; gives up after a 410, a 413 or the last attempt. True once delivered. ++ const deliver = Effect.fnUntraced(function*(subscription: Subscription, body: string, webhookId: string) { ++ for (let attempt = 1;; attempt++) { ++ // A subscription that ended may have been replaced under its id; this one speaks no longer. ++ const current = subscriptions.get(subscription.id) ++ if (current !== undefined && current !== subscription) return false ++ const startedAt = yield* Clock.currentTimeMillis ++ const outcome = yield* send(subscription, body, webhookId, false) ++ if (outcome._tag === "Delivered") { ++ subscription.lastDeliveryAt = yield* Clock.currentTimeMillis ++ subscription.lastError = undefined ++ return true ++ } ++ subscription.lastError = outcome.category ++ if (!outcome.retryable || attempt >= MAX_ATTEMPTS) return false ++ // Counted from the attempt's start, so a slow endpoint does not stretch the window. ++ const wait = startedAt + FIRST_RETRY_MS * 2 ** (attempt - 1) - (yield* Clock.currentTimeMillis) ++ if (wait > 0) yield* Effect.sleep(Duration.millis(wait)) ++ } ++ }) ++ ++ const control = (subscription: Subscription, type: string, fields: Readonly>) => ++ Effect.flatMap( ++ messageId(`msg_${type}`), ++ (webhookId) => deliver(subscription, JSON.stringify({ type, ...fields }), webhookId) ++ ) ++ ++ // One delivery in flight per subscription, so the watermark only moves forward ++ // once everything before it is resolved. ++ const run = (subscription: Subscription, name: string, events: McpCore.EventSubscription) => ++ events.items.pipe( ++ Stream.runForEach((item): Effect.Effect => { ++ switch (item._tag) { ++ case "Event": ++ return Effect.flatMap(deliveryId(subscription, item.eventId), (webhookId) => { ++ const body = JSON.stringify({ ++ eventId: webhookId, ++ name, ++ timestamp: item.timestamp, ++ data: item.data, ++ cursor: item.cursor, ++ ...(item._meta === undefined ? {} : { _meta: item._meta }) ++ }) ++ return deliver(subscription, body, webhookId) ++ }).pipe(Effect.andThen(Effect.sync(() => advance(subscription, item.cursor)))) ++ case "Position": ++ return Effect.sync(() => advance(subscription, item.cursor)) ++ case "Gap": ++ return control(subscription, "gap", { cursor: item.cursor }).pipe( ++ Effect.map((delivered) => { ++ if (!delivered) subscription.cursorsSinceGap = new Set() ++ advance(subscription, item.cursor) ++ }) ++ ) ++ case "Error": ++ // A webhook has no envelope for an error that leaves the subscription open. ++ return Effect.void ++ } ++ }), ++ // Ended before it says so, so a refresh meanwhile starts afresh instead of reporting it live. ++ Effect.catch((failure) => ++ Effect.suspend(() => { ++ forget(subscription) ++ return control(subscription, "terminated", { error: wireError(failure) }) ++ }) ++ ) ++ ) ++ ++ const expiry = (subscription: Subscription) => ++ Effect.gen(function*() { ++ while (true) { ++ const left = subscription.expiresAt - (yield* Clock.currentTimeMillis) ++ if (left <= 0) return forget(subscription) ++ yield* Effect.raceFirst(Effect.sleep(Duration.millis(left)), Deferred.await(subscription.deadlineMoved)) ++ } ++ }) ++ ++ const handshake = Effect.fnUntraced(function*(subscription: Subscription) { ++ const challenge = Base64Url.encode(yield* random.randomBytes(32)) ++ const outcome = yield* send( ++ subscription, ++ JSON.stringify({ type: "verification", challenge }), ++ yield* messageId("msg_verification"), ++ true ++ ) ++ if (outcome._tag === "Failed") return yield* Effect.fail(outcome.category) ++ const echoed = outcome.body === undefined ? undefined : echoedChallenge(outcome.body) ++ if (echoed === undefined || !Mac.timingSafeEqual(encoder.encode(echoed), encoder.encode(challenge))) { ++ return yield* Effect.fail("challenge_failed") ++ } ++ }) ++ ++ // Cached per (principal, url) either way; concurrent subscribes share one handshake. ++ const verify = Effect.fnUntraced(function*(subscription: Subscription) { ++ const key = JSON.stringify([subscription.principal, subscription.url.href]) ++ const now = yield* Clock.currentTimeMillis ++ for (const [entry, until] of verified) if (until <= now) verified.delete(entry) ++ for (const [entry, failure] of failedVerifications) if (failure.until <= now) failedVerifications.delete(entry) ++ if (verified.has(key)) return ++ const failure = failedVerifications.get(key) ++ if (failure !== undefined) return yield* callbackError(failure.category) ++ const inFlight = verifying.get(key) ++ if (inFlight !== undefined) return yield* Deferred.await(inFlight) ++ const host = subscription.url.hostname ++ const recent = (verificationsByHost.get(host) ?? []).filter((at) => at > now - MINUTE_MS) ++ if (recent.length >= VERIFICATIONS_PER_HOST_PER_MINUTE) { ++ verificationsByHost.set(host, recent) ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many callback verifications for this host", ++ data: { limit: "verifications", max: VERIFICATIONS_PER_HOST_PER_MINUTE } ++ }) ++ } ++ for (const [entry, times] of verificationsByHost) { ++ if (times.every((at) => at <= now - MINUTE_MS)) verificationsByHost.delete(entry) ++ } ++ verificationsByHost.set(host, [...recent, now]) ++ const done = Deferred.makeUnsafe() ++ verifying.set(key, done) ++ return yield* handshake(subscription).pipe( ++ Effect.tap(() => ++ Effect.map(Clock.currentTimeMillis, (at) => { ++ verified.set(key, at + VERIFIED_FOR_MS) ++ }) ++ ), ++ Effect.tapError((category) => ++ Effect.map(Clock.currentTimeMillis, (at) => { ++ failedVerifications.set(key, { until: at + FAILED_FOR_MS, category }) ++ }) ++ ), ++ Effect.mapError(callbackError), ++ Effect.onExit((exit) => ++ Effect.sync(() => { ++ verifying.delete(key) ++ Deferred.doneUnsafe(done, exit) ++ }) ++ ) ++ ) ++ }) ++ ++ // A caller that joins while the first subscribe's stream is opening waits for it and gets ++ // where it started; one whose subscription went away meanwhile subscribes afresh. ++ const refresh = Effect.fnUntraced(function*( ++ request: SubscribeRequest, ++ subscription: Subscription, ++ secret: { readonly text: string; readonly key: Mac.Key }, ++ expiresAt: number, ++ now: number ++ ): Effect.fn.Return { ++ const opening = !Deferred.isDoneUnsafe(subscription.accepted) ++ const start = yield* Deferred.await(subscription.accepted) ++ if (subscriptions.get(subscription.id) !== subscription) return yield* subscribe(request) ++ if (subscription.secret !== secret.text) { ++ subscription.previous = { key: subscription.key, until: now + ROTATION_GRACE_MS } ++ subscription.secret = secret.text ++ subscription.key = secret.key ++ } ++ subscription.expiresAt = expiresAt ++ const moved = subscription.deadlineMoved ++ subscription.deadlineMoved = Deferred.makeUnsafe() ++ Deferred.doneUnsafe(moved, Effect.void) ++ if (opening) return { id: subscription.id, refreshBefore: iso(expiresAt), ...start } ++ // Kept until the client shows a cursor from past the gap, so a lost response hides nothing. ++ const since = subscription.cursorsSinceGap ++ if (since !== undefined && since.has(request.cursor)) subscription.cursorsSinceGap = undefined ++ const truncated = subscription.cursorsSinceGap !== undefined ++ return { ++ id: subscription.id, ++ refreshBefore: iso(expiresAt), ++ cursor: subscription.watermark, ++ truncated, ++ deliveryStatus: { ++ active: true, ++ lastDeliveryAt: subscription.lastDeliveryAt === undefined ? null : iso(subscription.lastDeliveryAt), ++ lastError: subscription.lastError ?? null ++ } ++ } satisfies SubscribeResult ++ }) ++ ++ const subscribe: Webhooks["subscribe"] = Effect.fnUntraced(function*(request) { ++ const principal = yield* options.principal ++ const mode = request.delivery.mode ++ if (mode !== undefined && mode !== "webhook") return yield* invalid("delivery.mode must be 'webhook'") ++ const url = yield* parseUrl(request.delivery.url, guard) ++ const secret = yield* parseSecret(request.delivery.secret) ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments) ++ const now = yield* Clock.currentTimeMillis ++ const expiresAt = now + grantTtl(request.ttlMs) ++ const live = subscriptions.get(id) ++ if (live !== undefined) return yield* refresh(request, live, secret, expiresAt, now) ++ // The slot is taken before anything asynchronous, so concurrent subscribes cannot pass the cap. ++ let held = pending.get(principal) ?? 0 ++ for (const subscription of subscriptions.values()) if (subscription.principal === principal) held++ ++ if (held >= MAX_SUBSCRIPTIONS_PER_PRINCIPAL) { ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many webhook subscriptions", ++ data: { limit: "subscriptions", max: MAX_SUBSCRIPTIONS_PER_PRINCIPAL } ++ }) ++ } ++ pending.set(principal, (pending.get(principal) ?? 0) + 1) ++ let reserved = true ++ const release = () => { ++ if (!reserved) return ++ reserved = false ++ const left = (pending.get(principal) ?? 1) - 1 ++ if (left === 0) pending.delete(principal) ++ else pending.set(principal, left) ++ } ++ return yield* create(request, { principal, url, secret, id, expiresAt, now, release }).pipe( ++ Effect.ensuring(Effect.sync(release)) ++ ) ++ }) ++ ++ const create = Effect.fnUntraced(function*( ++ request: SubscribeRequest, ++ { expiresAt, id, now, principal, release, secret, url }: { ++ readonly principal: string ++ readonly url: URL ++ readonly secret: { readonly text: string; readonly key: Mac.Key } ++ readonly id: string ++ readonly expiresAt: number ++ readonly now: number ++ readonly release: () => void ++ } ++ ) { ++ // One answer whether the host is private or does not resolve, so it reveals neither. ++ yield* Effect.mapError(guard.check(url), () => invalid("delivery.url is not allowed")) ++ const subscription: Subscription = { ++ id, ++ principal, ++ url, ++ secret: secret.text, ++ key: secret.key, ++ previous: undefined, ++ expiresAt, ++ watermark: request.cursor, ++ lastDeliveryAt: undefined, ++ lastError: undefined, ++ fiber: undefined, ++ deadlineMoved: Deferred.makeUnsafe(), ++ accepted: Deferred.makeUnsafe(), ++ cursorsSinceGap: undefined ++ } ++ const decoded = yield* request.decode ++ yield* verify(subscription) ++ // A concurrent subscribe for the same key may have finished while this one verified. ++ const raced = subscriptions.get(id) ++ if (raced !== undefined) { ++ release() ++ return yield* refresh(request, raced, secret, expiresAt, now) ++ } ++ release() ++ subscriptions.set(id, subscription) ++ const { accepted } = subscription ++ const lifetime = request.open(decoded, (events) => ++ Effect.suspend(() => { ++ subscription.watermark = events.cursor ++ return Deferred.succeed(accepted, { cursor: events.cursor, truncated: events.truncated }) ++ }).pipe(Effect.andThen(run(subscription, request.name, events))) ++ ).pipe( ++ Effect.tapError((failure) => Deferred.fail(accepted, failure)), ++ Effect.raceFirst(expiry(subscription)), ++ Effect.ignore, ++ Effect.ensuring(Effect.suspend(() => { ++ forget(subscription) ++ return Deferred.fail(accepted, new PublicMcpSchema.InternalError({ message: "The subscription ended" })) ++ })) ++ ) ++ // Forked from the request, so the event's stream keeps the request's services. ++ subscription.fiber = yield* Effect.forkIn(lifetime, scope) ++ const start = yield* Deferred.await(accepted) ++ return { id, refreshBefore: iso(expiresAt), cursor: start.cursor, truncated: start.truncated } ++ }) ++ ++ const unsubscribe: Webhooks["unsubscribe"] = Effect.fnUntraced(function*(request) { ++ const principal = yield* options.principal ++ const url = yield* parseUrl(request.delivery.url, guard) ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments) ++ const subscription = subscriptions.get(id) ++ if (subscription === undefined) { ++ return yield* new PublicMcpSchema.NotFound({ ++ message: "No webhook subscription matches", ++ data: { kind: "subscription" } ++ }) ++ } ++ subscriptions.delete(id) ++ if (subscription.fiber !== undefined) yield* Fiber.interrupt(subscription.fiber) ++ }) ++ ++ return { ++ subscribe, ++ unsubscribe, ++ size: Effect.sync(() => subscriptions.size) ++ } satisfies Webhooks ++}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 471dec4be9987..e53019e0f39bd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -377,7 +377,7 @@ patchedDependencies: alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 - effect@4.1.5: 76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337 + effect@4.1.5: 24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28 electron-updater@6.8.9: 91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155 expo-audio@58.0.11: 92414572bf24ffd0c45de44c45f11f6c48bc0af13b8b9a56f77a67bc0e915c1e expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 @@ -435,7 +435,7 @@ importers: version: 0.15.4 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 @@ -459,7 +459,7 @@ importers: version: 0.10.2(patch_hash=cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4) effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) electron: specifier: 44.10.1 version: 44.10.1(supports-color@8.1.1) @@ -490,7 +490,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -551,7 +551,7 @@ importers: version: 0.4.4(patch_hash=7a808b92da8460750b85818552e13be3fb73d111691c7db76965970351e124e4)(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)(supports-color@8.1.1)(typescript@6.0.3) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0) '@expo-google-fonts/dm-sans': specifier: ^0.4.2 version: 0.4.2 @@ -629,7 +629,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) expo: specifier: 58.0.23 version: 58.0.23(d226faf1ca90e630d8c56a2108dee32d) @@ -816,10 +816,10 @@ importers: version: 7.29.7(supports-color@8.1.1) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@pierre/trees': specifier: 1.0.0-beta.6 version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(shiki@4.2.0) @@ -861,10 +861,10 @@ importers: version: 1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/platform-node-shared': specifier: 4.1.5 - version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) '@ff-labs/fff-node': specifier: 0.11.0 version: 0.11.0(patch_hash=93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252) @@ -945,7 +945,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -985,10 +985,10 @@ importers: devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@handy-computer/models': specifier: 0.2.3 version: 0.2.3 @@ -1093,7 +1093,7 @@ importers: version: 3.2.2(react@19.3.0) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0) '@fontsource-variable/inter': specifier: ^5.3.0 version: 5.3.0 @@ -1198,7 +1198,7 @@ importers: version: 3.4.17 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) entities: specifier: 8.1.0 version: 8.1.0 @@ -1268,10 +1268,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@tailwindcss/vite': specifier: 4.3.3 version: 4.3.3(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)) @@ -1337,7 +1337,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../packages/contracts @@ -1349,11 +1349,11 @@ importers: version: link:../packages/shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1365,28 +1365,28 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) + version: 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) '@alchemy.run/drizzle': specifier: 'catalog:' - version: 2.0.0-beta.85(9d8ed2cd275ad880a7ad7c23a0ac97be) + version: 2.0.0-beta.85(5cde798e96ab6d44cdc28240628f10b1) '@alchemy.run/planetscale': specifier: 'catalog:' - version: 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) + version: 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) '@clerk/backend': specifier: 3.27.0 version: 3.27.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@distilled.cloud/cloudflare': specifier: 'catalog:' - version: 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/sql-pg': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/sql-sqlite-do': specifier: 'catalog:' - version: 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@noble/curves': specifier: 'catalog:' version: 1.9.1 @@ -1404,26 +1404,26 @@ importers: version: link:../../packages/shared alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) drizzle-orm: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@alchemy.run/test': specifier: 'catalog:' - version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(f73ef3f521055a56671f9dfc623ae3a6) + version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(a619c060a1b8ed45ad4914f1f8e44c19) '@cloudflare/workers-types': specifier: ^4.20260601.1 version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@electric-sql/pglite': specifier: 0.3.15 version: 0.3.15 @@ -1432,7 +1432,7 @@ importers: version: 24.12.4 drizzle-kit: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf) + version: 1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809) vite: specifier: npm:@voidzero-dev/vite-plus-core@1.4.0 version: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' @@ -1444,16 +1444,16 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) + version: 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) jose: specifier: 'catalog:' version: 6.2.2 @@ -1463,10 +1463,10 @@ importers: version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1481,14 +1481,14 @@ importers: version: 1.89.0 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1545,7 +1545,7 @@ importers: version: link:../source-control-definitions effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) gt-i18n: specifier: 1.0.40 version: 1.0.40 @@ -1561,7 +1561,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/mdast': specifier: ^4.0.4 version: 4.0.4 @@ -1585,11 +1585,11 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1598,17 +1598,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1620,17 +1620,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1648,14 +1648,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1679,14 +1679,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1716,14 +1716,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1747,14 +1747,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1778,7 +1778,7 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) jsonc-parser: specifier: 3.3.1 version: 3.3.1 @@ -1788,10 +1788,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1818,14 +1818,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1855,14 +1855,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1892,14 +1892,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1929,14 +1929,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1954,7 +1954,7 @@ importers: version: 1.15.13 '@opencode/client': specifier: 2.0.28 - version: 2.0.28(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 2.0.28(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@opencode/protocol': specifier: 2.0.28 version: 2.0.28 @@ -1972,14 +1972,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2003,14 +2003,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2025,7 +2025,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2037,11 +2037,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2056,14 +2056,14 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2096,14 +2096,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2124,7 +2124,7 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -2185,10 +2185,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/hast': specifier: ^3.0.5 version: 3.0.5 @@ -2224,14 +2224,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2258,14 +2258,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2286,11 +2286,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2302,7 +2302,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2317,11 +2317,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2375,14 +2375,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2409,11 +2409,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2428,7 +2428,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2443,17 +2443,17 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) yaml: specifier: ^2.9.0 version: 2.9.0 devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2477,14 +2477,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2508,11 +2508,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2527,7 +2527,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2539,7 +2539,7 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@types/node': specifier: 24.12.4 @@ -2555,14 +2555,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2580,11 +2580,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2602,7 +2602,7 @@ importers: version: 0.15.5(e2e@0.23.0) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@electron/asar': specifier: ^4.3.0 version: 4.3.0 @@ -2626,7 +2626,7 @@ importers: version: 0.23.0 effect: specifier: 4.1.5 - version: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) playwright-core: specifier: 1.64.1 version: 1.64.1 @@ -2642,7 +2642,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/plist': specifier: 'catalog:' version: 3.0.5 @@ -13168,27 +13168,27 @@ snapshots: dependencies: json-schema: 0.4.0 - '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(rolldown@1.2.13)(typescript@6.0.3)': + '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(rolldown@1.2.13)(typescript@6.0.3)': dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@cloudflare/unenv-preset': 2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261026.1) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@puppeteer/browsers': 3.2.6(yauzl@3.4.0) capnp-es: 0.0.16(typescript@6.0.3) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) magic-string: 0.30.21 mime: 4.1.1 sharp: 0.35.5(@types/node@24.12.4) @@ -13196,8 +13196,8 @@ snapshots: workerd: 1.20261026.1 yauzl: 3.4.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) rolldown: 1.2.13 vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: @@ -13205,27 +13205,27 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/cloudflare@2.0.0-beta.85(2402ddc9484fce072797810bc31b583f)': - dependencies: - '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(rolldown@1.2.13)(typescript@6.0.3) - '@alchemy.run/docker': 2.0.0-beta.85(e480f1b1bda9582dded73d242d5d6dc9) - '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) - '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@alchemy.run/cloudflare@2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e)': + dependencies: + '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(rolldown@1.2.13)(typescript@6.0.3) + '@alchemy.run/docker': 2.0.0-beta.85(b7b9d9a38fe35faf72b0a492112f9365) + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) pathe: 2.0.3 picomatch: 4.0.7 rolldown: 1.2.13 tinyglobby: 0.2.17 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: - '@effect/sql-libsql' @@ -13237,26 +13237,26 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/docker@2.0.0-beta.85(e480f1b1bda9582dded73d242d5d6dc9)': + '@alchemy.run/docker@2.0.0-beta.85(b7b9d9a38fe35faf72b0a492112f9365)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) rolldown: 1.2.13 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) - '@alchemy.run/drizzle@2.0.0-beta.85(9d8ed2cd275ad880a7ad7c23a0ac97be)': + '@alchemy.run/drizzle@2.0.0-beta.85(5cde798e96ab6d44cdc28240628f10b1)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) - '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@alchemy.run/cloudflare': 2.0.0-beta.85(2402ddc9484fce072797810bc31b583f) - '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - drizzle-kit: 1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf) + '@alchemy.run/cloudflare': 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + drizzle-kit: 1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809) transitivePeerDependencies: - mysql2 - pg @@ -13266,13 +13266,13 @@ snapshots: chokidar: 5.0.0 rolldown: 1.2.13 - '@alchemy.run/planetscale@2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0)': + '@alchemy.run/planetscale@2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: pg: 8.23.0 transitivePeerDependencies: @@ -13285,21 +13285,21 @@ snapshots: '@types/react': 19.3.0 react-devtools-core: 6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@alchemy.run/sql@2.0.0-beta.85(13cf82a9ea878143588c95fe8a3597d0)': + '@alchemy.run/sql@2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) pg: 8.23.0 - '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(f73ef3f521055a56671f9dfc623ae3a6)': + '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(a619c060a1b8ed45ad4914f1f8e44c19)': dependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@effect/vitest': 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@effect/vitest': 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) vitest: 5.0.5(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/browser-preview@5.0.5)(@vitest/ui@5.0.5)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0) transitivePeerDependencies: - bufferutil @@ -14278,45 +14278,45 @@ snapshots: '@dimforge/rapier3d-compat@0.12.0': {} - '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@dnd-kit/accessibility@3.1.1(react@19.3.0)': dependencies: @@ -14362,64 +14362,64 @@ snapshots: e2e: 0.23.0 playwright-core: 1.64.1 - '@effect/atom-react@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react@19.3.0)(scheduler@0.28.0)': + '@effect/atom-react@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0)': dependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) react: 19.3.0 scheduler: 0.28.0 - '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(encoding@0.1.13)': + '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13)': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) swagger2openapi: 7.0.8(encoding@0.1.13) transitivePeerDependencies: - encoding - '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6)': + '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6)': + '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6)': dependencies: '@types/ws': 8.18.2 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6)': + '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) redis: 6.2.1 undici: 8.12.4 transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: '@cloudflare/workers-types': 5.20261026.1 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@effect/tsgo-darwin-arm64@0.67.1': optional: true @@ -14452,9 +14452,9 @@ snapshots: '@effect/tsgo-win32-arm64': 0.67.1 '@effect/tsgo-win32-x64': 0.67.1 - '@effect/vitest@4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': + '@effect/vitest@4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': dependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) vite-plus: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) transitivePeerDependencies: - '@arethetypeswrong/core' @@ -15930,22 +15930,22 @@ snapshots: dependencies: cross-spawn: 7.0.6 - '@opencode/client@2.0.28(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))': + '@opencode/client@2.0.28(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: '@opencode/protocol': 2.0.28 '@opencode/schema': 2.0.28 optionalDependencies: - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@opencode/protocol@2.0.28': dependencies: '@opencode/schema': 2.0.28 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@opencode/schema@2.0.28': dependencies: '@standard-schema/spec': 1.1.0 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@oslojs/asn1@1.0.0': dependencies: @@ -18034,12 +18034,12 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 - alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): + alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@alchemy.run/sigil': 0.1.0-alpha.1(@types/react@19.3.0)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6)) capnweb: 0.12.0 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) fflate: 0.8.3 pathe: 2.0.3 picomatch: 4.0.7 @@ -18047,8 +18047,8 @@ snapshots: tinyglobby: 0.2.17 yaml: 2.9.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: @@ -19007,21 +19007,21 @@ snapshots: dotenv@16.6.1: {} - drizzle-kit@1.0.0-rc.5(9451426e25210de8eb160d0749b6dfbf): + drizzle-kit@1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809): optionalDependencies: - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): + drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): optionalDependencies: '@cloudflare/workers-types': 4.20260604.1 - '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337)) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@electric-sql/pglite': 0.3.15 '@libsql/client': 0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@types/sql.js': 1.4.11 bun-types: 1.3.14 - effect: 4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) expo-sqlite: 58.0.15(expo@58.0.23)(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) pg: 8.23.0 sql.js: 1.15.0 @@ -19060,7 +19060,7 @@ snapshots: ee-first@1.1.1: {} - effect@4.1.5(patch_hash=76f8577c1124614416ae00af6d6eb1bd65342d6cf8070c3c34aa27726e32d337): {} + effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28): {} ejs@3.1.10: dependencies: From 29a33f8827ae4bbc14a315cc56938b5fbabbade5 Mon Sep 17 00:00:00 2001 From: Simone Date: Mon, 23 Nov 2026 03:56:35 +0100 Subject: [PATCH 145/162] fix(antigravity): recognize attachments with MIME parameters (#39097) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> --- .../acp/AntigravityAcpSupport.test.ts | 46 ++++++++++--------- .../src/provider/acp/AntigravityAcpSupport.ts | 2 +- 2 files changed, 25 insertions(+), 23 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index 7201d1edc0ba0..a68c1334c473f 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -508,29 +508,31 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => { }), ); - it.effect("sends supported audio files as native audio content", () => - Effect.gen(function* () { - const fixture = yield* makeAttachmentFixture(); - const audioAttachment = { - ...textAttachment, - id: "recording-1", - name: "recording.wav", - mimeType: "audio/wav", - } satisfies ChatAttachment; - const bytes = Buffer.from("RIFF....WAVEfmt ", "latin1"); - yield* fixture.write(audioAttachment, bytes); - const prompt = yield* buildAntigravityPrompt({ - input: "Transcribe this.", - attachments: [audioAttachment], - resolveAttachmentPath: fixture.resolve, - promptCapabilities: { image: true, audio: true, embeddedContext: true }, - }); + it.effect.each(["audio/wav", "audio/wav;codecs=1", "Audio/WAV \t; codecs=1"])( + "sends supported audio files as native audio content (%s)", + (mimeType) => + Effect.gen(function* () { + const fixture = yield* makeAttachmentFixture(); + const audioAttachment = { + ...textAttachment, + id: "recording-1", + name: "recording.wav", + mimeType, + } satisfies ChatAttachment; + const bytes = Buffer.from("RIFF....WAVEfmt ", "latin1"); + yield* fixture.write(audioAttachment, bytes); + const prompt = yield* buildAntigravityPrompt({ + input: "Transcribe this.", + attachments: [audioAttachment], + resolveAttachmentPath: fixture.resolve, + promptCapabilities: { image: true, audio: true, embeddedContext: true }, + }); - expect(prompt).toEqual([ - { type: "text", text: "Transcribe this." }, - { type: "audio", data: bytes.toString("base64"), mimeType: "audio/wav" }, - ]); - }), + expect(prompt).toEqual([ + { type: "text", text: "Transcribe this." }, + { type: "audio", data: bytes.toString("base64"), mimeType: "audio/wav" }, + ]); + }), ); it.effect.each([{ image: true }])( diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 4d57305f7e0ec..f16c143cc278c 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -428,7 +428,7 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi "source" in attachment && attachment.source?._tag === "pasted-text"; // The text already carries the path; keep folded pastes lazy so agents can search without embedding the whole file. - const mimeType = attachment.mimeType.toLowerCase().split(";", 1)[0] ?? ""; + const mimeType = attachment.mimeType.split(";", 1)[0]?.trim().toLowerCase() ?? ""; const image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType); const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType); const pdf = attachment.type === "file" && mimeType === "application/pdf"; From 27ab8d49eba9bd5f0910e71891bcdb719e0850a0 Mon Sep 17 00:00:00 2001 From: Simone Date: Mon, 23 Nov 2026 03:56:43 +0100 Subject: [PATCH 146/162] fix(antigravity): keep shortened question text valid Unicode (#39478) Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com> --- .../src/provider/acp/AntigravityProtocol.test.ts | 16 +++++++++++----- .../src/provider/acp/AntigravityProtocol.ts | 16 ++++++++-------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index 93f7d1fc377c8..d86ca3ead0f3c 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -253,17 +253,23 @@ describe("Antigravity permissions and questions", () => { }); it("bounds question text without changing choice IDs", () => { + const title = "Q".repeat(7_994) + "🧪"; + const label = "O".repeat(506) + "🧪"; const request = { ...questionRequest, - toolCall: { ...questionRequest.toolCall, title: "Question ".repeat(2_000) }, + toolCall: { ...questionRequest.toolCall, title: title + "🚀 continued" }, options: [ - { optionId: "stable-choice", name: "Choice ".repeat(2_000), kind: "allow_once" as const }, + { optionId: "stable-choice", name: label + "🚀 continued", kind: "allow_once" as const }, ], }; const question = extractAntigravityUserInputQuestion(request); - expect(question?.question.length).toBeLessThanOrEqual(8_000); - expect(question?.options[0]?.label.length).toBeLessThanOrEqual(512); - expect(question?.options[0]?.value).toBe("stable-choice"); + expect(question?.question).toBe(title + "..."); + expect(question?.options).toEqual([ + { value: "stable-choice", label: label + "...", description: label + "..." }, + ]); + expect( + makeAntigravityUserInputResponse(request, { interaction_9960062f: label + "..." }), + ).toEqual({ outcome: { outcome: "selected", optionId: "stable-choice" } }); }); }); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 2e59a78e376b4..008579d087f05 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -125,11 +125,14 @@ function copyBoundedText(text: string): string { return Buffer.from(text, "utf16le").toString("utf16le"); } +function boundQuestionText(text: string, limit: number): string { + if (text.length <= limit) return text; + const prefix = text.slice(0, limit - 3).replace(/[\uD800-\uDBFF]$/u, ""); + return copyBoundedText(`${prefix}...`); +} + function questionLabel(option: EffectAcpSchema.PermissionOption): string { - const label = option.name.trim() || option.optionId; - return label.length > QUESTION_LABEL_LIMIT - ? copyBoundedText(`${label.slice(0, QUESTION_LABEL_LIMIT - 3)}...`) - : label; + return boundQuestionText(option.name.trim() || option.optionId, QUESTION_LABEL_LIMIT); } export function extractAntigravityUserInputQuestion( @@ -149,10 +152,7 @@ export function extractAntigravityUserInputQuestion( return { id: request.toolCall.toolCallId, header: "Question", - question: - question.length > TOOL_TEXT_LIMIT - ? copyBoundedText(`${question.slice(0, TOOL_TEXT_LIMIT - 3)}...`) - : question, + question: boundQuestionText(question, TOOL_TEXT_LIMIT), multiSelect: false, allowCustomAnswer: false, options: request.options.map((option) => ({ From b9c310971001a4b0ca3010ddb13af4d028c60acc Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 22 Nov 2026 20:58:19 -0600 Subject: [PATCH 147/162] fix(cursor): preserve ended turns when connection retries exhaust (#41176) --- .../src/server/adapter.test.ts | 48 +++++++++++++++++++ .../provider-cursor/src/server/adapter.ts | 10 ++-- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index dfa1ac4865269..85cc2535960b8 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -445,6 +445,54 @@ describe("CursorAdapterV2", () => { failure: null, answers: [], }, + { + reason: "no failure when the connection fails after the turn ended", + updates: [ + { type: "text-delta", text: "Done." }, + { type: "turn-ended" }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: null, + }, + { + reason: "a connection failure before the turn ends", + updates: [ + { type: "text-delta", text: "Working." }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: { class: "provider_error", message: "Connection failed repeatedly" }, + }, + { + reason: "a connection failure during a continuation after the turn ended", + updates: [ + { type: "text-delta", text: "Done." }, + { type: "turn-ended" }, + { type: "step-started", stepId: 2 }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: { class: "provider_error", message: "Connection failed repeatedly" }, + }, { reason: "the token usage Cursor reported", // Cursor's inputTokens already include cache reads and writes. diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 8fe8fed5917f7..6b04e17c120a1 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -928,9 +928,11 @@ interface CursorProjectionTarget { const MAX_CURSOR_STREAMED_OUTPUT_CHARS = 256 * 1024; // After a turn ends, a retryable stream error can make Cursor's SDK resume from // an older checkpoint inside the same run. When those resumes save nothing, it -// ends the run with this error even though the answer was already delivered. -const CURSOR_RESUME_NO_PROGRESS_MESSAGE = - "Agent turn stopped after repeated resume attempts made no progress"; +// ends with either retry limit even though the answer was already delivered. +const CURSOR_POST_TURN_RETRY_ERRORS = new Set([ + "Agent turn stopped after repeated resume attempts made no progress", + "Connection failed repeatedly", +]); interface ActiveCursorToolCall { readonly callId: string; @@ -2690,7 +2692,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( const isResumeFailureAfterTurnEnded = (context: ActiveCursorTurn, result: RunResult) => context.turnEnded && result.status === "error" && - result.error?.message === CURSOR_RESUME_NO_PROGRESS_MESSAGE; + CURSOR_POST_TURN_RETRY_ERRORS.has(result.error?.message ?? ""); const terminalStatus = ( context: ActiveCursorTurn, From 074a0d35be9ff1e55355bbc2e12715b12d7b56d3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:05:07 -0800 Subject: [PATCH 148/162] fix(server): startup PR backfill looks up each repository branch once (#41175) --- .../ThreadPullRequestService.test.ts | 99 +++++++++++++++++++ .../ThreadPullRequestService.ts | 55 ++++++++--- 2 files changed, 138 insertions(+), 16 deletions(-) diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts index e80faac5c1902..11710743816f9 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.test.ts @@ -800,6 +800,105 @@ describe("ThreadPullRequestServiceV2 reads", () => { }), ); + it.effect("startup backfill looks up a branch once for threads whose worktrees are gone", () => + Effect.gen(function* () { + // Removed worktree folders all fall back to the project root, so they share one lookup. + const shared = ["a", "b", "c", "d"].map((suffix) => ({ + ...threadShell(`gone-worktree-${suffix}`), + branch: "feature/shared", + worktreePath: `/workspace/worktrees/gone-${suffix}`, + settledAt: NOW, + })); + // Every start repeats the backfill, so it reads only the most recently updated threads. + const older = Array.from({ length: 100 }, (_, index) => ({ + ...threadShell(`old-${index}`), + branch: `t3/old-${index}`, + worktreePath: `/workspace/worktrees/old-${index}`, + settledAt: NOW, + updatedAt: DateTime.subtract(NOW, { minutes: index + 1 }), + })); + const threads = [...older.toReversed(), ...shared]; + const project: OrchestrationProjectShell = { + id: threads[0]!.projectId, + title: "Project", + workspaceRoot: "/workspace/project", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-08-01T00:00:00.000Z", + updatedAt: "2026-08-01T00:00:00.000Z", + }; + const activation = yield* Deferred.make(); + const sweeps = yield* Queue.unbounded(); + const lookups: Array<{ readonly cwd: string; readonly branch: string }> = []; + const dependencies = Layer.mergeAll( + Layer.mock(Orchestrator.OrchestratorV2)({ + streamDomainEvents: Stream.never, + getPullRequestSnapshot: () => + Queue.offer(sweeps, undefined).pipe( + Effect.as({ + schemaVersion: 2, + snapshotSequence: 1, + threads, + archivedThreads: [], + }), + ), + }), + Layer.mock(ProjectStore.ProjectStoreV2)({ + listShells: () => Effect.succeed([project]), + getShell: () => Effect.succeedSome(project), + }), + Layer.mock(GitManager.GitManager)({ + branchPullRequest: (input) => + Effect.sync(() => { + lookups.push({ cwd: input.cwd, branch: input.branch }); + return null; + }), + }), + Layer.mock(PullRequestService.PullRequestService)({ + notifyLinkedThreadsChanged: Effect.void, + }), + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({ + resolve: () => + Effect.succeed({ + canonicalKey: "github.com/acme/project", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "git@github.com:acme/project.git", + }, + provider: SourceControlProviderKind.make("github"), + owner: "acme", + name: "project", + }), + }), + Layer.mock(BackgroundPolicy.BackgroundPolicy)({ + shouldRunScopeWork: () => Effect.succeed(true), + shouldRunOpportunisticWork: Effect.succeed(true), + }), + Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)), + Layer.succeed( + SecureRandom.SecureRandom, + SecureRandom.make((size) => new Uint8Array(size).fill(1)), + ), + FileSystem.layerNoop({}), + Path.layer, + ); + yield* Effect.gen(function* () { + const service = yield* ThreadPullRequestService.make; + yield* service.start(); + yield* Deferred.succeed(activation, undefined); + + yield* Queue.take(sweeps); + yield* service.drain; + + expect(lookups.map((lookup) => lookup.branch).toSorted()).toEqual( + ["feature/shared", ...older.slice(0, 60).map((thread) => thread.branch)].toSorted(), + ); + expect(lookups.every((lookup) => lookup.cwd === project.workspaceRoot)).toBe(true); + }).pipe(Effect.provide(dependencies)); + }), + ); + it.effect.each([ { state: "open", checkedOut: false }, { state: "merged", checkedOut: false }, diff --git a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts index 5c32dda1d183c..762c2f71c6d33 100644 --- a/apps/server/src/orchestration-v2/ThreadPullRequestService.ts +++ b/apps/server/src/orchestration-v2/ThreadPullRequestService.ts @@ -110,6 +110,7 @@ export function projectWorkspaceMatchesSnapshot( } const BACKFILL_ATTEMPTS = 5; +const BACKFILL_THREADS = 64; const REPOSITORY_LOOKUP_CONCURRENCY = 4; interface RefreshRequest { @@ -237,13 +238,23 @@ export const make = Effect.gen(function* () { const projects = new Map(projectShells.map((project) => [project.id, project])); const nowMs = DateTime.toEpochMillis(yield* DateTime.now); if (request.backfill) { - for (const thread of snapshotThreads) { - if ( + // Nothing records a lookup that found no pull request, so every start repeats this. + // Only the most recently updated threads are read; older ones wait for their own events. + const candidates = snapshotThreads.filter( + (thread) => + thread.archivedAt === null && + thread.branch !== null && (thread.settledOverride === "settled" || thread.settledAt !== null) && - thread.branchPullRequest == null - ) { - pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS); - } + thread.branchPullRequest == null, + ); + const recent = candidates + .toSorted( + (left, right) => + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), + ) + .slice(0, BACKFILL_THREADS); + for (const thread of recent) { + pendingBackfill.set(thread.id, BACKFILL_ATTEMPTS); } } const visibleThreadIds = new Set( @@ -261,8 +272,28 @@ export const make = Effect.gen(function* () { pendingBackfill.has(thread.id)) && (thread.branch !== null || thread.branchPullRequest != null), ); + // Threads whose worktree is gone fall back to the project root, so they share its lookup. + // A worktree folder can outlive its .git, and git there fails with not_a_repository. + // An unreadable .git keeps the worktree rather than failing the whole group. + const lookupCwds = new Map(); + yield* Effect.forEach( + threads, + (thread) => + Effect.gen(function* () { + const project = projects.get(thread.projectId); + const cwd = + thread.worktreePath !== null && + (yield* fileSystem + .exists(path.join(thread.worktreePath, ".git")) + .pipe(Effect.orElseSucceed(() => true))) + ? thread.worktreePath + : (project?.workspaceRoot ?? null); + lookupCwds.set(thread.id, cwd); + }), + { concurrency: 32, discard: true }, + ); const groups = Map.groupBy(threads, (thread) => - JSON.stringify([thread.projectId, thread.worktreePath, thread.branch]), + JSON.stringify([thread.projectId, lookupCwds.get(thread.id), thread.branch]), ); // A thread's own events and a backfill read at once; only scheduled sweeps wait. @@ -298,15 +329,7 @@ export const make = Effect.gen(function* () { refresh: request.refresh, }); if (first.branch !== null && repository === null) return finishBackfill(group); - // A worktree folder can outlive its .git, and git there fails with not_a_repository. - // An unreadable .git keeps the worktree rather than failing the whole group. - const cwd = - first.worktreePath !== null && - (yield* fileSystem - .exists(path.join(first.worktreePath, ".git")) - .pipe(Effect.orElseSucceed(() => true))) - ? first.worktreePath - : project.workspaceRoot; + const cwd = lookupCwds.get(first.id) ?? project.workspaceRoot; // A detected PR is confirmed against fresh git state before it is saved. const detected = first.branch === null From 8a17857870487f7a475a306d8dadfc264039f5d6 Mon Sep 17 00:00:00 2001 From: Isaac-b-ux Date: Sun, 22 Nov 2026 22:13:10 -0500 Subject: [PATCH 149/162] perf(mobile): avoid re-rendering on shell updates in useSidebarRowThreadKey (#41143) Co-authored-by: Isaac-b-ux <264455269+Isaac-b-ux@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../threads/useSidebarRowThreadKey.test.tsx | 94 +++++++++++++++++++ .../threads/useSidebarRowThreadKey.ts | 24 ++++- apps/mobile/vite.config.ts | 1 + 3 files changed, 114 insertions(+), 5 deletions(-) create mode 100644 apps/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx diff --git a/apps/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx b/apps/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx new file mode 100644 index 0000000000000..ef58c0571ce0c --- /dev/null +++ b/apps/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx @@ -0,0 +1,94 @@ +import { act, useLayoutEffect } from "react"; +import { createRoot } from "react-dom/client"; +import { RegistryContext } from "@effect/atom-react"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { type Atom, AtomRegistry } from "effect/reactivity"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { scopedThreadKey } from "../../lib/scopedEntities"; +import { environmentThreadShells } from "../../state/threads"; +import { makeThreadShellFixture } from "../../test-fixtures"; +import { useSidebarRowThreadKey } from "./useSidebarRowThreadKey"; + +vi.mock("../../state/threads", async () => { + const { Atom: ReactivityAtom } = await import("effect/reactivity"); + return { + environmentThreadShells: { + quietThreadShellsAtom: ReactivityAtom.make([]).pipe( + ReactivityAtom.keepAlive, + ), + }, + }; +}); + +const quietThreadShellsAtom = environmentThreadShells.quietThreadShellsAtom as Atom.Writable< + readonly EnvironmentThreadShell[] +>; + +describe("useSidebarRowThreadKey", () => { + it("re-renders only when the resolved row key changes", async () => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + using _globals = { [Symbol.dispose]: () => vi.unstubAllGlobals() }; + const registry = AtomRegistry.make(); + using _registry = { [Symbol.dispose]: () => registry.dispose() }; + + const envId = EnvironmentId.make("env-1"); + const parentId = ThreadId.make("thread-parent"); + const childId = ThreadId.make("thread-child"); + const parentKey = scopedThreadKey(envId, parentId); + const childKey = scopedThreadKey(envId, childId); + const parentThread = makeThreadShellFixture({ + environmentId: envId, + id: parentId, + title: "Parent", + }); + const childThread = makeThreadShellFixture({ + environmentId: envId, + id: childId, + title: "Delegated child", + delegatedFrom: { environmentId: envId, threadId: parentId, title: "Parent" }, + }); + const otherThread = (title: string) => + makeThreadShellFixture({ environmentId: envId, id: ThreadId.make("thread-other"), title }); + + registry.set(quietThreadShellsAtom, [parentThread, childThread, otherThread("v1")]); + + const seen: Array = []; + function Probe(props: { openThreadKey: string | null }) { + const value = useSidebarRowThreadKey(props.openThreadKey); + useLayoutEffect(() => { + seen.push(value); + }); + return null; + } + + const root = createRoot(document.createElement("div")); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + const renderKey = (openThreadKey: string | null) => + act(async () => + root.render( + + + , + ), + ); + const setShells = (shells: readonly EnvironmentThreadShell[]) => + act(async () => registry.set(quietThreadShellsAtom, shells)); + + await renderKey(null); + await setShells([parentThread, childThread, otherThread("v2")]); + expect(seen).toEqual([null]); + + await renderKey(childKey); + await setShells([parentThread, childThread, otherThread("v3")]); + expect(seen).toEqual([null, parentKey]); + + await setShells([ + { ...parentThread, archivedAt: "2026-01-02T00:00:00.000Z" }, + childThread, + otherThread("v3"), + ]); + expect(seen).toEqual([null, parentKey, childKey]); + }); +}); diff --git a/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts b/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts index 0e72dad60ca0d..a08efc2a0886a 100644 --- a/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts +++ b/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts @@ -1,15 +1,29 @@ import { useAtomValue } from "@effect/atom-react"; import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import { resolveListedAncestorThreadRef } from "@t3tools/client-runtime/state/threads"; +import { Atom } from "effect/reactivity"; import { scopedThreadKey } from "../../lib/scopedEntities"; import { environmentThreadShells } from "../../state/threads"; +const NULL_ROW_KEY_ATOM = Atom.make(null); + +// Deriving the resolved key inside an atom family avoids subscribing to the full shell list when +// no row is selected (phone portrait) and avoids re-rendering on shell frames that do not change +// the open thread's listed ancestor row. +const sidebarRowThreadKeyAtom = Atom.family((openThreadKey: string) => + Atom.make((get): string | null => { + const openThreadRef = parseScopedThreadKey(openThreadKey); + if (openThreadRef === null) return openThreadKey; + const threads = get(environmentThreadShells.quietThreadShellsAtom); + const rowRef = resolveListedAncestorThreadRef(openThreadRef, threads); + return scopedThreadKey(rowRef.environmentId, rowRef.threadId); + }), +); + /** An open subagent, side chat or delegated task has no row; its listed ancestor's row is selected. */ export function useSidebarRowThreadKey(openThreadKey: string | null): string | null { - const threads = useAtomValue(environmentThreadShells.quietThreadShellsAtom); - const openThreadRef = openThreadKey === null ? null : parseScopedThreadKey(openThreadKey); - if (openThreadRef === null) return openThreadKey; - const rowRef = resolveListedAncestorThreadRef(openThreadRef, threads); - return scopedThreadKey(rowRef.environmentId, rowRef.threadId); + return useAtomValue( + openThreadKey === null ? NULL_ROW_KEY_ATOM : sidebarRowThreadKeyAtom(openThreadKey), + ); } diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index ee001a3a5e3d4..436cea63f4f28 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -51,6 +51,7 @@ const reactTests = [ "src/features/terminal/useTerminalExitNavigation.test.tsx", "src/features/threads/use-thread-list-now.test.tsx", "src/features/threads/use-composer-command-menu.select.test.tsx", + "src/features/threads/useSidebarRowThreadKey.test.tsx", "src/features/threads/useThreadListV2.test.tsx", "src/features/home/home-list-options.test.tsx", "src/features/home/home-route-visibility.test.tsx", From 1a4932efd06eff5efce4c19072cd598a9d393d42 Mon Sep 17 00:00:00 2001 From: Alex Southwell Date: Mon, 23 Nov 2026 14:15:05 +1100 Subject: [PATCH 150/162] perf(client): skip child indexing when no child needs input (#25537) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: SAPHID Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> Co-authored-by: Claude Fable 5.2 --- .../src/state/threadShell.test.ts | 31 +++++++++++++++++++ .../client-runtime/src/state/threadShell.ts | 16 +++++++++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index de1bc04aeda8a..9210949afb737 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -61,6 +61,35 @@ function makeHarness(environmentIds: ReadonlyArray = [environment } describe("v2 thread shell lists", () => { + it("builds no child index while no child asks for input", () => { + const { registry, threads, snapshotAtom } = makeHarness(); + let parentIdReads = 0; + const child = { + ...v2ThreadShell, + id: ThreadId.make("child"), + creationSource: "mcp" as const, + lineage: { + rootThreadId: v2ThreadShell.id, + relationshipToParent: "subagent" as const, + // Nothing is pending, so only the child index would read parent ids. + get parentThreadId() { + parentIdReads++; + return v2ThreadShell.id; + }, + }, + }; + const inputs = threads.childThreadInputsAtom({ environmentId, threadId: v2ThreadShell.id }); + const dispose = registry.mount(inputs); + registry.set(snapshotAtom(environmentId), { + ...v2ShellSnapshot, + threads: [v2ThreadShell, child], + }); + expect(registry.get(inputs)).toEqual([]); + expect(parentIdReads).toBe(0); + dispose(); + registry.dispose(); + }); + it("preserves ordered reference arrays when a middle thread changes", () => { const { registry, threads, snapshotAtom } = makeHarness(); const snapshot = { @@ -160,6 +189,8 @@ describe("v2 thread shell lists", () => { threads: [root, { ...legacyChild, status: "completed" as const }], }); expect(registry.get(inputs)).toEqual([]); + registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [root, child] }); + expect(registry.get(inputs).map((thread) => thread.id)).toEqual([child.id]); dispose(); registry.dispose(); }); diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index d5c60570b0a18..3325346d5d153 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -147,6 +147,9 @@ function sideChatRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReq return kind === "user_input" ? "user_input" : "approval"; } +const asksParent = (thread: OrchestrationV2ThreadShell) => + subagentRequest(thread) !== null || sideChatRequest(thread) !== null; + /** * The threads to flag for a subagent's live approval, up its * subagent chain and through a side chat to its parent. `delegated` are tasks this @@ -496,12 +499,23 @@ export function createEnvironmentThreadShellAtoms(input: { }).pipe(Atom.withLabel(`environment-quiet-thread-shell:${key}`)); }); + const hasChildThreadInputsAtom = Atom.make((get) => { + for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { + if (get(environmentThreadsAtom(environmentId)).some(asksParent)) return true; + } + return false; + }).pipe(Atom.withLabel("environment-has-child-thread-inputs")); + // Child approvals and questions are hidden with their sidebar rows. Read their // shell summaries, without subscribing to every child transcript. A task // delegated to a linked environment is a child too, with its own subagents. const childThreadInputsAtomFamily = Atom.family((key: string) => { let previous: ReadonlyArray = []; return Atom.make((get) => { + if (!get(hasChildThreadInputsAtom)) { + if (previous.length !== 0) previous = []; + return previous; + } const children = new Map< string, Array<{ environmentId: EnvironmentId; thread: OrchestrationV2ThreadShell }> @@ -537,7 +551,7 @@ export function createEnvironmentThreadShellAtoms(input: { if (seen.has(childKey)) continue; seen.add(childKey); pending.push(childKey); - if (subagentRequest(thread) !== null || sideChatRequest(thread) !== null) { + if (asksParent(thread)) { next.push( scopedThread(environmentId, thread, get(pendingSubagentRequestsAtom(environmentId))), ); From 86349553c5aeb24196905368bcf5d25c70da626a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bazyli=20Brz=C3=B3ska?= Date: Sun, 22 Nov 2026 19:17:25 -0800 Subject: [PATCH 151/162] fix(server): app links no longer leave the preview stuck loading (#41168) Co-authored-by: Julius Marminge --- apps/server/src/preview/ServerBrowser.test.ts | 35 ++++++++++++ apps/server/src/preview/ServerBrowser.ts | 19 ++++++- packages/shared/package.json | 4 ++ packages/shared/src/appLinks.test.ts | 32 +++++++++++ packages/shared/src/appLinks.ts | 22 ++++++++ ...rver-preview-app-link-stops-loading.e2e.ts | 53 +++++++++++++++++++ 6 files changed, 164 insertions(+), 1 deletion(-) create mode 100644 packages/shared/src/appLinks.test.ts create mode 100644 packages/shared/src/appLinks.ts create mode 100644 scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index a15378ec3039c..d8e5f0622241c 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -2144,6 +2144,41 @@ it.effect("a request whose frame is not available yet is not a main navigation", ).pipe(Effect.provide(layer)), ); +it.effect("an app link's aborted request leaves the page it was clicked on", () => + Effect.scoped( + Effect.gen(function* () { + const { broker, tabId } = yield* ready; + const page = contexts[0]!.page; + const navigation = (url: string, redirectedFrom: unknown = null) => ({ + url: () => url, + method: () => "GET", + isNavigationRequest: () => true, + redirectedFrom: () => redirectedFrom, + frame: () => page, + failure: () => ({ errorText: "net::ERR_ABORTED" }), + }); + const loading = Effect.map( + broker.invoke({ scope, tabId, operation: "status", input: {} }), + (status) => status.loading, + ); + // Chromium hands the link to the OS, aborts the request and keeps the current page. + const direct = navigation("obsidian://open?vault=notes"); + page.emit("request", direct); + page.emit("requestfailed", direct); + expect(yield* loading).toBe(false); + + // A page that redirects to an app link ends its navigation there; the redirect itself finished. + const open = navigation("https://example.com/open"); + page.emit("request", open); + expect(yield* loading).toBe(true); + const redirected = navigation("obsidian://open?vault=notes", open); + page.emit("request", redirected); + page.emit("requestfailed", redirected); + expect(yield* loading).toBe(false); + }), + ).pipe(Effect.provide(layer)), +); + it.effect.each(["before", "during"] as const)( "a navigation that fails while a load reads its title keeps its failure (request %s read)", (requestTiming) => diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 26203fc1a63c8..9fd94232a5e23 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -51,6 +51,7 @@ import { import { AgentScope, agentScopeLauncherScript } from "@t3tools/shared/AgentScope"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { appLinkUrl } from "@t3tools/shared/appLinks"; import { normalizePreviewUrl } from "@t3tools/shared/preview"; import { resolvePreviewViewport } from "@t3tools/shared/previewViewport"; import * as NodeCrypto from "node:crypto"; @@ -1245,15 +1246,31 @@ const make = Effect.gen(function* () { } // Playwright's `request.frame()` throws for a request issued before its frame exists, and a // throw from a page listener is uncaught, so such a request is not a main-frame navigation. - const isMainNavigation = (request: { isNavigationRequest(): boolean; frame(): unknown }) => { + const isMainFrameNavigation = (request: { + isNavigationRequest(): boolean; + frame(): unknown; + }) => { try { return request.isNavigationRequest() && request.frame() === page.mainFrame(); } catch { return false; } }; + // Chromium aborts an app link's request and keeps the page, so it is no navigation. + const isMainNavigation = (request: { + isNavigationRequest(): boolean; + url(): string; + frame(): unknown; + }) => appLinkUrl(request.url()) === null && isMainFrameNavigation(request); const navigationGenerations = new WeakMap(); page.on("request", (request) => { + if (appLinkUrl(request.url()) !== null && isMainFrameNavigation(request)) { + // A redirect into an app link ends the navigation that led there. + const redirectedFrom = request.redirectedFrom(); + const generation = redirectedFrom && navigationGenerations.get(redirectedFrom); + if (generation) settleAbortedNavigation(tab, generation, request.url(), undefined); + return; + } if (!isMainNavigation(request)) return; // Playwright can deliver the first request after Stop has already settled its navigation. const stoppedInitialRequest = diff --git a/packages/shared/package.json b/packages/shared/package.json index b727b976fe143..d12cd9b003982 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -151,6 +151,10 @@ "types": "./src/toolOutput.ts", "import": "./src/toolOutput.ts" }, + "./appLinks": { + "types": "./src/appLinks.ts", + "import": "./src/appLinks.ts" + }, "./htmlRender": { "types": "./src/htmlRender.ts", "import": "./src/htmlRender.ts" diff --git a/packages/shared/src/appLinks.test.ts b/packages/shared/src/appLinks.test.ts new file mode 100644 index 0000000000000..2e3556803208f --- /dev/null +++ b/packages/shared/src/appLinks.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { appLinkUrl } from "./appLinks.ts"; + +describe("appLinkUrl", () => { + it("accepts schemes another app opens", () => { + expect(appLinkUrl("obsidian://open?vault=vault&file=Note")).toBe( + "obsidian://open?vault=vault&file=Note", + ); + expect(appLinkUrl("t3-thread://v2/env/thread")).toBe("t3-thread://v2/env/thread"); + expect(appLinkUrl("mailto:a@example.com")).toBe("mailto:a@example.com"); + }); + + it("rejects schemes the browser loads itself, and non-URLs", () => { + for (const url of [ + "https://example.com", + "http://example.com", + "javascript:alert(1)", + "JavaScript:alert(1)", + "data:text/html,x", + "file:///etc/passwd", + "blob:https://example.com/id", + "about:blank", + "view-source:https://example.com", + "chrome://settings", + "filesystem:https://example.com/temporary/a", + "not a url", + ]) { + expect(appLinkUrl(url), url).toBeNull(); + } + }); +}); diff --git a/packages/shared/src/appLinks.ts b/packages/shared/src/appLinks.ts new file mode 100644 index 0000000000000..85ebe6a6922f7 --- /dev/null +++ b/packages/shared/src/appLinks.ts @@ -0,0 +1,22 @@ +/** Schemes the browser engine loads itself; every other scheme names an app the OS opens. */ +const BROWSER_PROTOCOLS = [ + "about:", + "blob:", + "chrome:", + "data:", + "devtools:", + "file:", + "filesystem:", + "http:", + "https:", + "javascript:", + "view-source:", +]; + +const browserProtocols: ReadonlySet = new Set(BROWSER_PROTOCOLS); + +/** The normalized URL when it is an app link, such as `obsidian:` or `mailto:`, otherwise null. */ +export function appLinkUrl(rawUrl: string): string | null { + const url = URL.parse(rawUrl); + return url === null || browserProtocols.has(url.protocol) ? null : url.href; +} diff --git a/scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts b/scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts new file mode 100644 index 0000000000000..2aa4c70a1fa12 --- /dev/null +++ b/scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts @@ -0,0 +1,53 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - one fixture page for the server's browser to load +import * as NodeHttp from "node:http"; + +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +// One app link that fills the page. Its click renames the page a moment later, after the server +// has seen the link's request. +const PAGE = ` +Note link +Open the note`; + +test( + "An app link clicked in the Browser leaves the page shown and loaded", + WEB, + async ({ t3, app, browser, screen }) => { + const server = NodeHttp.createServer((_request, response) => { + response.writeHead(200, { "content-type": "text/html" }); + response.end(PAGE); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + try { + const address = server.address(); + if (address === null || typeof address === "string") throw new Error("No page port."); + const url = `http://127.0.0.1:${address.port}/`; + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Note check", messages: ["first"] }); + await t3.open(thread); + + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + const addressBar = screen.getByRole("textbox", "Search or enter URL"); + await addressBar.fill(url); + await browser.keyboard.press("Enter"); + await expect(screen.getByText("Note link")).toBeVisible(); + + // The page draws on the canvas beside its input proxy. + await browser.locator('canvas:has(~ textarea[aria-label="Browser page"])').tap(); + try { + // Chromium hands the link to the OS and keeps the page, which goes on renaming itself. + await expect(screen.getByText("Link clicked")).toBeVisible({ timeout: 2_000 }); + await expect(addressBar).toHaveValue(url); + await expect(screen.getByRole("button", "Refresh", { exact: true })).toBeVisible(); + } finally { + await app.screenshot("after-click"); + } + } finally { + await new Promise((resolve) => server.close(resolve)); + } + }, +); From 047a86f5ab43d6330b6b50607049c991624ab1eb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:34:22 -0800 Subject: [PATCH 152/162] fix(server): open Claude sessions on macOS share one process-table poll (#37585) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 120 ++++++++++++------ .../ClaudeAgentSdkQueryRunner.test.ts | 77 +++++++++-- 2 files changed, 147 insertions(+), 50 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 370b6b6c4c3f6..f6d84df4dcda9 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -534,40 +534,75 @@ function claudeDescendants( return found; } -/** What a CLI started, by pid and start time, recorded from each process table read while it runs. */ -export function makeClaudeDescendantTracker( - cliPid: number, +const processIdentity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`; + +/** What one CLI started, by pid and start time, recorded from each process table read while it runs. */ +function makeClaudeDescendantTracker(cliPid: number) { + const tracked = new Map(); + // After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots. + const record = (rows: ReadonlyArray, cliRunning: boolean) => { + const running = new Set(rows.map(processIdentity)); + // `ps -A` lists itself, so no rows is a failed read. + if (rows.length === 0) return running; + const roots = cliRunning ? [cliPid] : []; + for (const [key, row] of tracked) { + if (running.has(key)) roots.push(row.pid); + else tracked.delete(key); + } + for (const row of claudeDescendants(rows, roots)) tracked.set(processIdentity(row), row); + return running; + }; + return { tracked: tracked as ReadonlyMap, record }; +} + +/** + * Process table reads for every running CLI. A poll reads the table once for all of them, so the + * `ps` cost does not grow with open sessions. + */ +export function makeClaudeDescendantPoll( readProcessTable: Effect.Effect>, ) { - const tracked = new Map(); - const identity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`; - // The poll, a session close and the exit read one at a time, so each table is newer than all - // recorded here, and a pid and start time it no longer lists never run again. + const live = new Set>(); + // Polls, session closes and exits read one at a time, so each table is newer than all recorded, + // and a pid and start time it no longer lists never run again. const reading = Semaphore.makeUnsafe(1); - // After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots. - const refresh = Effect.fn("ClaudeAgentSdkQueryRunner.trackDescendants")( - function* (cliRunning: boolean) { - const rows = yield* readProcessTable; - const running = new Set(rows.map(identity)); - // `ps -A` lists itself, so no rows is a failed read. - if (rows.length === 0) return running; - const roots = cliRunning ? [cliPid] : []; - for (const [key, row] of tracked) { - if (running.has(key)) roots.push(row.pid); - else tracked.delete(key); - } - for (const row of claudeDescendants(rows, roots)) tracked.set(identity(row), row); - return running; - }, - (effect) => reading.withPermits(1)(effect), - ); + const read = (apply: (rows: ReadonlyArray) => A) => + reading.withPermits(1)(readProcessTable.pipe(Effect.map(apply))); return { - tracked: tracked as ReadonlyMap, - refresh: refresh(true).pipe(Effect.asVoid), - /** Reads the table after the CLI exited: what it left that is still the same process. */ - leftovers: refresh(false).pipe( - Effect.map((running) => [...tracked.values()].filter((row) => running.has(identity(row)))), - ), + // A table read before a CLI started may list an older process under its pid, so a poll records + // only into the CLIs tracked when its read began. + poll: reading + .withPermits(1)( + Effect.suspend(() => { + const tracked = [...live]; + return readProcessTable.pipe( + Effect.map((rows) => { + for (const tracker of tracked) if (live.has(tracker)) tracker.record(rows, true); + }), + ); + }), + ) + .pipe(Effect.withSpan("ClaudeAgentSdkQueryRunner.trackDescendants")), + track: (cliPid: number) => { + const tracker = makeClaudeDescendantTracker(cliPid); + live.add(tracker); + return { + tracked: tracker.tracked, + refresh: read((rows) => void tracker.record(rows, true)), + /** Reads the table after the CLI exited: what it left that is still the same process. */ + leftovers: Effect.sync(() => live.delete(tracker)).pipe( + Effect.andThen( + read((rows) => { + const running = tracker.record(rows, false); + return [...tracker.tracked.values()].filter((row) => + running.has(processIdentity(row)), + ); + }), + ), + ), + }; + }, + hasLive: () => live.size > 0, }; } @@ -1549,8 +1584,24 @@ export const layerQueryRunner: Layer.Layer< // Without an agent scope, a job that left the CLI's group escapes the group kill and is // re-parented once the CLI exits. So the CLI's tree is recorded while it runs, and what is // still the same process (pid and start time) is stopped after it exits. + const descendantPoll = makeClaudeDescendantPoll(readProcessTable); + // One poll serves every CLI. The first tracked CLI starts it; it stops once none is left. + let polling: Fiber.Fiber | undefined; const trackDescendants = (cliPid: number) => { - const tracker = makeClaudeDescendantTracker(cliPid, readProcessTable); + const tracker = descendantPoll.track(cliPid); + polling ??= runFork( + descendantPoll.poll.pipe( + Effect.repeat({ + schedule: Schedule.spaced(CLAUDE_DESCENDANT_POLL), + // Cleared in the same step that ends the poll, so the next tracked CLI starts a new one. + while: () => { + if (descendantPoll.hasLive()) return true; + polling = undefined; + return false; + }, + }), + ), + ); const stop = tracker.leftovers.pipe( Effect.map((rows) => { for (const row of rows) killClaudeDescendant(row); @@ -1666,12 +1717,7 @@ export const layerQueryRunner: Layer.Layer< ); if (unit === undefined && child.pid !== undefined) { const tracker = trackDescendants(child.pid); - const polling = runFork( - tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))), - ); - child.once("exit", () => - runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))), - ); + child.once("exit", () => runFork(tracker.stop)); refreshDescendants = tracker.refresh; } return child; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 2bf2763c58c66..431ee35e27187 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -31,7 +31,7 @@ import { ClaudeAgentSdkQueryRunner, type ClaudeAgentSdkQueryOpenInput, layerQueryRunner, - makeClaudeDescendantTracker, + makeClaudeDescendantPoll, spawnClaudeProcessGroup, } from "./ClaudeAdapterV2.ts"; @@ -734,10 +734,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro "keeps only the descendants the CLI still has running, however many jobs it ran", () => { let table: ReadonlyArray> = []; - const tracker = makeClaudeDescendantTracker( - 1000, - Effect.sync(() => table), - ); + const tracker = makeClaudeDescendantPoll(Effect.sync(() => table)).track(1000); const jobs = (poll: number) => [0, 1, 2, 3].map((job) => 1100 + poll * 4 + job); return Effect.gen(function* () { for (let poll = 0; poll < 50; poll++) { @@ -781,10 +778,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro [processRow(1000, 10, 0), ...unrelated, orphan], [...unrelated, orphan], ]; - const tracker = makeClaudeDescendantTracker( - 1000, - Effect.sync(() => tables.shift() ?? []), - ); + const tracker = makeClaudeDescendantPoll(Effect.sync(() => tables.shift() ?? [])).track(1000); return Effect.gen(function* () { yield* tracker.refresh; yield* tracker.refresh; @@ -811,10 +805,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro processRow(1001, 1000, 0), processRow(1100, 1001, 1), ]); - const tracker = makeClaudeDescendantTracker( - 1000, - Effect.suspend(() => read), - ); + const tracker = makeClaudeDescendantPoll(Effect.suspend(() => read)).track(1000); return Effect.gen(function* () { yield* tracker.refresh; read = Deferred.succeed(olderReadStarted, undefined).pipe( @@ -840,6 +831,66 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro }, ); + it.effect("reads the process table once per poll for every running CLI", () => { + let reads = 0; + const descendantPoll = makeClaudeDescendantPoll( + Effect.sync(() => { + reads++; + return [ + processRow(1000, 10, 0), + processRow(1100, 1000, 1), + processRow(2000, 10, 0), + processRow(2100, 2000, 1), + ]; + }), + ); + const first = descendantPoll.track(1000); + const second = descendantPoll.track(2000); + return Effect.gen(function* () { + yield* descendantPoll.poll; + assert.strictEqual(reads, 1); + assert.deepStrictEqual( + [...first.tracked.values()].map((row) => row.pid), + [1100], + ); + assert.deepStrictEqual( + [...second.tracked.values()].map((row) => row.pid), + [2100], + ); + yield* first.leftovers; + assert.isTrue(descendantPoll.hasLive()); + yield* second.leftovers; + assert.isFalse(descendantPoll.hasLive()); + }); + }); + + it.effect("does not record a poll's table into a CLI tracked after the read began", () => { + const readStarted = Deferred.makeUnsafe(); + const table = Deferred.makeUnsafe>>(); + const descendantPoll = makeClaudeDescendantPoll( + Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(table))), + ); + return Effect.gen(function* () { + const first = descendantPoll.track(1000); + const polling = yield* descendantPoll.poll.pipe(Effect.forkChild); + yield* Deferred.await(readStarted); + // The earlier process at pid 2000 exited and the pid went to a newly tracked CLI. + const late = descendantPoll.track(2000); + yield* Deferred.succeed(table, [ + processRow(1000, 10, 0), + processRow(1100, 1000, 1), + processRow(2000, 10, 0), + processRow(2100, 2000, 1), + ]); + yield* Fiber.join(polling); + assert.deepStrictEqual( + [...first.tracked.values()].map((row) => row.pid), + [1100], + ); + assert.strictEqual(late.tracked.size, 0); + }); + }); + const rootRefusal = "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons"; From 18850a5eeb388148fc2b8fa3499bf8e624a1154c Mon Sep 17 00:00:00 2001 From: tiliakoos <73005126+tiliakoos@users.noreply.github.com> Date: Mon, 23 Nov 2026 04:34:29 +0100 Subject: [PATCH 153/162] fix(mobile): screen readers hear when a terminal Ctrl, Alt or Cmd key is latched (#41173) Co-authored-by: MarcoDotIO <20867620+MarcoDotIO@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../mobile/src/components/ComposerToolbar.tsx | 1 + ...nal-latched-modifier-reads-selected.e2e.ts | 41 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 scripts/scenarios/terminal-latched-modifier-reads-selected.e2e.ts diff --git a/apps/mobile/src/components/ComposerToolbar.tsx b/apps/mobile/src/components/ComposerToolbar.tsx index 36ed505d27cd0..a901d6fa60b50 100644 --- a/apps/mobile/src/components/ComposerToolbar.tsx +++ b/apps/mobile/src/components/ComposerToolbar.tsx @@ -376,6 +376,7 @@ export function ComposerToolbarButton(props: { { + const project = await t3.project("demo"); + const { threadId } = await t3.thread({ project, title: "Latched keys", messages: ["hello"] }); + await t3.open(); + await screen.getByText("Latched keys", { exact: false }).first().waitFor({ timeout: 120_000 }); + + const environment = await runPromise( + environmentId(`http://${MOBILE.host}:${MOBILE.serverPort}`), + ); + await device.openLink(`t3code-dev://threads/${environment}/${threadId}/terminal`, { + app: "com.t3tools.t3code.dev", + }); + await device.alert("accept").catch(() => {}); + + // The keyboard toolbar shows with the software keyboard; ctrl starts past its right edge. + const esc = screen.getByRole("button", "esc"); + await esc.waitFor({ timeout: 60_000 }); + const box = await esc.boundingBox(); + const x = (box?.x ?? 0) + (box?.width ?? 0); + const y = (box?.y ?? 0) + (box?.height ?? 0) / 2; + // A slow drag, so the scroller stops with ctrl in view instead of flinging to its end. + await screen.swipe({ from: { x, y }, to: { x: x - 150, y }, duration: 1_500 }); + const ctrl = screen.getByRole("button", "ctrl"); + await ctrl.waitFor(); + await ctrl.tap(); + await app.screenshot("ctrl-latched"); + await expect(ctrl).toBeSelected(); + + await ctrl.tap(); + await expect(ctrl).not.toBeSelected(); + }, +); From 372fbabe5fa6196a32ac0f926aaff402fbf60a09 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:36:25 -0800 Subject: [PATCH 154/162] fix(server): renaming a provider instance no longer stops its sessions (#41189) --- .../provider/ProviderInstanceRegistry.test.ts | 35 +++++++++ .../src/provider/ProviderInstanceRegistry.ts | 70 +++++++++++++++-- .../src/provider/ProviderRegistry.test.ts | 76 +++++++++++++++++++ apps/server/src/provider/ProviderRegistry.ts | 21 +++++ 4 files changed, 194 insertions(+), 8 deletions(-) diff --git a/apps/server/src/provider/ProviderInstanceRegistry.test.ts b/apps/server/src/provider/ProviderInstanceRegistry.test.ts index ce6416332bae0..94c5f3f8c3cfd 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.test.ts @@ -347,6 +347,41 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect.each([{ displayName: "Renamed" }, { accentColor: "#ff0000" }])( + "keeps the live instance when only %o changes", + (presentation) => + Effect.gen(function* () { + let closed = 0; + const driver: typeof CodexDriver = { + ...CodexDriver, + create: (input) => + Effect.gen(function* () { + const instance = yield* CodexDriver.create(input); + yield* Effect.addFinalizer(() => Effect.sync(() => closed++)); + return instance; + }), + }; + const instanceId = ProviderInstanceId.make("account-a"); + const entry = { + driver: CodexDriver.driverKind, + enabled: false, + displayName: "Account A", + config: makeCodexConfig({}), + }; + const { registry, mutator } = yield* makeProviderInstanceRegistry({ + drivers: [driver], + configMap: { [instanceId]: entry }, + }); + const instance = yield* registry.getInstance(instanceId); + const changes = yield* registry.subscribeChanges; + yield* mutator.reconcile({ [instanceId]: { ...entry, ...presentation } }); + expect(closed).toBe(0); + expect(yield* registry.getInstance(instanceId)).toBe(instance); + yield* PubSub.take(changes); + expect(yield* instance!.snapshot.getSnapshot).toMatchObject(presentation); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("treats an explicit in-config enabled:false as disabling despite the envelope", () => Effect.gen(function* () { const staleId = ProviderInstanceId.make("codex_stale"); diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts index 9ab3f56aedcd5..f343093d7c9ef 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.ts @@ -55,6 +55,7 @@ interface LiveEntry { readonly scope: Scope.Closeable; readonly entry: ProviderInstanceConfig; readonly secrets: InstanceSecrets; + readonly setPresentation: (entry: ProviderInstanceConfig) => void; } interface RegistryState { @@ -69,6 +70,55 @@ interface RegistryState { const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean => Equal.equals(a, b); +const withoutPresentation = ({ + displayName: _displayName, + accentColor: _accentColor, + ...runtime +}: ProviderInstanceConfig) => runtime; + +// Display name and accent colour are only labels; changing them must not stop the instance's sessions. +const runtimeEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean => + Equal.equals(withoutPresentation(a), withoutPresentation(b)); + +// Drivers stamp the presentation they were created with into every snapshot, so a renamed +// instance kept live restamps what it reports. +const withLivePresentation = (instance: ProviderInstance, created: ProviderInstanceConfig) => { + let current = created; + const restamp = (snapshot: S): S => { + const next: { -readonly [K in keyof S]: S[K] } = { ...snapshot }; + for (const key of ["displayName", "accentColor"] as const) { + const value = current[key]; + if (value === created[key]) continue; + if (value) next[key] = value; + else delete next[key]; + } + return next; + }; + const { snapshot, snapshotForCwd } = instance; + const wrapped: ProviderInstance = { + ...instance, + get displayName() { + return current.displayName; + }, + get accentColor() { + return current.accentColor; + }, + snapshot: { + ...snapshot, + getSnapshot: Effect.suspend(() => snapshot.getSnapshot).pipe(Effect.map(restamp)), + refresh: Effect.suspend(() => snapshot.refresh).pipe(Effect.map(restamp)), + streamChanges: Stream.suspend(() => snapshot.streamChanges).pipe(Stream.map(restamp)), + }, + ...(snapshotForCwd + ? { snapshotForCwd: (cwd: string) => snapshotForCwd(cwd).pipe(Effect.map(restamp)) } + : {}), + }; + const setPresentation = (entry: ProviderInstanceConfig) => { + current = entry; + }; + return { instance: wrapped, setPresentation }; +}; + const secretReferencesIn = (environment: ProviderInstanceEnvironment): Array => environment.flatMap((variable) => (typeof variable.value === "string" ? [] : [variable.value])); @@ -350,14 +400,10 @@ const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* (input: { const nextEntry = configMap[instanceId]; if ( rebuild.has(instanceId) || - (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) + (nextEntry !== undefined && !runtimeEqual(live.entry, nextEntry)) ) { replacedIds.add(instanceId); } @@ -440,6 +486,7 @@ const makeReconcile = (input: { const builtUnavailable = new Map(); const builtSecretsUnreadable = new Map(); let orderChanged = false; + let presentationChanged = false; const previousOrder = [...previousEntries.keys()]; const nextOrder: Array = []; @@ -449,7 +496,13 @@ const makeReconcile = (input: { const existing = previousEntries.get(instanceId); if (existing !== undefined && !replacedIds.has(instanceId)) { - builtEntries.set(instanceId, existing); + if (entryEqual(existing.entry, entry)) { + builtEntries.set(instanceId, existing); + } else { + existing.setPresentation(entry); + builtEntries.set(instanceId, { ...existing, entry }); + presentationChanged = true; + } continue; } const parked = parkedSnapshot(instanceId, entry); @@ -489,6 +542,7 @@ const makeReconcile = (input: { } const entriesChanged = + presentationChanged || orderChanged || removedIds.length > 0 || replacedIds.size > 0 || diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 69b7bd9eb2c1d..4fe6da7f791a9 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -20,6 +20,7 @@ import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Option from "effect/Option"; import * as Scope from "effect/Scope"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; @@ -2682,6 +2683,81 @@ it.layer( }), ); + it.effect("publishes a new label for an instance the registry kept live", () => + Effect.gen(function* () { + const driver = ProviderDriverKind.make("antigravity"); + const instanceId = ProviderInstanceId.make("account-a"); + let displayName = "Account A"; + const instance: ProviderInstance = { + instanceId, + driverKind: driver, + continuationIdentity: { driverKind: driver, continuationKey: "antigravity:account-a" }, + get displayName() { + return displayName; + }, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driver, + packageName: null, + }), + ), + getSnapshot: Effect.sync(() => ({ + instanceId, + driver, + displayName, + status: "ready" as const, + enabled: true, + installed: true, + auth: { status: "authenticated" as const }, + checkedAt: "1970-01-01T00:00:00.000Z", + version: "1.0.0", + models: [], + slashCommands: [], + skills: [], + })), + refresh: Effect.die("unused"), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + }; + const changes = yield* PubSub.unbounded(); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const services = yield* Layer.build( + ProviderRegistry.layer.pipe( + Layer.provide(layerUnusedMutator), + Layer.provideMerge( + Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, { + getInstance: () => Effect.succeed(instance), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.fromPubSub(changes), + subscribeChanges: PubSub.subscribe(changes), + }), + ), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-label-" }), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ).pipe(Scope.provide(scope)); + const registry = yield* ProviderRegistry.ProviderRegistry.pipe(Effect.provide(services)); + const relabelled = yield* registry.streamChanges.pipe( + Stream.filter((providers) => providers[0]?.displayName === "Account B"), + Stream.runHead, + Effect.forkChild({ startImmediately: true }), + ); + displayName = "Account B"; + yield* PubSub.publish(changes, undefined); + assert.isTrue(Option.isSome(yield* Fiber.join(relabelled))); + }), + ); + it.effect("rescans a requested cwd whose snapshot is still current", () => Effect.gen(function* () { const h = yield* makeWorkspaceRescanHarness; diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 43d66cd1ca049..172599fd29c88 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -1050,6 +1050,27 @@ export const layer = Layer.effect( }).pipe(Effect.ignoreCause({ log: true })), { concurrency: "unbounded", discard: true }, ); + // A rename keeps the instance live, so its new label only arrives from a fresh read. + const published = new Map( + (yield* Ref.get(providersRef)).map((provider) => [provider.instanceId, provider]), + ); + yield* Effect.forEach( + carriedOver.values(), + (instance) => + Effect.gen(function* () { + // Its first check publishes the new label anyway; the placeholder must not replace the cache. + if (yield* instance.snapshot.isAwaitingFirstCheck ?? Effect.succeed(false)) return; + const provider = yield* instance.snapshot.getSnapshot; + const previous = published.get(instance.instanceId); + if ( + previous?.displayName !== provider.displayName || + previous?.accentColor !== provider.accentColor + ) { + yield* syncProvider(provider); + } + }).pipe(Effect.ignoreCause({ log: true })), + { concurrency: "unbounded", discard: true }, + ); yield* upsertProviders(unavailableProviders, { persist: false, replace: true, From 1d61429c02c1b880e55ef436588b1627edc4d381 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:38:40 -0800 Subject: [PATCH 155/162] perf(server): idle agent sessions free their memory after 2 minutes (#41174) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.ts | 94 ++++++++---- .../ClaudeAgentSdkQueryRunner.test.ts | 141 ++++++++++++++---- .../ProviderSessionManager.test.ts | 39 ++++- .../ProviderSessionManager.ts | 29 ++-- 4 files changed, 239 insertions(+), 64 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f6d84df4dcda9..9ff0c8fc16511 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -402,7 +402,7 @@ const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000; const CLAUDE_STDERR_TAIL_LENGTH = 2_048; // The process group is killed on exit, so its stderr closes promptly. const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1); -// How often the CLI's process tree is recorded when no agent scope will stop what it leaves. +// How often a working CLI's process tree is recorded when no agent scope will stop what it leaves. const CLAUDE_DESCENDANT_POLL = "1 second"; // Claude Code's refusal of bypassPermissions as root, which it explains only on stderr. const CLAUDE_ROOT_REFUSAL = @@ -556,8 +556,9 @@ function makeClaudeDescendantTracker(cliPid: number) { } /** - * Process table reads for every running CLI. A poll reads the table once for all of them, so the - * `ps` cost does not grow with open sessions. + * Process table reads for every working CLI. A poll reads the table once for all of them, so the + * `ps` cost does not grow with open sessions. Jobs start only while a CLI works, so an idle CLI is + * left out of polls; its turn ends with one last read. */ export function makeClaudeDescendantPoll( readProcessTable: Effect.Effect>, @@ -570,27 +571,44 @@ export function makeClaudeDescendantPoll( reading.withPermits(1)(readProcessTable.pipe(Effect.map(apply))); return { // A table read before a CLI started may list an older process under its pid, so a poll records - // only into the CLIs tracked when its read began. - poll: reading - .withPermits(1)( - Effect.suspend(() => { - const tracked = [...live]; - return readProcessTable.pipe( - Effect.map((rows) => { - for (const tracker of tracked) if (live.has(tracker)) tracker.record(rows, true); - }), - ); - }), - ) - .pipe(Effect.withSpan("ClaudeAgentSdkQueryRunner.trackDescendants")), + // only into the CLIs working when its read began. + poll: Effect.suspend(() => + live.size === 0 + ? Effect.void + : reading + .withPermits(1)( + Effect.suspend(() => { + const working = [...live]; + return readProcessTable.pipe( + Effect.map((rows) => { + for (const tracker of working) + if (live.has(tracker)) tracker.record(rows, true); + }), + ); + }), + ) + .pipe(Effect.withSpan("ClaudeAgentSdkQueryRunner.trackDescendants")), + ), track: (cliPid: number) => { const tracker = makeClaudeDescendantTracker(cliPid); - live.add(tracker); + let exited = false; + const refresh = read((rows) => void tracker.record(rows, true)); return { tracked: tracker.tracked, - refresh: read((rows) => void tracker.record(rows, true)), + refresh, + /** Polls this CLI from now until its turn settles. */ + work: () => { + if (!exited) live.add(tracker); + }, + settle: Effect.suspend(() => { + live.delete(tracker); + return exited ? Effect.void : refresh; + }), /** Reads the table after the CLI exited: what it left that is still the same process. */ - leftovers: Effect.sync(() => live.delete(tracker)).pipe( + leftovers: Effect.sync(() => { + exited = true; + live.delete(tracker); + }).pipe( Effect.andThen( read((rows) => { const running = tracker.record(rows, false); @@ -1587,8 +1605,7 @@ export const layerQueryRunner: Layer.Layer< const descendantPoll = makeClaudeDescendantPoll(readProcessTable); // One poll serves every CLI. The first tracked CLI starts it; it stops once none is left. let polling: Fiber.Fiber | undefined; - const trackDescendants = (cliPid: number) => { - const tracker = descendantPoll.track(cliPid); + const startPolling = () => { polling ??= runFork( descendantPoll.poll.pipe( Effect.repeat({ @@ -1602,12 +1619,20 @@ export const layerQueryRunner: Layer.Layer< }), ), ); + }; + const trackDescendants = (cliPid: number) => { + const tracker = descendantPoll.track(cliPid); + const work = () => { + tracker.work(); + startPolling(); + }; + work(); const stop = tracker.leftovers.pipe( Effect.map((rows) => { for (const row of rows) killClaudeDescendant(row); }), ); - return { refresh: tracker.refresh, stop }; + return { refresh: tracker.refresh, work, settle: tracker.settle, stop }; }; // The open span below is the tracing boundary for both attempts. @@ -1700,7 +1725,7 @@ export const layerQueryRunner: Layer.Layer< if (answered) return; stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH); }; - let refreshDescendants: Effect.Effect = Effect.void; + let descendants: ReturnType | undefined; const spawnProcess = options.spawnClaudeCodeProcess ?? ((spawnOptions: ClaudeSpawnOptions) => { @@ -1718,7 +1743,7 @@ export const layerQueryRunner: Layer.Layer< if (unit === undefined && child.pid !== undefined) { const tracker = trackDescendants(child.pid); child.once("exit", () => runFork(tracker.stop)); - refreshDescendants = tracker.refresh; + descendants = tracker; } return child; } @@ -1899,6 +1924,16 @@ export const layerQueryRunner: Layer.Layer< } }), ), + // The result waits for the turn's last tree read, so a session closed on it keeps that job. + Stream.tap((message) => + descendants === undefined + ? Effect.void + : message.type === "result" + ? descendants.settle + : message.type === "assistant" + ? Effect.sync(descendants.work) + : Effect.void, + ), Stream.tap((message) => logProtocolEvent({ direction: "incoming", @@ -1910,7 +1945,12 @@ export const layerQueryRunner: Layer.Layer< offer: (message, onQueued) => Effect.uninterruptibleMask((restore) => restore(Queue.offer(promptQueue, message)).pipe( - Effect.tap(() => Effect.sync(() => onQueued?.())), + Effect.tap(() => + Effect.sync(() => { + descendants?.work(); + onQueued?.(); + }), + ), ), ).pipe( Effect.asVoid, @@ -2101,7 +2141,9 @@ export const layerQueryRunner: Layer.Layer< ), ), // A job started since the last poll is recorded before the CLI is told to exit. - close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe( + close: Effect.suspend(() => + processExited || descendants === undefined ? Effect.void : descendants.refresh, + ).pipe( Effect.andThen(Queue.shutdown(promptQueue)), Effect.andThen(closeClaudeQuery(queryRuntime)), Effect.tap(() => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 431ee35e27187..76439d76924b5 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -18,6 +18,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Stream from "effect/Stream"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; @@ -831,7 +832,7 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro }, ); - it.effect("reads the process table once per poll for every running CLI", () => { + it.effect("reads the process table once per poll for every working CLI", () => { let reads = 0; const descendantPoll = makeClaudeDescendantPoll( Effect.sync(() => { @@ -847,6 +848,8 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro const first = descendantPoll.track(1000); const second = descendantPoll.track(2000); return Effect.gen(function* () { + first.work(); + second.work(); yield* descendantPoll.poll; assert.strictEqual(reads, 1); assert.deepStrictEqual( @@ -859,37 +862,121 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro ); yield* first.leftovers; assert.isTrue(descendantPoll.hasLive()); - yield* second.leftovers; + // A settled turn reads the table once more, then idles out of polls. + yield* second.settle; + assert.strictEqual(reads, 3); assert.isFalse(descendantPoll.hasLive()); + yield* descendantPoll.poll; + assert.strictEqual(reads, 3); }); }); - it.effect("does not record a poll's table into a CLI tracked after the read began", () => { - const readStarted = Deferred.makeUnsafe(); - const table = Deferred.makeUnsafe>>(); - const descendantPoll = makeClaudeDescendantPoll( - Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(table))), - ); - return Effect.gen(function* () { - const first = descendantPoll.track(1000); - const polling = yield* descendantPoll.poll.pipe(Effect.forkChild); - yield* Deferred.await(readStarted); - // The earlier process at pid 2000 exited and the pid went to a newly tracked CLI. - const late = descendantPoll.track(2000); - yield* Deferred.succeed(table, [ - processRow(1000, 10, 0), - processRow(1100, 1000, 1), - processRow(2000, 10, 0), - processRow(2100, 2000, 1), - ]); - yield* Fiber.join(polling); - assert.deepStrictEqual( - [...first.tracked.values()].map((row) => row.pid), - [1100], + it.effect( + "does not record a poll's table into a CLI that started working after the read began", + () => { + const readStarted = Deferred.makeUnsafe(); + const table = Deferred.makeUnsafe>>(); + const descendantPoll = makeClaudeDescendantPoll( + Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(table))), ); - assert.strictEqual(late.tracked.size, 0); - }); - }); + return Effect.gen(function* () { + const first = descendantPoll.track(1000); + first.work(); + const polling = yield* descendantPoll.poll.pipe(Effect.forkChild); + yield* Deferred.await(readStarted); + // The earlier process at pid 2000 exited and the pid went to a newly tracked CLI. + const late = descendantPoll.track(2000); + late.work(); + yield* Deferred.succeed(table, [ + processRow(1000, 10, 0), + processRow(1100, 1000, 1), + processRow(2000, 10, 0), + processRow(2100, 2000, 1), + ]); + yield* Fiber.join(polling); + assert.deepStrictEqual( + [...first.tracked.values()].map((row) => row.pid), + [1100], + ); + assert.strictEqual(late.tracked.size, 0); + }); + }, + ); + + it.effect("reads the CLI's process tree once when its turn ends and not while it is idle", () => + Effect.gen(function* () { + const cli = fakeClaudeCli( + [ + 'dir=$(dirname "$0")', + `while read -r line; do case "$line" in *'"type":"user"'*) break;; esac; done`, + `perl -e 'setpgrp(0, 0); exec @ARGV' sleep 600 > "$dir/alive" &`, + 'echo $! > "$dir/leftover.pid"', + `echo '{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"native-session-fake-cli"}'`, + 'read -r _ < "$dir/exit"', + ].join("\n"), + ); + const dir = NodePath.dirname(cli); + NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]); + NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "exit")]); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + try { + process.kill(Number(NodeFS.readFileSync(NodePath.join(dir, "leftover.pid"), "utf8"))); + } catch {} + NodeFS.rmSync(dir, { recursive: true, force: true }); + }), + ); + const alive = NodeFS.createReadStream(NodePath.join(dir, "alive")); + const leftoverStopped = new Promise((resolve) => alive.once("close", () => resolve())); + alive.resume(); + let listings = 0; + const countingSpawner = Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + return ChildProcessSpawner.make((command) => { + if (command._tag === "StandardCommand" && command.command === "ps") listings += 1; + return spawner.spawn(command); + }); + }), + ).pipe(Layer.provide(NodeServices.layer)); + + const session = yield* openFakeCli(cli).pipe( + Effect.provide( + layerQueryRunner.pipe( + Layer.provide(countingSpawner), + Layer.provide(PortScanner.layerTest), + Layer.provide( + Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined }), + ), + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ); + const turnEnded = yield* Deferred.make(); + yield* session.messages.pipe( + Stream.tap((message) => + message.type === "result" ? Deferred.succeed(turnEnded, undefined) : Effect.void, + ), + Stream.runDrain, + Effect.ignore, + Effect.forkScoped, + ); + yield* session.offer({ + type: "user", + message: { role: "user", content: "Start a job." }, + parent_tool_use_id: null, + session_id: "native-session-fake-cli", + }); + yield* Deferred.await(turnEnded); + const listingsAtTurnEnd = listings; + yield* TestClock.adjust("1 minute"); + // The CLI exits on its own, so only the turn-end read can have recorded the job. + yield* Effect.promise(() => NodeFS.promises.writeFile(NodePath.join(dir, "exit"), "\n")); + yield* Effect.promise(() => leftoverStopped); + assert.equal(listings, listingsAtTurnEnd + 1); + }), + ); const rootRefusal = "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons"; diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 4f67c42bb6d76..14d17371983b5 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -649,7 +649,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( function layerTest(input: { readonly state: Ref.Ref; - readonly idleTimeoutMs: number; + readonly idleTimeoutMs?: number; readonly maxIdlePinMs?: number; readonly failEventStream?: boolean; readonly normalizeThreadLoadModelSelection?: (selection: ModelSelection) => ModelSelection; @@ -769,7 +769,7 @@ function layerTest(input: { layerConfiguredMcpRegistry, McpProviderSessions.layer, ProviderSessionManager.layerWithOptions({ - idleTimeoutMs: input.idleTimeoutMs, + ...(input.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: input.idleTimeoutMs }), ...(input.maxIdlePinMs === undefined ? {} : { maxIdlePinMs: input.maxIdlePinMs }), }).pipe( Layer.provide( @@ -2102,6 +2102,41 @@ it.effect( }), ); +it.effect.each([ + { resume: "native resume", supportsNativeResume: true, minutes: 2 }, + { resume: "no native resume", supportsNativeResume: false, minutes: 30 }, +])( + "ProviderSessionManagerV2 releases an idle session with $resume after $minutes minutes", + ({ supportsNativeResume, minutes }) => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const capabilities = { + ...CodexCapabilities, + turns: { ...CodexCapabilities.turns, supportsNativeResume }, + }; + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const threadId = ThreadId.make("thread-default-idle-timeout"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now: yield* DateTime.now }), + ], + }); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + yield* TestClock.adjust(minutes * 60_000 - 1_000); + assert.isTrue(yield* manager.isLive(providerSessionId)); + yield* TestClock.adjust("1 second"); + assert.isFalse(yield* manager.isLive(providerSessionId)); + }).pipe(Effect.provide(layerTest({ state, capabilities }))); + }), +); + it.effect.each(["session metadata", "session status changes", "provider work"] as const)( "ProviderSessionManagerV2 expires idle sessions according to %s", (activity) => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index b840379ae5b54..6d445f5b0bdf7 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -78,7 +78,9 @@ import { import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; -const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; +const DEFAULT_IDLE_TIMEOUT_MS = 2 * 60 * 1000; +// Without native resume, a released session comes back as a summary of the thread, so it stays longer. +const NO_NATIVE_RESUME_IDLE_TIMEOUT_MS = 30 * 60 * 1000; const DEFAULT_MAX_IDLE_PIN_MS = 4 * 60 * 60 * 1000; const RELEASE_SCOPE_CLOSE_TIMEOUT_MS = 30 * 1000; /** Past adapters' own 10 s stop fallbacks, so they settle first when the provider answers at all. */ @@ -576,7 +578,14 @@ export const layerWithOptions = ( readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; }) => `${input.providerSessionId}\u0000${input.threadId}`; - const idleTimeoutMs = Math.max(1, options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS); + const idleTimeoutFor = (runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime) => + Math.max( + 1, + options.idleTimeoutMs ?? + (runtime.providerSession.capabilities.turns.supportsNativeResume === true + ? DEFAULT_IDLE_TIMEOUT_MS + : NO_NATIVE_RESUME_IDLE_TIMEOUT_MS), + ); const maxIdlePinMs = Math.max(0, options.maxIdlePinMs ?? DEFAULT_MAX_IDLE_PIN_MS); interface PreparedMcpCredential { readonly mcpCredentialId: string | undefined; @@ -1688,7 +1697,7 @@ export const layerWithOptions = ( pinnedForMs: now - pinnedSinceMs, }); // Recheck on this fiber; scheduleIdleReleaseInternal would interrupt it and self-deadlock. - yield* Effect.sleep(Duration.millis(idleTimeoutMs)); + yield* Effect.sleep(Duration.millis(idleTimeoutFor(probedRuntime))); return yield* releaseIfStillIdle(input); } yield* Effect.logWarning("orchestration-v2.driver-session.idle-release-pin-expired", { @@ -1758,7 +1767,7 @@ export const layerWithOptions = ( yield* cancelIdleFiber(entry.idleFiber); const generation = entry.idleGeneration + 1; - const idleFiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( + const idleFiber = yield* Effect.sleep(Duration.millis(idleTimeoutFor(entry.runtime))).pipe( Effect.andThen(releaseIfStillIdle({ providerSessionId, generation })), Effect.forkIn(layerScope), ); @@ -2128,7 +2137,7 @@ export const layerWithOptions = ( const pending = entry.idleThreadUnloads.get(providerThreadId); if (pending === undefined) return; const generation = pending.generation + 1; - const fiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( + const fiber = yield* Effect.sleep(Duration.millis(idleTimeoutFor(entry.runtime))).pipe( Effect.andThen( unloadIdleThread({ providerSessionId, @@ -2217,10 +2226,12 @@ export const layerWithOptions = ( : yield* entry.runtime .hasPendingBackgroundWorkForThread(pending.providerThread) .pipe(Effect.catchCause(() => Effect.succeed(false))); - if (hasPendingWork) return "deferred" as const; + if (hasPendingWork) return { retryAfterMs: idleTimeoutFor(entry.runtime) }; const child = yield* delegatedChildArchive(input.threadId); // Unloading now would miss the archive once the parent takes the result. - if (child === "awaiting_delivery") return "deferred" as const; + if (child === "awaiting_delivery") { + return { retryAfterMs: idleTimeoutFor(entry.runtime) }; + } const archive = child === "ready"; if (input.archiveOnly === true && !archive) return "skipped" as const; // null when skipped, otherwise whether this native thread is the app thread's loaded one. @@ -2295,8 +2306,8 @@ export const layerWithOptions = ( }), ); // Wait outside the lock so the next attach is not blocked. - if (outcome === "deferred" && input.archiveOnly !== true) { - yield* Effect.sleep(Duration.millis(idleTimeoutMs)); + if (typeof outcome === "object" && input.archiveOnly !== true) { + yield* Effect.sleep(Duration.millis(outcome.retryAfterMs)); return yield* unloadIdleThread(input); } }, From 8708a29a0b9017133cdfc08c4ad3841fdd50f021 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:39:05 -0800 Subject: [PATCH 156/162] perf(server): checkpoint capture no longer walks every reflog in the repository (#41177) Co-authored-by: Claude Opus 5.5 --- apps/server/src/vcs/GitVcsDriver.test.ts | 135 ++++++++++++++++++++++- apps/server/src/vcs/GitVcsDriver.ts | 125 ++++++++++++++++----- 2 files changed, 227 insertions(+), 33 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 21b4d23a37bda..882469b57a5c0 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -1427,7 +1427,7 @@ it.effect.each([1_700_000_000, 1_700_000_000.9999])( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); -it.effect.each(["local", "mixed", "exit"] as const)( +it.effect.each(["local", "mixed", "exit", "non-UTF-8 refs", "pruned ref"] as const)( "checkpoint authorship uses local evidence or full fallback ($0)", (mode) => Effect.gen(function* () { @@ -1441,7 +1441,7 @@ it.effect.each(["local", "mixed", "exit"] as const)( const fromCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/authorship/from"); const toCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/authorship/to"); yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef: fromCheckpointRef }); - if (mode === "mixed") { + if (mode !== "local" && mode !== "exit") { yield* fs.writeFileString(path.join(cwd, "imported.txt"), "upstream\n"); yield* git(["add", "."]); const tree = (yield* git(["write-tree"])).stdout.trim(); @@ -1476,10 +1476,30 @@ it.effect.each(["local", "mixed", "exit"] as const)( const queryDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( Effect.provideService(VcsProcess.VcsProcess, { run: (input) => { + if (mode === "non-UTF-8 refs" && input.args.includes("for-each-ref")) { + return liveProcess + .run(input) + .pipe(Effect.map((result) => ({ ...result, stdoutInvalidUtf8: true }))); + } + // Pruned between listing the refs and walking their reflogs. + if (mode === "pruned ref" && input.args.includes("for-each-ref")) { + return liveProcess.run(input).pipe( + Effect.map((result) => ({ + ...result, + stdout: `refs/remotes/origin/pruned\n${result.stdout}`, + })), + ); + } if (!input.args.includes("--walk-reflogs")) return liveProcess.run(input); - const scope = input.args.includes("--all") ? "--all" : "HEAD"; + const scope = input.args.includes("--all") + ? `worktree HEADs${input.args.includes("--branches") ? " and --branches" : ""}` + : input.args.includes("--remotes") + ? "--remotes" + : input.args.includes("--stdin") + ? "refs" + : "HEAD"; reflogScopes.push(scope); - if (scope === "--all" || mode !== "exit") return liveProcess.run(input); + if (scope !== "HEAD" || mode !== "exit") return liveProcess.run(input); return Effect.fail( new VcsProcessExitError({ operation: input.operation, @@ -1500,10 +1520,115 @@ it.effect.each(["local", "mixed", "exit"] as const)( }), new Set(["local.txt"]), ); - assert.deepEqual(reflogScopes, mode === "local" ? ["HEAD"] : ["HEAD", "--all"]); + assert.deepEqual( + reflogScopes, + { + local: ["HEAD"], + mixed: ["HEAD", "refs", "worktree HEADs"], + // Without an import no remote-tracking ref holds the turn's commits, so none is read. + exit: ["HEAD"], + "non-UTF-8 refs": ["HEAD", "--remotes", "worktree HEADs and --branches"], + "pruned ref": ["HEAD", "refs", "worktree HEADs"], + }[mode], + ); }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect("checkpoint authorship reads only reflogs of refs holding the turn's commits", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const liveProcess = yield* VcsProcess.VcsProcess; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-imports-" }); + const upstream = path.join(root, "upstream"); + const primary = path.join(root, "primary"); + const cwd = path.join(root, "turn"); + const git = (repo: string, args: ReadonlyArray, stdin?: string) => + driver.execute({ + operation: "checkpoint-test", + cwd: repo, + args: ["-c", "user.name=Test", "-c", "user.email=test@test.com", ...args], + ...(stdin === undefined ? {} : { stdin }), + }); + const commitFile = (repo: string, file: string) => + Effect.gen(function* () { + yield* fs.writeFileString(path.join(repo, file), `${file}\n`); + yield* git(repo, ["add", "."]); + yield* git(repo, ["commit", "-m", file]); + }); + yield* fs.makeDirectory(upstream); + yield* git(upstream, ["init"]); + yield* commitFile(upstream, "base.txt"); + yield* git(root, ["clone", upstream, primary]); + yield* git(primary, ["worktree", "add", cwd, "-b", "turn"]); + const fromCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/imports/from"); + const toCheckpointRef = CheckpointRef.make("refs/t3/checkpoints/imports/to"); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef: fromCheckpointRef }); + + // Refs updated during the turn that hold none of its commits. + const base = (yield* git(cwd, ["rev-parse", "HEAD"])).stdout.trim(); + const unrelated = Array.from({ length: 200 }, (_, index) => [ + `create refs/remotes/origin/unrelated-${index} ${base}`, + `create refs/heads/unrelated-${index} ${base}`, + `create refs/t3/checkpoints/unrelated-${index} ${base}`, + ]).flat(); + yield* git( + cwd, + ["update-ref", "--create-reflog", "-m", "fetch origin: storing head", "--stdin"], + `${unrelated.join("\n")}\n`, + ); + + // Fetched and fast-forwarded: imported. + yield* git(upstream, ["checkout", "-b", "release"]); + yield* commitFile(upstream, "fetched.txt"); + // Made in another worktree that then moved on, pushed, and fetched back: local. + yield* git(primary, ["checkout", "--detach"]); + yield* commitFile(primary, "own.txt"); + yield* git(primary, ["push", "origin", "HEAD:refs/heads/pushed"]); + yield* git(primary, ["checkout", "-"]); + yield* git(upstream, ["merge", "pushed", "--no-edit"]); + yield* git(upstream, ["checkout", "-b", "feature"]); + yield* commitFile(upstream, "picked.txt"); + yield* git(cwd, ["fetch", "origin"]); + yield* git(cwd, ["merge", "--ff-only", "origin/release"]); + // Cherry-picked from a fetched branch: a new local commit. + yield* git(cwd, ["cherry-pick", "origin/feature"]); + yield* commitFile(cwd, "local.txt"); + // Pushing imported commits elsewhere must not make them look local. + yield* git(cwd, ["push", "origin", "HEAD:refs/heads/mirror"]); + yield* driver.checkpoints.captureCheckpoint({ + cwd, + checkpointRef: toCheckpointRef, + previousCheckpointRef: fromCheckpointRef, + }); + + const reflogWalks: Array<{ args: ReadonlyArray; refs: ReadonlyArray }> = []; + const queryDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => { + if (input.args.includes("--walk-reflogs")) { + reflogWalks.push({ args: input.args, refs: (input.stdin ?? "").split("\n") }); + } + return liveProcess.run(input); + }, + }), + ); + assert.deepEqual( + yield* queryDriver.checkpoints.listAuthoredPaths({ cwd, fromCheckpointRef, toCheckpointRef }), + new Set(["own.txt", "picked.txt", "local.txt"]), + ); + assert.isNotEmpty(reflogWalks); + for (const { args, refs } of reflogWalks) { + // Refs come only from the explicit list; --all is limited to worktree HEADs. + const selectors = args.filter((arg) => /^--(?:all|branches|remotes|glob|tags)\b/.test(arg)); + assert.deepEqual(selectors, args.includes("--all") ? ["--all"] : []); + if (args.includes("--all")) assert.include(args, "--exclude=refs/*"); + for (const ref of refs) assert.notInclude(ref, "unrelated"); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect("checkpoint authorship works with git that rejects --diff-merges=remerge", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 3a4dd7cedf10a..3ba545caf97a8 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -1,5 +1,6 @@ import * as NodeBuffer from "node:buffer"; +import * as Arr from "effect/Array"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -2368,36 +2369,102 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( outputMode: "error", }).pipe(Effect.map((result) => result.stdout.split("\0"))); - // A commit is an import when a fetch delivered it since the previous checkpoint and no - // reflog in any worktree shows this repository creating it. --all covers every worktree's - // HEAD, and with --walk-reflogs --max-age compares each entry's own time. --since would - // guess at a date, and reads a timestamp before 1973 as the current time. - const listImportedCommits = Effect.gen(function* () { - const entries = (yield* listLines([ - "log", - "--walk-reflogs", - "--all", - `--max-age=${capturedAt}`, - "--format=%H %gD %gs", - ])).map(parseCheckpointReflogEntry); - // A push records commits this repository already had. - const fetchedTips = new Set( - entries - .filter((entry) => entry.fetched && entry.subject !== "update by push") - .map((entry) => entry.commit), - ); - if (fetchedTips.size === 0) return fetchedTips; - // Fetching another branch can deliver a commit that was made here and pushed. - const createdHere = new Set( - entries.filter(isLocalReflogCreation).map((entry) => entry.commit), - ); - const fetched = yield* listLines( - ["rev-list", `--max-age=${capturedAt}`, "--stdin"], - `${[...fetchedTips, `^${startHead}`].join("\n")}\n`, + // Refs under `namespace` that contain any of `commits`. Only the oldest commits of the set + // are passed on, since a ref containing a descendant also contains its ancestors. + const listRefsContaining = Effect.fn("GitVcsDriver.checkpoints.listRefsContaining")( + function* (commits: ReadonlySet, namespace: "refs/remotes" | "refs/heads") { + const roots = (yield* listLines( + ["rev-list", "--no-walk=unsorted", "--parents", "--stdin"], + `${[...commits].join("\n")}\n`, + )).flatMap((line) => { + const [commit = "", ...parents] = line.split(" "); + return parents.some((parent) => commits.has(parent)) ? [] : [commit]; + }); + const outputs = yield* Effect.forEach(Arr.chunksOf(roots, 256), (chunk) => + execute({ + operation, + cwd: input.cwd, + args: [ + "for-each-ref", + "--format=%(refname)", + ...chunk.flatMap((commit) => ["--contains", commit]), + namespace, + ], + maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + outputMode: "error", + }), + ); + // A ref name that is not UTF-8 would not survive the round trip, so Git lists them. + if (outputs.some((output) => output.stdoutInvalidUtf8)) { + return { + revisionArgs: [namespace === "refs/heads" ? "--branches" : "--remotes"], + refs: [], + }; + } + const refs = outputs.flatMap((output) => output.stdout.split("\n")); + return { revisionArgs: [], refs: [...new Set(refs.filter((ref) => ref !== ""))] }; + }, + ); + // With --walk-reflogs, --max-age compares each entry's own time; --since would guess at a + // date and reads a timestamp before 1973 as now. Walking many reflogs at once slows down + // quadratically with the refs passed: --all took 40 s in a repository with 29k refs. + const walkReflogs = Effect.fn("GitVcsDriver.checkpoints.walkReflogs")(function* ( + revisionArgs: ReadonlyArray, + refs: ReadonlyArray, + ) { + const lines = yield* listLines( + [ + "log", + "--walk-reflogs", + ...revisionArgs, + `--max-age=${capturedAt}`, + "--format=%H %gD %gs", + // A listed ref may be pruned before this walk reads it. + "--ignore-missing", + "--stdin", + ], + `${refs.join("\n")}\n`, ); - return new Set(fetched.filter((commit) => !createdHere.has(commit))); + return lines.map(parseCheckpointReflogEntry); }); + // A commit is an import when a fetch delivered it since the previous checkpoint and no + // reflog shows this repository creating it. Only refs containing a turn commit are read; + // a remote-tracking ref force-moved off one after the fetch is missed, which keeps that + // commit attributed to the turn. + const listImportedCommits = Effect.fn("GitVcsDriver.checkpoints.listImportedCommits")( + function* (candidates: ReadonlySet) { + const remote = yield* listRefsContaining(candidates, "refs/remotes"); + if (remote.revisionArgs.length === 0 && remote.refs.length === 0) { + return new Set(); + } + // A push records commits this repository already had. + const fetchedTips = new Set( + (yield* walkReflogs(remote.revisionArgs, remote.refs)) + .filter((entry) => entry.fetched && entry.subject !== "update by push") + .map((entry) => entry.commit), + ); + if (fetchedTips.size === 0) return fetchedTips; + const fetched = new Set( + (yield* listLines( + ["rev-list", `--max-age=${capturedAt}`, "--stdin"], + `${[...fetchedTips, `^${startHead}`].join("\n")}\n`, + )).filter((commit) => candidates.has(commit)), + ); + if (fetched.size === 0) return fetched; + // Fetching another branch can deliver a commit that was made here and pushed. Every + // worktree's HEAD reflog is read, since a detached HEAD may have moved off the commit + // it made; --all with refs/* excluded yields exactly those HEADs. + const local = yield* listRefsContaining(fetched, "refs/heads"); + const createdHere = new Set( + (yield* walkReflogs(["--exclude=refs/*", "--all", ...local.revisionArgs], local.refs)) + .filter(isLocalReflogCreation) + .map((entry) => entry.commit), + ); + return new Set([...fetched].filter((commit) => !createdHere.has(commit))); + }, + ); + // Remerge diffs retain merge conflict fixes while excluding clean upstream changes. // Older Git gets dense combined diffs, which miss a conflict resolved to one side's // version, so it also keeps every path more than one parent changed since the merge base. @@ -2483,7 +2550,9 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const importedCommits = unprovenCommits.size === 0 ? new Set() - : yield* listImportedCommits.pipe(Effect.orElseSucceed(() => new Set())); + : yield* listImportedCommits(unprovenCommits).pipe( + Effect.orElseSucceed(() => new Set()), + ); const ownCommits = recentCommits.filter((commit) => !importedCommits.has(commit)); const ownCommitPaths = ownCommits.length === 0 From a679987c0b15b3be5a105062b7b47c9889ca4752 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:44:39 -0800 Subject: [PATCH 157/162] test(server): replay scenarios no longer run checkpoints against the real checkout (#41192) Co-authored-by: Claude Opus 5.5 --- .../src/orchestration-v2/RuntimePolicy.ts | 10 -------- .../ThreadFork.execution.test.ts | 1 + .../testkit/ProviderReplayHarness.ts | 23 +++++++++++++++++-- 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.ts b/apps/server/src/orchestration-v2/RuntimePolicy.ts index aac7a859423fb..3ba0baa24dd5d 100644 --- a/apps/server/src/orchestration-v2/RuntimePolicy.ts +++ b/apps/server/src/orchestration-v2/RuntimePolicy.ts @@ -79,16 +79,6 @@ export class RuntimePolicyV2 extends Context.Service = Layer.succeed(RuntimePolicyV2, { - resolve: Effect.fn("RuntimePolicyV2.resolve")(function (input) { - return Effect.succeed({ - runtimeMode: input.thread.runtimeMode, - interactionMode: input.thread.interactionMode, - cwd: input.thread.worktreePath, - }); - }), -}); - export function providerRuntimeMode( runtimeMode: RuntimeMode, supportedRuntimeModes: ReadonlyArray | undefined, diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts index 634a842843b93..3466fed79f502 100644 --- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts @@ -1938,6 +1938,7 @@ const runForkWithFailingNativeSource = (forkFailures: number) => { ProviderReplayHarness.layerWithRegistry( { name: "fork-missing-native-source" }, ProviderAdapterRegistry.layerFromAdapters([adapter]), + { runEffectWorker: false }, ), ), ); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index bb336d3179f34..ccd4c69710d81 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -17,6 +17,7 @@ import type * as SqlClient from "effect/sql/SqlClient"; import type { MigrationError } from "effect/sql/Migrator"; import type { SqlError } from "effect/sql/SqlError"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts"; import * as ServerConfig from "../../config.ts"; import * as SqlitePersistence from "../../persistence/Sqlite.ts"; @@ -317,11 +318,29 @@ export function layerWithRegistry( ServerConfig.ServerConfig, makeReplayServerConfig(scenario.name).pipe(Effect.orDie), ).pipe(Layer.provide(NodeServices.layer)); + // A thread without a worktree would otherwise fall back to process.cwd(), so checkpoints + // would run git against the checkout running the tests and race its other users. + const layerScenarioWorkspacePolicy = Layer.effect( + RuntimePolicy.RuntimePolicyV2, + Effect.gen(function* () { + const workspace = yield* checkpointWorkspace( + scenario.name.replace(/[^a-z0-9_-]+/gi, "-"), + ).pipe(Effect.orDie); + return { + resolve: (input) => + Effect.succeed({ + runtimeMode: input.thread.runtimeMode, + interactionMode: input.thread.interactionMode, + cwd: input.thread.worktreePath ?? workspace, + }), + }; + }), + ); const layerRuntimeBase = scenario.runtimePolicyOverride === undefined - ? RuntimePolicy.layer + ? layerScenarioWorkspacePolicy : RuntimePolicy.layerWithOverride(scenario.runtimePolicyOverride).pipe( - Layer.provide(RuntimePolicy.layer), + Layer.provide(layerScenarioWorkspacePolicy), ); const layerDatabase = options.databaseLayer ?? SqlitePersistence.layerMemory; // Share one continuation queue across adapters, orchestrator, and worker through layer memoization. From 9a87dbb99a9d672957de4ebe45df92aea5283647 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:45:33 -0800 Subject: [PATCH 158/162] fix(web): chat file tooltips open beside the link instead of sliding in from the corner (#41194) --- apps/web/src/components/ui/shared-tooltip.tsx | 3 +++ .../components/ui/tooltip.browser.test.tsx | 22 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/apps/web/src/components/ui/shared-tooltip.tsx b/apps/web/src/components/ui/shared-tooltip.tsx index 0858fa656e6bb..cca4d8a43fd61 100644 --- a/apps/web/src/components/ui/shared-tooltip.tsx +++ b/apps/web/src/components/ui/shared-tooltip.tsx @@ -11,6 +11,7 @@ import { type ReactElement, type ReactNode, } from "react"; +import { flushSync } from "react-dom"; import { Tooltip, TooltipPopup, TooltipTrigger, useTooltipScrollTracker } from "./tooltip"; @@ -79,6 +80,8 @@ export function SharedTooltipProvider({ children }: { children: ReactNode }) { const [api] = useState(() => ({ show(anchor, content, immediate) { clearTimer(); + // A Root that mounts open skips Base UI's mount transition, so the popup would slide in from (0,0). + if (!current.current) flushSync(() => commit({ ...content, anchor, open: false })); const open = current.current?.open === true; const reopen = performance.now() - lastClosedAt.current < REOPEN_WINDOW_MS; if (immediate || open || reopen) { diff --git a/apps/web/src/components/ui/tooltip.browser.test.tsx b/apps/web/src/components/ui/tooltip.browser.test.tsx index bcb62ee2fdaf0..344ddcea7f0f1 100644 --- a/apps/web/src/components/ui/tooltip.browser.test.tsx +++ b/apps/web/src/components/ui/tooltip.browser.test.tsx @@ -114,3 +114,25 @@ it("refreshes a pending shared tooltip if its label changes during the open dela await expect.element(page.getByText("Copy code")).toBeVisible(); expect(page.getByText("Copied").query()).toBeNull(); }); + +it("opens a shared tooltip in place the first time", async () => { + await using _screen = await render( + // Away from the corner the unpositioned popup sits in, so a slide from there is a real move. +

    , + ); + // Focus opens it at once, while a position transition would still be running. + await userEvent.keyboard("{Tab}"); + await expect.element(page.getByText("Description")).toBeVisible(); + const moving = document + .getAnimations() + .filter((animation) => animation instanceof CSSTransition) + .map((transition) => transition.transitionProperty) + .filter((property) => ["top", "left", "right", "bottom", "transform"].includes(property)); + expect(moving).toEqual([]); +}); From c18f82c4bd9f7fa27df6c7edded2442f48c5538b Mon Sep 17 00:00:00 2001 From: Victor Date: Sun, 22 Nov 2026 21:46:57 -0600 Subject: [PATCH 159/162] fix(server): RTF attachments leave hidden text out of what agents read (#41191) Co-authored-by: Julius Marminge --- apps/server/src/provider/documentTextWorker.ts | 5 ++++- apps/server/src/provider/userInputAttachments.test.ts | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts index ec1f1f694c2f4..0acffd168c07d 100644 --- a/apps/server/src/provider/documentTextWorker.ts +++ b/apps/server/src/provider/documentTextWorker.ts @@ -459,6 +459,7 @@ function* rtf(source: string): Generator { let state = { skip: false, deleted: false, + hiddenText: false, uc: 1, font: 0, fontTable: false, @@ -469,7 +470,7 @@ function* rtf(source: string): Generator { const fonts = new Map(); let defaultFont = 0; const decoder = () => fonts.get(state.font) ?? state.decoder; - const hidden = () => state.skip || state.deleted; + const hidden = () => state.skip || state.deleted || state.hiddenText; const symbols = new Map([ ["endash", "–"], ["emdash", characterEntities.mdash], @@ -548,8 +549,10 @@ function* rtf(source: string): Generator { if (codePage) fonts.set(state.font, new TextDecoder(codePage)); } if (control === "deleted") state.deleted = value !== 0; + else if (control === "v") state.hiddenText = value !== 0; else if (control === "plain") { state.deleted = false; + state.hiddenText = false; state.font = defaultFont; } if (control === "mac" || (control === "ansicpg" && value === 10000)) diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts index 55c3468f3dce9..8c8be7bf30534 100644 --- a/apps/server/src/provider/userInputAttachments.test.ts +++ b/apps/server/src/provider/userInputAttachments.test.ts @@ -329,6 +329,16 @@ describe("question answer paths", () => { String.raw`{\rtf1\ansi\trowd\cellx1000\cellx2000\intbl A\deleted\cell\deleted0 B\cell\deleted\row\deleted0 C\cell}`, "A\tB\t\nC", ], + [ + "hidden text", + String.raw`{\rtf1\ansi A {\v B{\v0 C}D} E\v F\v0 G\v1 H\plain I}`, + "A C E G I", + ], + [ + "hidden text table and escapes", + String.raw`{\rtf1\ansi\trowd\cellx1000\cellx2000\intbl A\v B\u945?\'e9\cell\v0 C\cell\v\row\v0 D\cell}`, + "A\tC\t\nD", + ], [ "document breaks", String.raw`{\rtf1\ansi\sectd\cols2\pard North quota: 120\column South quota: 240\page East quota: 360\sect\sectd\pard West quota: 480\par}`, From 1d4d9be3ff925d5d5ecc90859bdcbd20ecb04b15 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 22 Nov 2026 19:47:09 -0800 Subject: [PATCH 160/162] fix(server): Antigravity 502s fail the turn with the real error (#33596) --- .../Adapters/AcpAdapterV2.test.ts | 46 +++++++++++++++++ .../acp/AntigravityTurnOutcome.test.ts | 47 +++++++++++++++++- .../provider/acp/AntigravityTurnOutcome.ts | 16 ++++-- packages/provider-acp/src/server/adapter.ts | 49 +++++++++++++++---- 4 files changed, 142 insertions(+), 16 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 7815f8d959a2f..43db1b82b63a2 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -626,6 +626,7 @@ const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapter const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { readonly environment: (runtimeOrdinal: number) => Readonly>; readonly runtimeMode?: "full-access" | "approval-required"; + readonly watchPromptOutcome?: AcpAdapterV2Flavor["watchPromptOutcome"]; readonly wrapPrompt?: ( prompt: AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"], ) => AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"]; @@ -642,6 +643,9 @@ const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, promptInactivityTimeout: "15 minutes", + ...(input.watchPromptOutcome === undefined + ? {} + : { watchPromptOutcome: input.watchPromptOutcome }), ...(input.followAgentWorkState === true ? { followAgentWorkState: true } : {}), makeRuntime: makeMockRuntime({ childProcessSpawner, @@ -5845,6 +5849,48 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("fails a silent prompt with the failure its outcome check recorded", () => + Effect.gen(function* () { + const badGateway = { + class: "provider_error", + message: "Bad Gateway: Failed to connect to backend API", + code: "502 Bad Gateway", + retryable: true, + } as const; + // The agent logs the upstream error and leaves session/prompt open. + const harness = yield* makePromptInactivityHarness({ + environment: () => ({ T3_ACP_HANG_PROMPT_FOREVER: "1" }), + watchPromptOutcome: () => + Effect.succeed((_result, options) => + Effect.succeed( + options?.retired === true + ? { failure: badGateway, threadDisposition: "reusable" as const } + : undefined, + ), + ), + }); + yield* harness.startTurn(1); + yield* TestClock.adjust("15 minutes"); + const [silent] = yield* harness.terminals(1); + assert.equal(silent?.status, "failed"); + assert.deepEqual(silent?.failure, badGateway); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.effect("retires a silent prompt whose outcome check dies", () => + Effect.gen(function* () { + const harness = yield* makePromptInactivityHarness({ + environment: () => ({ T3_ACP_HANG_PROMPT_FOREVER: "1" }), + watchPromptOutcome: () => Effect.succeed(() => Effect.die("session log unreadable")), + }); + yield* harness.startTurn(1); + yield* TestClock.adjust("15 minutes"); + const [silent] = yield* harness.terminals(1); + assert.equal(silent?.status, "failed"); + assert.include(silent?.failure?.message, "15 minutes"); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + // regression: #34160 a turn failed as silent right after the computer woke from sleep it.effect.each([ { label: "a timer due during sleep fires on wake", timerCountsSleep: true, asleep: "2 hours" }, diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts index b6094e638285d..962da73bfc2bd 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.test.ts @@ -30,9 +30,19 @@ const QUOTA_ERROR = errorPayload( const RATE_LIMIT_ERROR = errorPayload( "Error 429, Message: Resource has been exhausted (e.g. check quota)., Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.ErrorInfo domain:cloudcode-pa.googleapis.com reason:RATE_LIMIT_EXCEEDED] map[@type:type.googleapis.com/google.rpc.RetryInfo retryDelay:42s]]", ); +const RETIRED_QUOTA_ERROR = errorPayload( + "Error 429, Message: Quota exhausted for test model., Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.ErrorInfo domain:googleapis.com metadata:map[quotaResetDelay:3600s quotaResetTimeStamp:2026-11-09T01:05:00Z] reason:QUOTA_EXHAUSTED]]", +); const INVALID_ARGUMENT_ERROR = errorPayload( "Error 400, Message: Request contains an invalid argument., Status: INVALID_ARGUMENT, Details: []", ); +// The harness renders a gateway failure with its HTTP status line in place of a gRPC status. +const BAD_GATEWAY_ERROR = Buffer.concat([ + errorPayload( + "Error 502, Message: Bad Gateway: Failed to connect to backend API, Status: 502 Bad Gateway, Details: []", + ), + Buffer.from("\nThe model is currently unreachable."), +]); // Vertex Claude rejects a resumed history whose saved thinking block lost its signature. const MISSING_SIGNATURE_ERROR = errorPayload( 'Error 400, Message: {"type":"error","error":{"type":"invalid_request_error","message":"messages.1.content.0.thinking.signature: Field required"},"request_id":"req_vrtx_test"}, Status: INVALID_ARGUMENT, Details: []', @@ -82,11 +92,12 @@ describe("watchAntigravityPromptOutcome", () => { const turn = ( steps: ReadonlyArray, result: EffectAcpSchema.PromptResponse = { stopReason: "end_turn" }, + options?: { readonly retired?: boolean }, ) => Effect.gen(function* () { const check = yield* watchAntigravityPromptOutcome(profileDirectory, sessionId); appendSteps(steps); - return yield* check(result); + return yield* check(result, options); }); const input = Buffer.from("Run the fixture."); const reply = Buffer.from("FIXTURE_OK"); @@ -149,6 +160,40 @@ describe("watchAntigravityPromptOutcome", () => { retryable: false, }), ); + assert.deepInclude( + (yield* turn([ + [USER_INPUT, input], + [ERROR_MESSAGE, BAD_GATEWAY_ERROR], + ]))?.failure, + { + class: "provider_error", + message: "Bad Gateway: Failed to connect to backend API", + retryable: true, + }, + ); + // A prompt the watchdog retired keeps an absolute reset time but drops a relative one. + assert.deepEqual( + (yield* turn( + [ + [USER_INPUT, input], + [ERROR_MESSAGE, RATE_LIMIT_ERROR], + ], + undefined, + { retired: true }, + ))?.failure.resetAt, + undefined, + ); + assert.equal( + (yield* turn( + [ + [USER_INPUT, input], + [ERROR_MESSAGE, RETIRED_QUOTA_ERROR], + ], + undefined, + { retired: true }, + ))?.failure.resetAt, + "2026-11-09T01:05:00.000Z", + ); // A 404 after the turn already reached the model is a transient edge error, not a bad model. for (const error of [NOT_FOUND_ERROR, STATUS_NOT_FOUND_ERROR]) { assert.deepEqual( diff --git a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts index 32eee40f008ae..35ed2f347df1d 100644 --- a/apps/server/src/provider/acp/AntigravityTurnOutcome.ts +++ b/apps/server/src/provider/acp/AntigravityTurnOutcome.ts @@ -20,7 +20,10 @@ const PLANNER_RESPONSE_STEP_TYPE = 15; // The harness error text leads the payload; a Go stack trace follows it. const MAX_ERROR_PAYLOAD_BYTES = 16_384; // The Go harness's rendering of a Google API error, as the agent's api_errors.py reads it. -const API_ERROR = /Error (\d{3}), Message: (.+?), Status: ([A-Z_]+)/s; +// Status is a gRPC code, or an HTTP status line such as "502 Bad Gateway". A message +// stops at the next error, so each start scans its own span and the match stays linear. +const API_ERROR = + /Error (\d{3}), Message: ((?:(?!, Status: |Error \d{3}, Message: ).)+), Status: ([A-Z_]+|\d{3}[^,\n]*)/s; // Antigravity 1.5 with a Google account writes "STATUS (code NNN): message". const STATUS_ERROR = /(? undefined), ) : undefined; - return turnFailure(result.stopReason, step, yield* DateTime.now); + // A retired prompt's check runs long after the error, so a relative delay has no anchor. + const now = options?.retired === true ? undefined : yield* DateTime.now; + return turnFailure(result.stopReason, step, now); }); }); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 997158c78a1ce..d4af4aa10ddd5 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -389,15 +389,17 @@ export interface AcpAdapterV2Flavor { /** The flavor's runtime refuses a version the policy rates broken when it starts. */ readonly checksVersionAtHandshake?: boolean; /** - * Runs before `session/prompt`. The returned check sees a prompt the agent ended - * without an error or cancel, and reports a failure its stop reason hid. A reported - * failure restarts the runtime before the next turn. A `broken` thread's native - * history is unusable, so the next turn falls back to a fresh session. + * Runs before `session/prompt`. The check reports a failure hidden by a clean stop, or + * by silence when the inactivity watchdog retires the prompt (`retired`). A failure + * restarts the runtime; a `broken` thread's next turn starts a fresh session. */ readonly watchPromptOutcome?: ( sessionId: string, ) => Effect.Effect< - (result: EffectAcpSchema.PromptResponse) => Effect.Effect + ( + result: EffectAcpSchema.PromptResponse, + options?: { readonly retired?: boolean }, + ) => Effect.Effect >; readonly requiresSignIn?: (cause: unknown) => boolean; /** @@ -1746,6 +1748,12 @@ interface ActiveAcpTurn { inactivityWatchdog: Fiber.Fiber | undefined; } +const PROMPT_OUTCOME_CHECK_TIMEOUT = Duration.seconds(5); + +type PromptOutcomeCheck = Effect.Success< + ReturnType> +>; + type AcpRuntimeTeardownState = | { readonly _tag: "Idle" } | { @@ -8909,6 +8917,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context: ActiveAcpTurn, generation: number, timeoutMillis: number, + checkPromptOutcome: PromptOutcomeCheck | undefined, ) { const retired = yield* runRuntimeCallbackAtGeneration( generation, @@ -8929,14 +8938,31 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(runtimeRestartRequired, true); yield* cancelPendingRuntimeRequests(); yield* terminalizeOpenForegroundTools(context, "failed"); + // Bounded: it runs under the transition permit that Stop and the next turn wait on. + const recorded = + checkPromptOutcome === undefined + ? undefined + : yield* checkPromptOutcome({ stopReason: "end_turn" }, { retired: true }).pipe( + Effect.timeout(PROMPT_OUTCOME_CHECK_TIMEOUT), + Effect.catchCause((cause) => + Effect.logError("failed to check a silent ACP prompt's outcome", { + driver, + cause, + }).pipe(Effect.as(undefined)), + ), + ); const minutes = Math.max(1, Math.round(timeoutMillis / 60_000)); yield* finalizeTurn( context, "failed", - makeProviderFailure({ - class: "provider_error", - message: `${flavor.runtimeHarness ?? driver} sent nothing for ${minutes} ${minutes === 1 ? "minute" : "minutes"}, so T3 Code stopped the turn and restarted the agent. Send a message to continue.`, - }), + recorded?.failure ?? + makeProviderFailure({ + class: "provider_error", + message: `${flavor.runtimeHarness ?? driver} sent nothing for ${minutes} ${minutes === 1 ? "minute" : "minutes"}, so T3 Code stopped the turn and restarted the agent. Send a message to continue.`, + }), + recorded === undefined + ? undefined + : { threadDisposition: recorded.threadDisposition }, ); return "retired" as const; }), @@ -8960,6 +8986,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context: ActiveAcpTurn, generation: number, timeoutMillis: number, + checkPromptOutcome: PromptOutcomeCheck | undefined, ) { yield* Deferred.await(context.promptDispatched); context.lastProgressAt = yield* Clock.currentTimeMillis; @@ -8978,7 +9005,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( continue; } const outcome = yield* runtimeTransitionPermit.withPermit( - retireInactivePrompt(context, generation, timeoutMillis), + retireInactivePrompt(context, generation, timeoutMillis, checkPromptOutcome), ); if (outcome !== "rearm") return; } @@ -9742,6 +9769,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context, promptGeneration, promptInactivityTimeoutMillis, + checkPromptOutcome, ).pipe(Effect.forkIn(sessionScope)); } const compactSession = isCompactionMessage(turnInput.message) @@ -9844,6 +9872,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context, generation, promptInactivityTimeoutMillis, + checkPromptOutcome, ).pipe(Effect.forkIn(sessionScope)); } const releasedForSteer = context.foregroundIdle; From 9dc36169b4a2018ac6c2ca3e32263874475437a3 Mon Sep 17 00:00:00 2001 From: SeniorZhai Date: Mon, 23 Nov 2026 11:55:41 +0800 Subject: [PATCH 161/162] fix(web,mobile): translate remaining untranslated workflow, git, and link strings (#41193) Co-authored-by: Julius Marminge --- apps/mobile/src/i18n/translations/pt-BR.json | 2 +- apps/web/src/i18n/translations/de.json | 2 +- apps/web/src/i18n/translations/es.json | 2 +- apps/web/src/i18n/translations/fr.json | 2 +- apps/web/src/i18n/translations/ja.json | 2 +- apps/web/src/i18n/translations/ko.json | 2 +- apps/web/src/i18n/translations/pt-BR.json | 4 ++-- apps/web/src/i18n/translations/ru.json | 2 +- apps/web/src/i18n/translations/sv.json | 6 +++--- apps/web/src/i18n/translations/zh.json | 2 +- 10 files changed, 13 insertions(+), 13 deletions(-) diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index d8d29e5cd0641..037e9559e0aa3 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -1555,7 +1555,7 @@ "49a888ab323521ae": "Thread ramificada", "5d865442753ef6c2": "Thread criada", "3ccfbf7e86868c35": "Feedback para a equipe do T3", - "3604d2f52be9539e": "Link {target}", + "3604d2f52be9539e": "Vincular {target}", "646de37e0bec85f8": "Chamada de ferramenta", "5469bba2f5569925": "Plano proposto", "c3a88348c14f8258": "Plano atualizado", diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index f63b5ce4f5841..aeb4e4497d43e 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12470,7 +12470,7 @@ "3cc43f1dbf3f8e0c": "Abgebrochen", "ded70e75de6404ba": "Zurück zur Liste der Ausführungen", "2f4ed7dbd22be30d": "Ausführung abbrechen", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Stoppen", "04b050b0329f0ac8": "dauerte {duration}", "aff78e1774818ff4": "bisher {duration}", "38eddd466439afc9": "Was die Ausführung berührt hat", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index b15af98ce01ba..113f1c5d4cafe 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12463,7 +12463,7 @@ "3cc43f1dbf3f8e0c": "Cancelada", "ded70e75de6404ba": "Volver a la lista de ejecuciones", "2f4ed7dbd22be30d": "Cancelar ejecución", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Detener", "04b050b0329f0ac8": "tardó {duration}", "aff78e1774818ff4": "{duration} hasta ahora", "38eddd466439afc9": "Lo que tocó la ejecución", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index f2f519b25ae0b..17c01696429a9 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12468,7 +12468,7 @@ "3cc43f1dbf3f8e0c": "Annulée", "ded70e75de6404ba": "Retour à la liste des exécutions", "2f4ed7dbd22be30d": "Annuler l’exécution", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Arrêter", "04b050b0329f0ac8": "a duré {duration}", "aff78e1774818ff4": "{duration} jusqu’ici", "38eddd466439afc9": "Ce que l’exécution a touché", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index e665b9445f6f9..a13377564e7fe 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12416,7 +12416,7 @@ "3cc43f1dbf3f8e0c": "キャンセル済み", "ded70e75de6404ba": "実行一覧に戻る", "2f4ed7dbd22be30d": "実行をキャンセル", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "停止", "04b050b0329f0ac8": "所要時間 {duration}", "aff78e1774818ff4": "{duration} 経過", "38eddd466439afc9": "この実行が扱ったもの", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 90614ef54230d..da68956e5a4d2 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12411,7 +12411,7 @@ "3cc43f1dbf3f8e0c": "취소됨", "ded70e75de6404ba": "실행 목록으로 돌아가기", "2f4ed7dbd22be30d": "실행 취소", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "중지", "04b050b0329f0ac8": "{duration} 소요", "aff78e1774818ff4": "현재까지 {duration}", "38eddd466439afc9": "이 실행이 다룬 항목", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index e8d50d83a5f44..a0e88601de24c 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2122,7 +2122,7 @@ "cd80122422577239": "Publicar repositório", "c85db9ac99efa605": "Push e criar {term, select, mr {MR} cr {solicitação de alteração} other {PR}}", "dbccf81ad4a03f48": "Sincronizar ref", - "4350ab8128b18105": "Pull", + "4350ab8128b18105": "Fazer pull", "dca2ca8303bfc14e": "Fazer commit e push na ref padrão?", "e196fda632e279d0": "Esta ação vai fazer commit e push das alterações em \"{branch}\". Você pode continuar nesta ref ou criar uma ref de feature e executar a mesma ação nela.", "87e714255e8be7f2": "Fazer push na ref padrão?", @@ -12468,7 +12468,7 @@ "3cc43f1dbf3f8e0c": "Cancelada", "ded70e75de6404ba": "Voltar à lista de execuções", "2f4ed7dbd22be30d": "Cancelar execução", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Parar", "04b050b0329f0ac8": "levou {duration}", "aff78e1774818ff4": "{duration} até agora", "38eddd466439afc9": "O que a execução tocou", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index f15a9f71b21f2..890e0b9d7506b 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12469,7 +12469,7 @@ "3cc43f1dbf3f8e0c": "Отменён", "ded70e75de6404ba": "Назад к списку запусков", "2f4ed7dbd22be30d": "Отменить запуск", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Остановить", "04b050b0329f0ac8": "занял {duration}", "aff78e1774818ff4": "пока {duration}", "38eddd466439afc9": "Что затронул запуск", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 6d53cb0b38d73..967d0c7eededd 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -9576,9 +9576,9 @@ "d2b0987f8c907e13": "Samplar var {ms} ms", "4a3d538e12caed70": "{count, plural, one {Samplar var {seconds} sekund} other {Samplar var {seconds}:e sekund}}", "32c787e014d8f2ec": "Underprocess i backend", - "ca84041dbbfb9e45": "Electron main", + "ca84041dbbfb9e45": "Electrons huvudprocess", "0693ca29c961e19b": "Renderare", - "fb4e08f7e0f78d3b": "Electron utility", + "fb4e08f7e0f78d3b": "Electrons hjälpprocess", "7f206abc2cb38ab2": "Övervakare", "7cdfa8c2f4106d6a": "T3-process", "9bc60e1d0ef816cf": "Lagringsbyte", @@ -12476,7 +12476,7 @@ "3cc43f1dbf3f8e0c": "Avbruten", "ded70e75de6404ba": "Tillbaka till listan över körningar", "2f4ed7dbd22be30d": "Avbryt körningen", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "Stoppa", "04b050b0329f0ac8": "tog {duration}", "aff78e1774818ff4": "{duration} hittills", "38eddd466439afc9": "Vad körningen rörde", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index deaa65edcc1ec..5a5128c0a7c8d 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12492,7 +12492,7 @@ "3cc43f1dbf3f8e0c": "已取消", "ded70e75de6404ba": "返回运行列表", "2f4ed7dbd22be30d": "取消运行", - "614e5ad58a795fb5": "Stop", + "614e5ad58a795fb5": "停止", "04b050b0329f0ac8": "用时 {duration}", "aff78e1774818ff4": "已用时 {duration}", "38eddd466439afc9": "此运行涉及的内容", From 48f6dc09119bd95cceb6a3b2936bf39f4a39d161 Mon Sep 17 00:00:00 2001 From: Renfei Zhou Date: Mon, 23 Nov 2026 07:39:19 +0000 Subject: [PATCH 162/162] fix(fork): resolve upstream merge 9dc36169b4 (2026-11-22) Resolve the 24 conflicts of commit A (1640512383) and fix the breaks the merge brought. - Keep both sides in the server, settings, file preview and adapter conflicts; the fork's change sits on upstream's code. - Drop the fork's early port of Codex full-access approvals (#206): upstream shipped its own fix (#40773). - Re-port the fork's chat Markdown changes onto upstream's Words renderer (#27866) through apps/web/src/fork/forkMarkdown.ts and hooks in wordsHast.ts: single tilde in agent text, CJK bold, CJK link ends, board links, \eps in math, the Dashboard renderer; the sanitizer's board and t3-dashboard protocols move to markdownHast.ts. - CheckpointCaptureService takes upstream's commit id: #31349's lock and reread let only one attempt of a run commit a capture. Commit A keeps the per-attempt queued capture effect id; the fork steer test pins it and now models the order the lock allows. - Upstream's virtualized Markdown list (#40631) keeps no reading place for now: the fork's binding for it is dropped and will be rebuilt (orbitingflea/t3code#264). README notes this and the 1-64 MB text files loaded in parts. The fork's panel test follows upstream's routing of large text files. - Upstream code now loads the fork's chat Markdown and chunk reload guard in tests: the whiteboard hover handler is imported from boardChannel (no re-export from the Markdown pass), and the chunk reload build key lives in chunkReloadGuard.ts. - Workflow agent links decode the run-result shape of t3_thread_send; the fork's CLI commands join upstream's feedback command list; fork tests mock upstream's new services; agent context budget 67360. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- apps/server/src/cli/thread.ts | 4 - .../src/environment/ServerEnvironment.ts | 5 +- apps/server/src/feedback/FeedbackReport.ts | 2 + apps/server/src/fork/fyi/Fyi.test.ts | 3 +- apps/server/src/fork/fyi/Fyi.ts | 5 +- .../server/src/fork/generalRoleParity.test.ts | 4 + .../Adapters/ClaudeAdapterV2.ts | 7 - .../Adapters/CodexAdapterV2.test.ts | 30 ---- .../Adapters/CodexAdapterV2.ts | 21 +-- .../CheckpointCaptureService.ts | 8 - .../src/orchestration-v2/ProjectionStore.ts | 3 - .../ProviderSessionManager.ts | 77 +------- .../ProviderTurnStartService.ts | 34 +--- .../SteeringCompletion.integration.test.ts | 15 +- .../src/orchestration-v2/runtimeLayer.ts | 3 - .../src/provider/Drivers/AntigravityDriver.ts | 8 +- .../src/provider/agentContextBudget.json | 8 +- .../src/workflows/WorkflowAgentLinks.ts | 4 +- apps/web/src/components/ChatMarkdown.tsx | 165 +++--------------- .../components/ComposerPromptEditorTiptap.tsx | 2 +- .../chat/ComposerPendingUserInputPanel.tsx | 2 +- .../src/components/chat/MarkdownFileLink.tsx | 98 ++--------- apps/web/src/components/chat/MathTypeset.tsx | 50 ------ .../src/components/chat/ProposedPlanCard.tsx | 4 +- .../components/chat/TimelineWorkEntryRow.tsx | 8 +- .../components/chat/TimelineWorkGroupRows.tsx | 12 +- .../chat/UserMessageContextChips.tsx | 4 +- .../components/chat/timelineMinimapItems.ts | 19 +- .../composerContextPresentation.tsx | 4 +- .../src/components/files/FilePreviewPanel.tsx | 8 - .../fileReadingPosition.browser.test.tsx | 74 ++------ .../components/files/fileReadingTestKit.tsx | 11 +- .../settings/settingsSearch.test.ts | 3 - .../src/components/settings/settingsSearch.ts | 9 - .../useAvailableSettingsSearchItems.ts | 7 +- .../components/workflows/WorkflowRunFeed.tsx | 2 + apps/web/src/fork/chunkReloadBuild.ts | 10 -- apps/web/src/fork/cjkLinkEnd.test.tsx | 69 +++++--- apps/web/src/fork/cjkLinkEnd.ts | 153 +++++++++------- .../src/fork/dashboard/dashboardMarkdown.tsx | 42 ++--- apps/web/src/fork/forkMarkdown.test.ts | 97 ++++++++++ apps/web/src/fork/forkMarkdown.ts | 114 ++++++++++++ .../whiteboard/markdown-whiteboard.test.ts | 44 ++--- .../fork/whiteboard/markdown-whiteboard.ts | 80 +++++---- apps/web/src/lib/chunkReloadGuard.ts | 13 +- apps/web/src/markdown/wordsHast.ts | 14 +- fork/whiteboard/run-t3.md | 2 +- packages/contracts/src/environment.ts | 3 - packages/contracts/src/orchestratorMcp.ts | 2 +- packages/shared/src/markdownHast.ts | 2 + packages/shared/src/markdownPipeline.ts | 130 -------------- 52 files changed, 571 insertions(+), 929 deletions(-) delete mode 100644 apps/web/src/components/chat/MathTypeset.tsx delete mode 100644 apps/web/src/fork/chunkReloadBuild.ts create mode 100644 apps/web/src/fork/forkMarkdown.test.ts create mode 100644 apps/web/src/fork/forkMarkdown.ts diff --git a/README.md b/README.md index 45a1770d1200c..1496dbb2e6f70 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ This is a fork of T3 Code that integrates a few additional features, including: - **Compact when idle for Claude threads:** a choice in Settings → Providers → Advanced → Compact idle threads. Besides compacting before the prompt cache expires, it compacts a large idle Claude thread (default 400K tokens or more) a set time (default 15 minutes) after the last message or answer from a user or a bot, so the compaction runs while no one waits for a reply. The token counts and the wait are set right under the choice. - **Prune idle worker threads:** `t3 prune-worker-threads` deletes the messages, turn items, nodes, plans and runtime requests of idle worker threads. A worker thread is idle when it has no open run and, in the last 7 days, was not created, had no run requested or ended, and had no turn item or message updated. A worker thread is a subagent thread that an agent started. Subagent threads that a bot starts are workers too. Threads a person opens, bot threads themselves and a person's forks are never workers. An idle worker keeps its rows while recovery still needs the worker, or while a thread that keeps its own rows names the worker as parent or fork source. Pruned threads keep their thread row, runs, parent link and pull request links, so they still show up and open with no messages. The command runs only when you call it, so run it daily to keep worker transcripts from piling up. Other threads still grow the database. With `--dry-run`, the command only prints how many threads it would empty and how many rows it would delete. You can run the command while the server runs. - **One way to start subagents in Claude and Codex threads:** T3 Code starts Claude and Codex sessions without the provider's own subagent tools: Claude's `Agent`, `Workflow`, `SendMessage` and `ListAgents`, and Codex's `spawn_agent` with its other collaboration tools. The agent starts every subagent, same provider and model included, with T3 Code's `delegate_task` tool, so each child is a T3 Code thread that you can open and follow. -- **Files remember where you stopped reading:** a file in the right panel opens where you left it when you switch back to its tab, close and reopen it, or reload the app. This covers code, Markdown, PDFs, large text files, CSV and TSV tables, HTML pages, Word and PowerPoint files, the first sheet of an Excel or ODS spreadsheet, notebooks, Mermaid diagrams and chat attachments; video and audio come back paused at the time you left. If the file changed, it opens at the same place, or at its start or end when that place is gone. Places stay in this browser for 30 days. A link to a line still jumps to that line once. PDFs in the right panel open in T3 Code's own PDF viewer, also in Chrome and Edge on the desktop. Image zoom, fonts, archives, SQLite files, ODT, ODP, RTF and EPUB files, HTML attachments and the other sheets of a spreadsheet still open at the top. A place in a notebook cell after the first 20 opens at the end of cell 20. +- **Files remember where you stopped reading:** a file in the right panel opens where you left it when you switch back to its tab, close and reopen it, or reload the app. This covers code, Markdown source, PDFs, large text files, CSV and TSV tables, HTML pages, Word and PowerPoint files, the first sheet of an Excel or ODS spreadsheet, notebooks, Mermaid diagrams and chat attachments; video and audio come back paused at the time you left. If the file changed, it opens at the same place, or at its start or end when that place is gone. Places stay in this browser for 30 days. A link to a line still jumps to that line once. PDFs in the right panel open in T3 Code's own PDF viewer, also in Chrome and Edge on the desktop. Image zoom, fonts, archives, SQLite files, ODT, ODP, RTF and EPUB files, HTML attachments, the other sheets of a spreadsheet and rendered workspace Markdown still open at the top. Text files of 1 MB to 64 MB open in source view in parts after the first megabyte, so past 1 MB a saved place may not be restored and a line link may stop at the end of the text loaded so far. [Issue #264](https://github.com/orbitingflea/t3code/issues/264) tracks support for rendered workspace Markdown and these 1 MB to 64 MB text files. A place in a notebook cell after the first 20 opens at the end of cell 20. - **Reflink worktrees on Linux:** Settings → Worktrees → Reflink worktrees (on by default) clones new worktrees copy-on-write from a cache of recent checkouts on the worktree location's drive, so worktrees share disk space until files change. Drives that cannot clone, such as ext4, use Git's normal checkout. - **FYI messages between agents:** an agent can send another thread an FYI, a note of at most 16,000 characters that needs no action and starts no turn. The receiving agent gets it with its next turn; a running Claude Code thread gets it at its next tool call. An FYI counts as delivered only when the turn that carries it finishes: a turn that fails, is stopped, restarts or is reverted gives it back, so the agent may see it twice. When a thread has an FYI waiting and has been idle for 6 hours, T3 Code wakes it to deliver its FYIs, unless the thread is settled, archived, waiting for your answer or holds queued messages; a snoozed thread waits until its snooze ends. The 6 hours count from the thread's last turn, or from the reset of a usage limit that stopped it on the provider it still uses (or from the end of a snooze that ends after that reset), so an FYI to a thread that has been idle longer wakes it within minutes. A thread whose usage limit has no known reset time, or whose provider fails every turn, gets a failed wake every 6 hours while an FYI waits. A wake carries up to 16,000 characters of FYIs. The rest, and any that a wake gives back because it failed or you stopped it, get another wake after 6 more idle hours. A wake is a new turn, so **Resume** no longer continues a turn that ended before it. Settle or archive a thread to stop its wakes. The timeline marks these messages "FYI · waiting", "FYI · sent" while the turn that carries them runs, and "FYI" once it finished. - **Open server files by their path:** in a browser signed in to T3 Code at its own address, open `/` (such as `https://t3.example.com/home/ana/work/report.html`) to see that file read-only, for files under the server user's home folder and temp folder. A session needs the `filesystem:read` permission, and a signed-out browser gets a sign-in page. Text and code of any type show as plain text, and images, PDFs, audio and video show as themselves. A folder shows its `index.html`, or else a list of its files. Links ending in `:line` or `:line:col` open the file. Names that start with `.`, and T3 Code's own data folder, are not served. An HTML page runs in a sandboxed frame at the same address: its scripts run but cannot act as you in T3, and it loads files from its own folder and below for an hour, though its scripts cannot fetch them. A page directly in the home or temp folder loads no other files. An HTML page linked from another site, or any HTML page over plain HTTP, first shows an Open link. diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index f039536cbf724..3ba496d1a522b 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -250,15 +250,11 @@ export type ThreadTools = ReturnType; * outside agent does, and revokes that session when the command ends. */ export const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* ( -<<<<<<< origin/main - flags: { readonly baseDir: Option.Option; readonly json: boolean }, -======= flags: { readonly baseDir: Option.Option; readonly json: boolean; readonly clientLabel?: string; }, ->>>>>>> upstream/main run: (tools: ThreadTools) => Effect.Effect, ) { const logLevel = yield* GlobalFlag.LogLevel; diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 223979c7e2808..504f00f81d254 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -311,11 +311,8 @@ export const make = Effect.gen(function* () { mcpHostedApproval: true, shellThreadFamilies: true, shellOlderSettled: true, -<<<<<<< origin/main - ...(yield* whiteboardPanelCapabilities()), -======= agentFeedback: true, ->>>>>>> upstream/main + ...(yield* whiteboardPanelCapabilities()), }, }; diff --git a/apps/server/src/feedback/FeedbackReport.ts b/apps/server/src/feedback/FeedbackReport.ts index f7c026700b0e8..0262fa6b01cfb 100644 --- a/apps/server/src/feedback/FeedbackReport.ts +++ b/apps/server/src/feedback/FeedbackReport.ts @@ -158,6 +158,8 @@ export const T3_CLI_COMMANDS: ReadonlyArray = [ "t3 thread start", "t3 thread send", "t3 thread show", + "t3 thread user-view", + "t3 prune-worker-threads", "t3 feedback", "t3 feedback list", "t3 workflow", diff --git a/apps/server/src/fork/fyi/Fyi.test.ts b/apps/server/src/fork/fyi/Fyi.test.ts index dde27d9a61803..056d83d63d820 100644 --- a/apps/server/src/fork/fyi/Fyi.test.ts +++ b/apps/server/src/fork/fyi/Fyi.test.ts @@ -116,7 +116,8 @@ describe("turnCarriesFyi", () => { ["a prose message", "Fix the flaky test", [], false, true], ["/compact", "/compact", [], false, false], ["a slash command after spaces", " /review", [], false, false], - ["a slash message with an image", "/look at this", [{}], false, true], + ["a slash message with an image", "/look at this", [{}], false, false], + ["a path", "/srv/app/notes.md has the plan", [], false, true], ["a goal command", "/goal ship it", [], true, false], ["a skill mention", "$deploy ship it", [], false, false], ["a skill mention with another sigil after spaces", " €review the plan", [], false, false], diff --git a/apps/server/src/fork/fyi/Fyi.ts b/apps/server/src/fork/fyi/Fyi.ts index aa7af4129dbee..a7406d7867fee 100644 --- a/apps/server/src/fork/fyi/Fyi.ts +++ b/apps/server/src/fork/fyi/Fyi.ts @@ -17,6 +17,8 @@ import { type TurnItemId, } from "@t3tools/contracts"; import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; + +import { isSlashCommandMessage } from "../../orchestration-v2/ContextHandoffDelivery.ts"; import { latestExecutedRun, latestRootProviderFailure, @@ -79,7 +81,8 @@ export function turnCarriesFyi(input: { !input.goalCommand && !input.resumesNatively && !(message.createdBy === "agent" && message.creationSource === "provider") && - !(message.attachments.length === 0 && message.text.trimStart().startsWith("/")) && + // A slash command reaches the provider verbatim, attachments or not, so it carries none. + !isSlashCommandMessage({ role: "user", text: message.text }) && !LEADING_SKILL_MENTION.test(message.text) ); } diff --git a/apps/server/src/fork/generalRoleParity.test.ts b/apps/server/src/fork/generalRoleParity.test.ts index 7abb7963aeca1..714b70bc839e2 100644 --- a/apps/server/src/fork/generalRoleParity.test.ts +++ b/apps/server/src/fork/generalRoleParity.test.ts @@ -47,6 +47,7 @@ import { ThreadDashboard } from "./threadDashboard/ThreadDashboard.ts"; import { UserView } from "./userView/UserView.ts"; import { ServerEnvironment } from "../environment/ServerEnvironment.ts"; import * as EnvironmentTheme from "../environmentTheme.ts"; +import { FeedbackStore } from "../feedback/FeedbackStore.ts"; import { GitManager } from "../git/GitManager.ts"; import { GitWorkflowService } from "../git/GitWorkflowService.ts"; import { IssueService } from "../issue/IssueService.ts"; @@ -91,6 +92,7 @@ import * as ServerSettings from "../serverSettings.ts"; import { SourceControlRepositoryService } from "../sourceControl/SourceControlRepositoryService.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts"; +import { Workflows } from "../workflows/Workflows.ts"; import { TaskFolders } from "../workspace/TaskFolders.ts"; const projectId = ProjectId.make("project:general-role-parity"); @@ -693,6 +695,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(UserView)({}), Layer.mock(DisplayModeWrap)({ forgetNotesAfterCompaction: () => (ingest) => ingest }), Layer.mock(DocumentText)({}), + Layer.mock(FeedbackStore)({}), Layer.mock(EnvironmentTheme.EnvironmentThemeService)({}), Layer.mock(GitVcsDriver.GitVcsDriver)({}), Layer.mock(GitManager)({}), @@ -730,6 +733,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(TaskFolders)({}), Layer.mock(ThreadSearch)({}), Layer.mock(VcsStatusBroadcaster)({}), + Layer.mock(Workflows)({}), ).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); const decodeToolsList = Schema.decodeUnknownEffect( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 6ff7329910411..614a24c73cd20 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1696,14 +1696,10 @@ export const layerQueryRunner: Layer.Layer< ...(resumeSessionAt === undefined ? {} : { resumeSessionAt }), env: { ...(sdkOptions.env ?? hostEnvironment), -<<<<<<< origin/main ...claudeTerminalToolEnvironment, ...DELEGATE_ONLY_PROVIDERS.claudeAgent.hide.environment, - ...(input.resume -======= // The CLI would re-run a failed request by itself, then run the resume prompt as a second turn. ...(input.resume && !endsOnFailedRequest ->>>>>>> upstream/main ? { CLAUDE_CODE_RESUME_INTERRUPTED_TURN: "1", CLAUDE_CODE_RESUME_REASON: "user_resume", @@ -2559,15 +2555,12 @@ export function makeClaudeQueryOptions(input: { }, } as ClaudeSdkSettings); const deviceInstructions = input.mcpServers !== undefined && input.deviceToolsAvailable === true; -<<<<<<< origin/main const hooks = { ...input.hooks, ...(deviceInstructions ? { SubagentStart: [{ hooks: [subagentDeviceInstructions] }] } : {}), ...(input.onStop === undefined ? {} : { Stop: [{ hooks: [input.onStop] }] }), }; -======= const agentFeedback = input.mcpServers === undefined ? "off" : (input.agentFeedback ?? "off"); ->>>>>>> upstream/main const options: ClaudeAgentSdkQueryOptions = { model: compiledSelection.apiModelId, // T3 names threads; a supplied title skips Claude's redundant naming request. diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 6299f41d611e8..aea174821f2a4 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -2105,9 +2105,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); -<<<<<<< origin/main - it.effect("accepts dangerous-command approvals in full-access without asking", () => -======= it.effect.each([ { name: "dangerous command", networkApprovalContext: undefined, asks: false }, { @@ -2116,7 +2113,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { asks: true, }, ] as const)("full access asks about a $name: $asks", ({ networkApprovalContext, asks }) => ->>>>>>> upstream/main Effect.gen(function* () { const nativeThreadId = "command-approval-thread"; const nativeTurnId = "command-approval-turn"; @@ -2138,22 +2134,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { itemId: "exec-rm", command: "/bin/bash -lc 'rm -rf ./node_modules'", startedAtMs: 0, -<<<<<<< origin/main - }, - }, - }, - { type: "expect_outbound", frame: { id: 0, result: { decision: "accept" } } }, - { - type: "emit_inbound", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), - }, - }, - }, -======= ...(networkApprovalContext === undefined ? {} : { networkApprovalContext }), }, }, @@ -2173,7 +2153,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, }, ] as const)), ->>>>>>> upstream/main ], }), (event) => @@ -2196,14 +2175,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { harness.firstTerminal.pipe(Effect.as(undefined)), Queue.take(pending), ); -<<<<<<< origin/main - assert.isUndefined(request, "Full access must not wait for a command approval"); - assert.equal(yield* Queue.size(pending), 0, "Full access must not show a command approval"); - assert.deepEqual( - harness.terminalEvents().map((event) => event.status), - ["completed"], - ); -======= assert.equal(request?.kind, asks ? "command" : undefined); if (!asks) { assert.deepEqual( @@ -2211,7 +2182,6 @@ describe("CodexAdapterV2 post-settle continuation", () => { ["completed"], ); } ->>>>>>> upstream/main }).pipe( Effect.scoped, Effect.provide( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 46a4012ae146f..10b46bde3b866 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -6128,12 +6128,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload, ); } -<<<<<<< origin/main - // Codex still asks for commands it deems dangerous under the granular full-access policy. - if ( - context.input.runtimePolicy.runtimeMode === "full-access" && - context.input.runtimePolicy.approvalPolicy === undefined -======= // T3's Full access policy is granular, under which Codex still asks before commands it // deems dangerous. Managed-network asks enforce the user's allowlist, so they still ask. if ( @@ -6142,7 +6136,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( context.input.runtimePolicy.sandboxPolicy === undefined && payload.networkApprovalContext == null && (payload.proposedNetworkPolicyAmendments ?? []).length === 0 ->>>>>>> upstream/main ) { return { decision: "accept", @@ -7873,17 +7866,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(yield* Ref.get(settledTurns)), ...(yield* Ref.get(activeTurns)), ]); -<<<<<<< origin/main - const started = yield* client.request( - "turn/start", - withCodexCommandNote(turnStartParams, turnInput.message.messageId, commandNote), - ); - if (commandNote !== undefined) yield* commandNote.delivered; -======= const started = yield* client - .request("turn/start", turnStartParams) + .request( + "turn/start", + withCodexCommandNote(turnStartParams, turnInput.message.messageId, commandNote), + ) .pipe(withAppServerDeadline("turn/start")); ->>>>>>> upstream/main + if (commandNote !== undefined) yield* commandNote.delivered; const previousTurn = previousTurns.get(started.turn.id) ?? (yield* Ref.get(activeTurns)).get(started.turn.id); diff --git a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts index c6f9952627fc0..dd7f27079a4e5 100644 --- a/apps/server/src/orchestration-v2/CheckpointCaptureService.ts +++ b/apps/server/src/orchestration-v2/CheckpointCaptureService.ts @@ -208,15 +208,7 @@ export const layer: Layer.Layer< ], { concurrency: 2 }, ); -<<<<<<< origin/main - // Omit delegatedCompletion to preserve cohort writes made after capture loaded the run. - const { delegatedCompletion: _delegatedCompletion, ...runWithoutDelegatedCompletion } = run; - const commandId = CommandId.make( - `command:effect:checkpoint.capture:${run.activeAttemptId ?? run.id}`, - ); -======= const commandId = CommandId.make(`command:effect:checkpoint.capture:${run.id}`); ->>>>>>> upstream/main const checkpointEvent = (payload: OrchestrationV2Checkpoint) => Effect.map(ids.allocate.event({ threadId: input.threadId, commandId }), (id) => ({ id, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 5000bfcdba995..d5ce6d6950f6e 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -102,11 +102,8 @@ import * as SqlClient from "effect/sql/SqlClient"; import type * as Statement from "effect/sql/Statement"; import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; -<<<<<<< origin/main import { SEND_TO_USER_PAYLOAD_LIKE } from "@t3tools/shared/displayModes"; -======= import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; ->>>>>>> upstream/main import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; import * as ShownHistory from "../fork/shownHistory/ShownHistory.ts"; import { DELEGATED_TASK_MESSAGE_CONDITION } from "./delegatedTaskMessage.ts"; diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index b0d4893e77ca2..9c521fd6495dc 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -2766,83 +2766,12 @@ export const layerWithOptions = ( Effect.map(({ loaded }) => loaded), ), startTurn: (input) => -<<<<<<< origin/main startBusyTurn( input, - runtime.startTurn(input).pipe(turnMetrics("send", input.modelSelection.model)), -======= - observeActivity( - providerSessionId, - ensureThreadAttached({ - providerSessionId, - threadId: input.threadId, - providerInstanceId: runtime.instanceId, - }), - ).pipe( - // Failed or stopped starts may omit turn.terminal; clear their turns so sessions can idle. - Effect.andThen( - holdThreadLoaded({ - providerSessionId, - threadId: input.threadId, - providerThread: input.providerThread, - }), - ), - Effect.andThen( - Effect.acquireUseRelease( - markBusy( - providerSessionId, - busyTurnKey(input.providerThread.id, input.runOrdinal), - runtime, - ).pipe( - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.driver-session.activity-failed", { - providerSessionId, - cause, - }).pipe(Effect.as(true)), - ), - // A release between attach and markBusy leaves nothing to mark: fail the - // start instead of running it on a runtime being torn down. - Effect.flatMap((marked) => - marked - ? Effect.void - : Effect.fail( - new ProviderAdapter.ProviderAdapterTurnStartError({ - driver: runtime.driver, - threadId: input.threadId, - providerThreadId: input.providerThread.id, - runId: input.runId, - cause: "The provider session was released while the turn started.", - }), - ), - ), - ), - () => - agentFeedbackMode.pipe( - Effect.flatMap((agentFeedback) => - runtime.startTurn({ ...input, agentFeedback }), - ), - turnMetrics("send", input.modelSelection.model), - ), - (_, exit) => - Exit.isFailure(exit) - ? observeActivity( - providerSessionId, - markIdle(providerSessionId, input.providerThread.id, input.runOrdinal), - ).pipe( - // A failed start can leave its native thread gone (Claude rejecting a - // resume), so the next start must ask the adapter to resume it again. - Effect.andThen( - forgetProviderThreadLoaded({ - providerSessionId, - threadId: input.threadId, - runtime, - }), - ), - ) - : Effect.void, - ), + agentFeedbackMode.pipe( + Effect.flatMap((agentFeedback) => runtime.startTurn({ ...input, agentFeedback })), + turnMetrics("send", input.modelSelection.model), ), ->>>>>>> upstream/main ), ...(compactThread === undefined ? {} diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 5365c8fb78706..69d7b3a89cb52 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1049,7 +1049,6 @@ export const layer: Layer.Layer< projection.providerTurns, projection.attempts, ); -<<<<<<< origin/main const turnFyi = yield* fyiDelivery.forTurn({ threadId: run.threadId, message: providerMessage, @@ -1058,13 +1057,11 @@ export const layer: Layer.Layer< (run.restartContinuationOfRunId !== undefined && !noteContinuation) || (manualResume && unsentResumeMessage === undefined), }); -======= let compactionMessageIdSet: ReadonlySet | undefined; const compactionMessageIds = () => (compactionMessageIdSet ??= new Set( projection.messages.filter(isSlashCommandMessage).map((candidate) => candidate.id), )); ->>>>>>> upstream/main const restartCancelledWork = pendingRestartCancelledBackgroundWork({ runs: projection.runs, providerTurns: projection.providerTurns, @@ -1929,6 +1926,7 @@ export const layer: Layer.Layer< retryHandoff.attachments.length > 0 || sideChatHandoff !== undefined || restartNote !== "" || + turnFyi.text !== "" || noteContinuation; // Pending context turns the resume into a prompted turn, which needs no native resume. if ( @@ -1947,7 +1945,6 @@ export const layer: Layer.Layer< }); return; } -<<<<<<< origin/main const noteContext = DisplayModeWrap.noteContextAtTurnStart({ sameNativeThread, handoffCount: effectiveHandoffs.length, @@ -1958,9 +1955,6 @@ export const layer: Layer.Layer< wrapped = yield* displayModeWrap.wrapUserText({ ...wrapInput, context: noteContext }); userText = wrapped.text; } - const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); -======= ->>>>>>> upstream/main const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, contextUsage: handoffUsage, @@ -2130,14 +2124,11 @@ export const layer: Layer.Layer< ], }); }); -<<<<<<< origin/main const acceptingSession = DisplayModeWrap.deliveringNote(session, wrapped); -======= let inlineDeliveredHandoffs: ReadonlyArray = []; let promptDroppedOnTerminal = false; const inlineDeliveryLock = yield* Semaphore.make(1); const retryHandoffIds = new Set(retryHandoff.handoffs.map((handoff) => handoff.id)); ->>>>>>> upstream/main const startWithHandoffs = Effect.fn("ProviderTurnStartService.startWithHandoffs")( function* (turnInput: Parameters[0], compact = false) { const delivery = yield* deliverContextHandoffs({ @@ -2170,9 +2161,6 @@ export const layer: Layer.Layer< sideChatHandoff === undefined || compact || slashCommand ? "" : sideChatHandoff.summaryText; -<<<<<<< origin/main - const context = [delivery.context, sideChatContext, restartNote, turnFyi.text] -======= // Record inline handoffs before startTurn so an immediate dropped terminal can restore them. inlineDeliveredHandoffs = [ ...delivery.inlineHandoffs.map((handoff) => @@ -2182,8 +2170,7 @@ export const layer: Layer.Layer< ), ...(sideChatContext === "" || sideChatHandoff === undefined ? [] : [sideChatHandoff]), ]; - const context = [delivery.context, sideChatContext, restartNote] ->>>>>>> upstream/main + const context = [delivery.context, sideChatContext, restartNote, turnFyi.text] .filter((part) => part !== "") .join("\n\n"); const { restartContinuationOfRunId: _resumedRunId, ...promptedInput } = turnInput; @@ -2286,22 +2273,9 @@ export const layer: Layer.Layer< }), ), ); -<<<<<<< origin/main - const deliverySession = - effectiveHandoffs.length === 0 && - retryHandoff.handoffs.length === 0 && - retryHandoff.attachments.length === 0 && - sideChatHandoff === undefined && - restartNote === "" && - turnFyi.text === "" && - !noteContinuation - ? acceptingSession - : makeDeliverySession(acceptingSession, startWithHandoffs); -======= const deliverySession = carriesPendingContext - ? makeDeliverySession(session, startWithHandoffs) - : session; ->>>>>>> upstream/main + ? makeDeliverySession(acceptingSession, startWithHandoffs) + : acceptingSession; return runExecution.startRootRun({ commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`), appThread: projection.thread, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 033d74a58c20b..4922d817c03c0 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1402,13 +1402,13 @@ it.effect("restarts the turn for an image when native steering takes text only", ); it.effect.each(["completed", "interrupted"] as const)( - "checkpoints a run that a steer restarted after its first answer was checkpointed (restart %s)", + "checkpoints a run that a steer restarted before its first answer was checkpointed (restart %s)", (restartEnd) => Effect.gen(function* () { const steerReadRunning = yield* Deferred.make(); const letSteerCommit = yield* Deferred.make(); const { events, started, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - `steer-restart-after-checkpoint-${restartEnd}`, + `steer-restart-before-checkpoint-${restartEnd}`, true, false, Effect.void, @@ -1480,10 +1480,7 @@ it.effect.each(["completed", "interrupted"] as const)( }) .pipe(Effect.forkScoped); yield* Deferred.await(steerReadRunning); - const firstCompleted = yield* runReaches("completed"); yield* endTurn(started[0]!, "completed"); - const firstCapture = yield* worker.drain().pipe(Effect.forkScoped); - yield* Fiber.join(firstCompleted); const restartRunning = yield* orchestrator.streamDomainEvents.pipe( Stream.filter( (event) => @@ -1497,8 +1494,12 @@ it.effect.each(["completed", "interrupted"] as const)( ); yield* Deferred.succeed(letSteerCommit, undefined); yield* Fiber.join(steer); - yield* Fiber.join(firstCapture); - yield* worker.drain(); + // The first answer's capture finds the run restarting and retries until it gives up; the + // restarted attempt starts behind it on the thread's effect lane. + for (const delay of [0, 100, 200, 400, 800]) { + yield* TestClock.adjust(delay); + yield* worker.drain(); + } yield* Fiber.join(restartRunning); yield* (yield* ThreadCommandExecutor.ThreadCommandExecutor).withLock(threadId, Effect.void); assert.equal(started.length, 2); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 536e4e3451d08..d1f67723c6d72 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -65,16 +65,13 @@ import * as ThreadForkService from "./ThreadForkService.ts"; import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; -<<<<<<< origin/main import * as DisplayModeWrap from "../fork/displayModeWrap/DisplayModeWrap.ts"; import * as FyiDelivery from "../fork/fyi/FyiDelivery.ts"; import * as FyiWakeWorker from "../fork/fyi/FyiWakeWorker.ts"; import * as ThreadDashboard from "../fork/threadDashboard/ThreadDashboard.ts"; import * as UserView from "../fork/userView/UserView.ts"; import * as SubThreads from "../fork/subThreads/SubThreads.ts"; -======= import * as FeedbackStore from "../feedback/FeedbackStore.ts"; ->>>>>>> upstream/main import * as WorkspaceFolders from "../workspace/WorkspaceFolders.ts"; import * as TaskFolderStore from "../workspace/TaskFolderStore.ts"; diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index e5b5e363e102a..093d8666b318c 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -603,10 +603,6 @@ export const AntigravityDriver: ProviderDriver< probeUsage: usage.probe, clearUsage: usage.clear, auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) }, -<<<<<<< origin/main - supportsTextGeneration: runtimeState.pipe( - Effect.flatMap((state) => isAntigravityTextGenerationAvailable(state.root)), -======= ...(rememberedRuntimeModes ? { rememberedRuntimeModes } : {}), rememberRuntimeModes: (modes) => writeFileStringAtomically({ @@ -617,8 +613,8 @@ export const AntigravityDriver: ProviderDriver< Effect.provideService(Path.Path, path), Effect.catch(() => Effect.logWarning("Could not save Antigravity permission modes.")), ), - supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe( ->>>>>>> upstream/main + supportsTextGeneration: runtimeState.pipe( + Effect.flatMap((state) => isAntigravityTextGenerationAvailable(state.root)), Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), Effect.orElseSucceed(() => false), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 5f19fb99ce6d1..9ddc4254d9fea 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,11 +1,5 @@ { -<<<<<<< origin/main "claudeSystemAppendBytes": 5945, "codexAdditionalContextBytes": 7339, - "mcpToolListJsonBytes": 64688 -======= - "claudeSystemAppendBytes": 6245, - "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 61724 ->>>>>>> upstream/main + "mcpToolListJsonBytes": 67360 } diff --git a/apps/server/src/workflows/WorkflowAgentLinks.ts b/apps/server/src/workflows/WorkflowAgentLinks.ts index 6a0836fc0162c..17afc658b2cd4 100644 --- a/apps/server/src/workflows/WorkflowAgentLinks.ts +++ b/apps/server/src/workflows/WorkflowAgentLinks.ts @@ -4,7 +4,7 @@ import { OrchestratorMcpFailure, OrchestratorMcpThreadInterruptResult, OrchestratorMcpThreadReadResult, - OrchestratorMcpThreadSendResult, + OrchestratorMcpThreadSendRunResult, OrchestratorMcpThreadWaitResult, } from "@t3tools/contracts"; import * as Duration from "effect/Duration"; @@ -170,7 +170,7 @@ export const make = Effect.gen(function* () { input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema }; if (input.thread !== undefined) { if (input.launch !== undefined) return yield* launchOnContinue; - const sent = yield* call(environment, "t3_thread_send", OrchestratorMcpThreadSendResult, { + const sent = yield* call(environment, "t3_thread_send", OrchestratorMcpThreadSendRunResult, { threadId: input.thread, message: input.prompt, mode: "queue", diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index eaf67d10224df..7dd8bd7ac2878 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -21,20 +21,7 @@ import { AuthOrchestrationOperateScope, SOURCE_CONTROL_MEDIA_ASSET, } from "@t3tools/contracts"; -<<<<<<< origin/main -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - CHAT_MARKDOWN_REHYPE_PLUGINS, - chatMarkdownImageSource, - decodeMarkdownLinkEscapes, - ASSISTANT_MARKDOWN_REMARK_PLUGINS, - ASSISTANT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; -======= import { chatMarkdownImageSource } from "@t3tools/shared/markdownHast"; ->>>>>>> upstream/main import { useAtomValue } from "@effect/atom-react"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, @@ -100,24 +87,12 @@ import React, { useState, type ReactNode, } from "react"; -<<<<<<< origin/main -import type { - Components, - ExtraProps as ReactMarkdownExtraProps, - Options as ReactMarkdownOptions, -} from "react-markdown"; -import { createIncrementalMarkdownPlugin } from "../markdown-incremental"; -import { postWhiteboardHover, remarkWhiteboardLinks } from "../fork/whiteboard/markdown-whiteboard"; +import { postWhiteboardHover } from "../fork/whiteboard/boardChannel"; import { chatAnchorPanelLinks } from "../fork/rightPanelSplit/chatAnchorLink"; import { openedSync } from "../fork/rightPanelSplit/linkSources"; import { type OpenedSurface, startPanelLinkDrag } from "../fork/rightPanelSplit/panelLinkDrag"; import { showBoardRef } from "../fork/whiteboard/boardChannel"; -import { remarkEndLinksAtCjkPunctuation } from "../fork/cjkLinkEnd"; import { DashboardLinkChip, parseDashboardHref } from "../fork/dashboard/dashboardLink"; -import type { Pluggable, PluggableList } from "unified"; -import { defaultUrlTransform } from "react-markdown"; -======= ->>>>>>> upstream/main import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations"; import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences"; import { parseThreadLinkHref } from "@t3tools/shared/threadLinks"; @@ -463,7 +438,7 @@ type MarkdownComponents = { // react-markdown's defaultUrlTransform: relative URLs, and absolute ones with a safe protocol. const SAFE_PROTOCOL = /^(?:https?|ircs?|mailto|xmpp)$/i; -function safeUrl(value: string): string { +export function safeUrl(value: string): string { const colon = value.indexOf(":"); const before = (character: string) => { const at = value.indexOf(character); @@ -538,13 +513,8 @@ function blockFileLinkSources( text: string, cwd: string | undefined, imageBaseDir: string | undefined, -<<<<<<< origin/main - peerPaths: readonly string[] = [], - hostFileOrigins: readonly string[] = [], -): string { -======= + hostFileOrigins: readonly string[], ): BlockFileLinkSources { ->>>>>>> upstream/main const hrefs = extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(text)) .filter((href) => !parseComposerContextHref(href)) .map(decodeMarkdownLinkEscapes) @@ -553,9 +523,6 @@ function blockFileLinkSources( const spans = extractInlineCodeSpans(text).filter((span) => resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd), ); -<<<<<<< origin/main - return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)], peerPaths]); -======= return { hrefs, spans }; } @@ -569,12 +536,14 @@ function fileLinkSourcesKey( cwd: string | undefined, imageBaseDir: string | undefined, streamingBlocks: ReadonlyArray | null, + peerPaths: readonly string[] = [], + hostFileOrigins: readonly string[] = [], ): string { if (!streamingBlocks) { - const { hrefs, spans } = blockFileLinkSources(text, cwd, imageBaseDir); - return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); + const { hrefs, spans } = blockFileLinkSources(text, cwd, imageBaseDir, hostFileOrigins); + return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)], peerPaths]); } - const config = `${cwd ?? ""}\u0000${imageBaseDir ?? ""}\u0000`; + const config = `${cwd ?? ""}\u0000${imageBaseDir ?? ""}\u0000${hostFileOrigins.join("\u0001")}\u0000`; const hrefs = new Set(); const spans = new Set(); const last = streamingBlocks.length - 1; @@ -583,7 +552,7 @@ function fileLinkSourcesKey( const key = config + block; let sources = index === last ? undefined : finishedBlockFileLinkSources.get(key); if (!sources) { - sources = blockFileLinkSources(block, cwd, imageBaseDir); + sources = blockFileLinkSources(block, cwd, imageBaseDir, hostFileOrigins); if (index !== last) { if (cachedBlockChars + key.length > MAX_CACHED_BLOCK_CHARS) { finishedBlockFileLinkSources.clear(); @@ -596,8 +565,7 @@ function fileLinkSourcesKey( for (const href of sources.hrefs) hrefs.add(href); for (const span of sources.spans) spans.add(span); } - return JSON.stringify([[...hrefs], [...spans]]); ->>>>>>> upstream/main + return JSON.stringify([[...hrefs], [...spans], peerPaths]); } function resolveFileLinkSources( @@ -624,30 +592,6 @@ function resolveFileLinkSources( return { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath }; } -<<<<<<< origin/main -function useChatMarkdownState({ - text, - inline = false, - cwd, - agentDirectories, - threadRef, - pullRequestPanelRef, - environmentId: explicitEnvironmentId, - onTaskListChange, - isStreaming = false, - skills = EMPTY_MARKDOWN_SKILLS, - onUseArtifactTemplate, - onRunShellCommand, - imageBaseDir, - workspaceMutationId, - onImageExpand, - renderContextReference, - headingLevelOffset = 0, - sourceControlMedia = false, - sourceControlMediaRepository, - fileLinkPeerPaths, -}: ChatMarkdownProps) { -======= function useChatMarkdownState( { text, @@ -669,10 +613,10 @@ function useChatMarkdownState( headingLevelOffset = 0, sourceControlMedia = false, sourceControlMediaRepository, + fileLinkPeerPaths, }: ChatMarkdownProps, streamingBlocks: ReadonlyArray | null, ) { ->>>>>>> upstream/main const gt = useGT(); const messages = useMessages(); const resolvedTheme = useRenderedAppearance(); @@ -870,13 +814,9 @@ function useChatMarkdownState( // Keyed by the file links found, not the text, so streamed text that adds none keeps the // renderer context, and every block reading it, unchanged. // A template literal marks the key as a string, so the compiler memoizes the maps on its value. -<<<<<<< origin/main // A file chip opens in a thread, so only a thread's links to its environment's files become chips. const hostFileOrigins = useHostFileOrigins(threadRef?.environmentId ?? null); - const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, fileLinkPeerPaths, hostFileOrigins)}`; -======= - const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null)}`; ->>>>>>> upstream/main + const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir, isStreaming ? (streamingBlocks ?? splitMarkdownBlocks(text) ?? [text]) : null, fileLinkPeerPaths, hostFileOrigins)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); const fileLinkPrefix = useFileLinkPrefix(fileLinkParentSuffixByPath); @@ -1035,20 +975,12 @@ function useChatMarkdownState( } return findAgentDirectoryMatch(workspaceRelativePath, agentRoots, searchRoot); }; -<<<<<<< origin/main const openFileInPanel = ( fileLinkMeta: MarkdownFileLinkMeta, panelPath: string, ...options: [OpenFileOptions?] ): OpenedSurface | Promise => { if (!threadRef) return null; - const openAt = (path: string) => - openedSync(rightPanelHostRef(threadRef), () => - useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line, ...options), - ); -======= - const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => { - if (!threadRef) return; // The panel reads relative paths from the thread's folder. A pull request body's `cwd` is the // checkout of its repository, which can be another folder. const shell = readThreadShell(threadRef); @@ -1058,16 +990,18 @@ function useChatMarkdownState( (project) => project.environmentId === environmentId && project.id === shell?.projectId, )?.workspaceRoot; const openAt = (path: string) => - useRightPanelStore - .getState() - .openFile( - threadRef, - cwd && panelRoot !== undefined && cwd !== panelRoot - ? resolveWorkspaceFilePath(path, cwd) - : path, - fileLinkMeta.line, - ); ->>>>>>> upstream/main + openedSync(rightPanelHostRef(threadRef), () => + useRightPanelStore + .getState() + .openFile( + threadRef, + cwd && panelRoot !== undefined && cwd !== panelRoot + ? resolveWorkspaceFilePath(path, cwd) + : path, + fileLinkMeta.line, + ...options, + ), + ); if ( fileLinkMeta.workspaceLookupPath === null || !cwd || @@ -2024,29 +1958,7 @@ const CHAT_MARKDOWN_COMPONENTS = { }, } satisfies MarkdownComponents; -<<<<<<< origin/main -const REMARK_MATH: Pluggable = [remarkMath, { singleDollarTextMath: true }]; -const FORK_REMARK_PLUGINS = [remarkWhiteboardLinks, remarkEndLinksAtCjkPunctuation]; -// Shared lists, so every message with the same options shares a processor and its cache. -const CHAT_MARKDOWN_REMARK_PLUGIN_SETS = { - plain: [...CHAT_MARKDOWN_REMARK_PLUGINS, ...FORK_REMARK_PLUGINS], - breaks: [...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, ...FORK_REMARK_PLUGINS], - math: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS, ...FORK_REMARK_PLUGINS], - mathBreaks: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, ...FORK_REMARK_PLUGINS], -} satisfies Record; -const ASSISTANT_MARKDOWN_REMARK_PLUGIN_SETS = { - plain: [...ASSISTANT_MARKDOWN_REMARK_PLUGINS, ...FORK_REMARK_PLUGINS], - breaks: [...ASSISTANT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, ...FORK_REMARK_PLUGINS], - math: [REMARK_MATH, ...ASSISTANT_MARKDOWN_REMARK_PLUGINS, ...FORK_REMARK_PLUGINS], - mathBreaks: [ - REMARK_MATH, - ...ASSISTANT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - ...FORK_REMARK_PLUGINS, - ], -} satisfies Record; -======= const markdownOptions = new WeakMap>(); ->>>>>>> upstream/main /** One options object per configuration, so equal messages share a renderer and its cache. */ function wordsOptions( @@ -2055,7 +1967,7 @@ function wordsOptions( ): WordsHastOptions { let byFlags = markdownOptions.get(extensions); if (!byFlags) markdownOptions.set(extensions, (byFlags = new Map())); - const key = `${+flags.math}${+flags.breaks}${+flags.escapeHtml}${+flags.insights}`; + const key = `${+flags.math}${+flags.breaks}${+flags.escapeHtml}${+flags.insights}${+!!flags.agentText}${+!!flags.boardLinks}${+!!flags.inline}`; let options = byFlags.get(key); if (!options) byFlags.set(key, (options = { ...flags, extensions })); return options; @@ -2236,36 +2148,15 @@ function ChatMarkdown({ const bindMarkdownRef = (node: HTMLElement | null) => { markdownRef.current = node; }; -<<<<<<< origin/main - const sharedRemarkPlugins = ( - assistantReply ? ASSISTANT_MARKDOWN_REMARK_PLUGIN_SETS : CHAT_MARKDOWN_REMARK_PLUGIN_SETS - )[ - componentState.mathEnabled - ? lineBreaks - ? "mathBreaks" - : "math" - : lineBreaks - ? "breaks" - : "plain" - ]; - // The incremental parser keeps per-instance state, so its output is not shared. - const uncachedPlugins = incrementalParsing; - const remarkPlugins = incrementalParsing - ? [...sharedRemarkPlugins, ...extraRemarkPlugins, createIncrementalMarkdownPlugin()] - : withExtraPlugins( - hasInsights - ? withExtraPlugins(INSIGHT_REMARK_PLUGINS, sharedRemarkPlugins) - : sharedRemarkPlugins, - extraRemarkPlugins, - ); -======= const markdown = wordsOptions(extensions, { math: componentState.mathEnabled, breaks: lineBreaks, escapeHtml: !parseRawHtml, insights: renderInsights && text.includes("★ Insight"), + agentText: assistantReply, + boardLinks: true, + inline, }); ->>>>>>> upstream/main const blocks = streamingBlocks ?? [text]; return ( diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 897a78932efe5..9bd09d45046eb 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -126,7 +126,7 @@ import { primaryServerKeybindingsAtom } from "~/state/server"; import { hasCommandForKeyDown } from "~/shortcuts/dispatcher"; import { basenameOfPath } from "~/pierre-icons"; import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon"; -import { postWhiteboardHover } from "../fork/whiteboard/markdown-whiteboard"; +import { postWhiteboardHover } from "../fork/whiteboard/boardChannel"; import { FileTagChipContent } from "./chat/FileTagChip"; import { SkillChipPopover, skillPopoverDescription } from "./chat/SkillInlineText"; import { AssistantCitationChip } from "./chat/AssistantCitationChip"; diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx index 1c26e54cf0375..c22e0d2f52927 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx @@ -268,7 +268,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( text={activeQuestion.question} cwd={cwd} threadRef={threadRef} - // Fork: selects the agent-text single-tilde list, so a question's "1~2" keeps its tilde. + // Fork: agent text, so a question's "1~2" keeps its tilde. assistantReply lineBreaks className={cn("pt-0.5 text-foreground/85", questionTextAlign)} diff --git a/apps/web/src/components/chat/MarkdownFileLink.tsx b/apps/web/src/components/chat/MarkdownFileLink.tsx index aa0e33330c29b..827469667f3b5 100644 --- a/apps/web/src/components/chat/MarkdownFileLink.tsx +++ b/apps/web/src/components/chat/MarkdownFileLink.tsx @@ -361,12 +361,24 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ const chip = hasPrimaryAction ? ( { + if (nativeDrag.draggable) nativeDrag.onDragStart(event); + else + startPanelLinkDrag( + event, + fileChipPanelLink(threadRef, panelPath, (path, options) => + onOpenInPanel(path, line, options), + ), + ); + }} kind={chipKind} dir="ltr" render={} + aria-label={labelPrefix === undefined ? undefined : `${labelPrefix}${label}`} className={MARKDOWN_FILE_LINK_CLASS_NAME} data-markdown-copy={copyMarkdown} onClick={(event) => { + if (leavesFileChipClickToBrowser(href, event)) return; event.preventDefault(); event.stopPropagation(); if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { @@ -388,6 +400,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ path={iconPath} environmentId={environmentId} label={label} + labelPrefix={labelPrefix} theme={theme} /> @@ -397,7 +410,7 @@ export const MarkdownFileLink = memo(function MarkdownFileLink({ kind={chipKind} dir="ltr" render={
    )} diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index 89db4e665e04a..9e9de82984f81 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -57,18 +57,6 @@ function resolveFinalAssistantTextForTurn( return finalAssistantText; } -<<<<<<< origin/main -const markdownPreviewParser = unified() - .use(remarkParse) - .use(remarkGfm, { singleTilde: false }) - .freeze(); - -const INLINE_PARENT_TYPES = new Set([ - "paragraph", - "heading", - "tableCell", - "emphasis", -======= // Elements whose children run together; every other element is separated by a space. const INLINE_PARENTS = new Set([ "p", @@ -81,7 +69,6 @@ const INLINE_PARENTS = new Set([ "td", "th", "em", ->>>>>>> upstream/main "strong", "del", "a", @@ -106,13 +93,15 @@ function markdownNodeText(node: Nodes): string { /** Markdown as one line of the text it renders, without markup or link targets. */ export function markdownPlainText(markdown: string): string { - return markdownNodeText(markdownTree(markdown)).replace(/\s+/g, " ").trim(); + return markdownNodeText(markdownTree(markdown, { singleTilde: false })) + .replace(/\s+/g, " ") + .trim(); } // The tooltip shows a few lines; bound parsing work for long messages and streaming responses. function markdownMinimapPreview(markdown: string | null) { if (markdown === null) return null; - const compact = markdownNodeText(markdownTree(markdown.slice(0, 1_500))) + const compact = markdownNodeText(markdownTree(markdown.slice(0, 1_500), { singleTilde: false })) .replace(/\s+/g, " ") .trim(); return compact.length > 0 ? compact : null; diff --git a/apps/web/src/components/composerContextPresentation.tsx b/apps/web/src/components/composerContextPresentation.tsx index 74c83df1005ab..4c629e002068d 100644 --- a/apps/web/src/components/composerContextPresentation.tsx +++ b/apps/web/src/components/composerContextPresentation.tsx @@ -1,6 +1,6 @@ import ChatMarkdown from "./ChatMarkdown"; import { isSvgAttachment } from "@t3tools/shared/image"; -import { CHAT_USER_MARKDOWN_REMARK_PLUGINS } from "@t3tools/shared/markdownPipeline"; +import { USER_TEXT_MARKDOWN } from "../fork/forkMarkdown"; import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview"; import type { ChatAttachment, @@ -431,7 +431,7 @@ function ComposerReviewCommentDetails({ comment }: { comment: ReviewCommentConte text={comment.text.trim()} cwd={undefined} // Fork: "1~2" keeps its tilde before sending, as in the user's message. - extraRemarkPlugins={CHAT_USER_MARKDOWN_REMARK_PLUGINS} + extensions={USER_TEXT_MARKDOWN} /> ) : null} {comment.diff.trim() ? ( diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 96c69e9330d94..e525dbf693e1e 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -123,12 +123,9 @@ import { FileSurfaceLoading, } from "./fileSurfaceChrome"; import SourceFilePreview from "./ReadOnlySourcePreview"; -<<<<<<< origin/main import { pathReadingKey, useFileReadingPosition } from "./fileReadingPosition"; -======= import LargeFilePreview from "./LargeFilePreview"; import { FULL_TEXT_MAX_BYTES } from "./largeTextProtocol"; ->>>>>>> upstream/main import { resolveCenteredFileLineScrollTop } from "./fileLineReveal"; import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation"; import { projectFileCacheKey } from "./fileContentRevision"; @@ -1382,15 +1379,10 @@ export default function FilePreviewPanel({ }); const revealHandled = revealLine === null || -<<<<<<< origin/main reading.renderedAllowed || (handledReveal?.path === relativePath && handledReveal.requestId === reading.revealKey); - const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled; -======= - (handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId); const markdownRenderable = isMarkdown && (file.data?.byteLength ?? 0) <= FULL_TEXT_MAX_BYTES; const renderMarkdown = markdownRenderable && renderMarkdownPreferred && revealHandled; ->>>>>>> upstream/main const renderMermaid = isMermaid && renderMermaidPreferred && revealHandled; const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled); const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled; diff --git a/apps/web/src/components/files/fileReadingPosition.browser.test.tsx b/apps/web/src/components/files/fileReadingPosition.browser.test.tsx index 6ebb2d514f522..a43c2f843ff09 100644 --- a/apps/web/src/components/files/fileReadingPosition.browser.test.tsx +++ b/apps/web/src/components/files/fileReadingPosition.browser.test.tsx @@ -53,6 +53,7 @@ import { csv, environmentId, holdIndexing, + LARGE_TEXT_BYTES, largeText, lines, ReadingPanel, @@ -144,63 +145,6 @@ describe("file reading position", () => { expect(reading.saved("a.ts", "source")).toEqual(saved); }); - it("returns rendered Markdown to the reader's block after a tab switch, clamped when shorter", async () => { - using reading = await readingSetup("rendered"); - const { panel, ref } = reading; - panel.openFile(ref, "b.ts"); - panel.openFile(ref, "doc.md"); - await using screen = await render(); - const viewport = () => - screen.container - .querySelector(".chat-markdown") - ?.closest('[data-slot="scroll-area-viewport"]'); - await vi.waitFor(() => expect(viewport()?.textContent).toContain("Paragraph 80.")); - await userEvent.wheel(viewport()!, { delta: { y: 1500 } }); - await vi.waitFor(() => expect(reading.saved("doc.md", "rendered")?.block).toBeGreaterThan(10)); - const wheeled = reading.saved("doc.md", "rendered")!.block!; - - // The custom scrollbar sits beside the viewport and moves it directly. - const scrollbar = screen.container.querySelector( - '[data-slot="scroll-area-scrollbar"]', - )!; - const track = scrollbar.getBoundingClientRect(); - await userEvent.click(scrollbar, { - position: { x: track.width / 2, y: track.height - 4 }, - }); - await vi.waitFor(() => - expect(reading.saved("doc.md", "rendered")?.block).toBeGreaterThan(wheeled), - ); - const before = viewport()!.scrollTop; - - await act(() => panel.activateSurface(ref, "file:b.ts")); - await vi.waitFor(() => expect(viewport()).toBeFalsy()); - await act(() => panel.activateSurface(ref, "file:doc.md")); - await vi.waitFor(() => expect(Math.abs(viewport()!.scrollTop - before)).toBeLessThanOrEqual(1)); - - await act(() => panel.activateSurface(ref, "file:b.ts")); - await vi.waitFor(() => expect(viewport()).toBeFalsy()); - const saved = reading.saved("doc.md", "rendered"); - const shorter = Array.from({ length: 30 }, (_, index) => `Paragraph ${index + 1}.`).join( - "\n\n", - ); - state.files["doc.md"] = { - relativePath: "doc.md", - contents: shorter, - byteLength: shorter.length, - truncated: false, - }; - await act(() => panel.activateSurface(ref, "file:doc.md")); - await vi.waitFor(() => { - const element = viewport()!; - expect(element.textContent).not.toContain("Paragraph 31."); - expect(element.scrollHeight).toBeGreaterThan(element.clientHeight); - expect(element.scrollTop).toBeGreaterThanOrEqual( - element.scrollHeight - element.clientHeight - 1, - ); - }); - expect(reading.saved("doc.md", "rendered")).toEqual(saved); - }); - it("returns a citation reopened with Reopen Closed View to the reader's place", async () => { using reading = await readingSetup("reopen-closed"); const { panel, ref } = reading; @@ -320,7 +264,7 @@ describe("large text and table rows keep the reader's place", () => { expect(reading.saved("table.csv", "rendered")).toEqual(saved); }); - it("keeps a text file's line when it grows past the 1 MB preview and when it shrinks back", async () => { + it("keeps a text file's line when it grows past the full-text read and when it shrinks back", async () => { using reading = await readingSetup("crossing"); const { panel, ref } = reading; const contents = lines(400); @@ -344,7 +288,7 @@ describe("large text and table rows keep the reader's place", () => { await act(() => panel.activateSurface(ref, "file:b.ts")); await vi.waitFor(() => view.expectLineInView(1, "beta_1")); reading.serve("app.log", contents); - state.files["app.log"] = { ...small, byteLength: 2_000_000, truncated: true }; + state.files["app.log"] = { ...small, byteLength: LARGE_TEXT_BYTES, truncated: true }; await act(() => panel.activateSurface(ref, "file:app.log")); await vi.waitFor(() => { rows.indexed(); @@ -418,8 +362,14 @@ describe("large text and table rows keep the reader's place", () => { await using screen = await render(); const rows = rowsView(screen.container); const view = sourceView(screen.container); - const status = () => screen.container.querySelector('[role="status"]')?.textContent ?? ""; - await vi.waitFor(() => expect(status()).toMatch(/600 lines.*Indexing/), COLD_WORKER); + // The worker has read all 600 rows; the status shows counts only once indexing ends. + const stillIndexing = () => { + expect(screen.container.querySelector("[aria-rowcount]")?.getAttribute("aria-rowcount")).toBe( + "600", + ); + expect(screen.container.querySelector('[role="status"]')?.textContent).toBe(""); + }; + await vi.waitFor(stillIndexing, COLD_WORKER); await rows.wheel(3000); await vi.waitFor(() => expect(rows.topRow()).toBeGreaterThan(80)); const top = rows.scroller()!.scrollTop; @@ -439,7 +389,7 @@ describe("large text and table rows keep the reader's place", () => { indexing.hold(); await act(() => panel.activateSurface(ref, "file:big.log")); // A click that scrolls nothing while it indexes leaves the restore to land. - await vi.waitFor(() => expect(status()).toMatch(/600 lines.*Indexing/), COLD_WORKER); + await vi.waitFor(stillIndexing, COLD_WORKER); await userEvent.click(rows.scroller()!); indexing.release(); await vi.waitFor(() => { diff --git a/apps/web/src/components/files/fileReadingTestKit.tsx b/apps/web/src/components/files/fileReadingTestKit.tsx index 92f72db6377f3..123cc7224953b 100644 --- a/apps/web/src/components/files/fileReadingTestKit.tsx +++ b/apps/web/src/components/files/fileReadingTestKit.tsx @@ -16,6 +16,7 @@ import appCss from "~/index.css?inline"; import { selectActiveRightPanelSurface, useRightPanelStore } from "~/rightPanelStore"; import FilePreviewPanel from "./FilePreviewPanel"; +import { FULL_TEXT_MAX_BYTES } from "./largeTextProtocol"; import { resetState, state } from "./fileReadingTestMocks"; export { state }; @@ -279,6 +280,9 @@ export function lines(count: number) { return Array.from({ length: count }, (_, index) => `log line ${index + 1}`).join("\n"); } +/** Past the full-text read, so the worker-backed rows viewer shows the file. */ +export const LARGE_TEXT_BYTES = FULL_TEXT_MAX_BYTES + 1; + /** A large text file the panel streams from its asset URL. */ export function largeText( reading: { readonly serve: (path: string, contents: string) => void }, @@ -286,7 +290,12 @@ export function largeText( contents: string, ) { reading.serve(path, contents); - state.files[path] = { relativePath: path, contents, byteLength: 2_000_000, truncated: true }; + state.files[path] = { + relativePath: path, + contents, + byteLength: LARGE_TEXT_BYTES, + truncated: true, + }; } /** diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index b3b122729a080..0d615600bd03c 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -168,12 +168,9 @@ describe("searchSettings", () => { "auto-settle-merged-threads", "days-before-auto-settle", "linked-environments", -<<<<<<< origin/main "worktree-reflink", "right-panel-menu", -======= "agent-feedback", ->>>>>>> upstream/main ]); expect(available.map((item) => item.id).filter((id) => gatedIds.has(id))).toEqual([]); }); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index c6ad6d9671d9d..6acefaf3218c3 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -74,11 +74,8 @@ export interface SettingsSearchItem { readonly managedTunnelOnly?: boolean; readonly peerLinksOnly?: boolean; readonly fastWorktreeCheckoutOnly?: boolean; -<<<<<<< origin/main readonly reflinkWorktreesOnly?: boolean; -======= readonly agentFeedbackOnly?: boolean; ->>>>>>> upstream/main readonly textGeneratorsOnly?: boolean; readonly rightPanelMenuOnly?: boolean; readonly secondary?: boolean; @@ -96,11 +93,8 @@ export interface SettingsSearchAvailability { readonly managedTunnelActive?: boolean; readonly hasPeerLinkHost?: boolean; readonly hasFastWorktreeCheckoutEnvironment?: boolean; -<<<<<<< origin/main readonly hasReflinkWorktreesEnvironment?: boolean; -======= readonly hasAgentFeedbackEnvironment?: boolean; ->>>>>>> upstream/main /** An environment without a provider allow-list, which hides text generators. */ readonly hasTextGeneratorsEnvironment?: boolean; readonly hasPrimaryEnvironment?: boolean; @@ -1727,11 +1721,8 @@ export function filterAvailableSettingsSearchItems( (!item.peerLinksOnly || availability.hasPeerLinkHost === true) && (!item.fastWorktreeCheckoutOnly || availability.hasFastWorktreeCheckoutEnvironment === true) && -<<<<<<< origin/main (!item.reflinkWorktreesOnly || availability.hasReflinkWorktreesEnvironment === true) && -======= (!item.agentFeedbackOnly || availability.hasAgentFeedbackEnvironment === true) && ->>>>>>> upstream/main (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true) && (!item.secretProvidersOnly || availability.hasSecretProvidersEnvironment === true) && (!item.rightPanelMenuOnly || availability.hasRightPanelMenu === true), diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts index f366b0e92b861..c5fb1aaa7cdc4 100644 --- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts +++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts @@ -46,19 +46,17 @@ export function useAvailableSettingsSearchItems() { environment.connection.phase === "connected" && environment.serverConfig?.environment.capabilities.fastWorktreeCheckout === true, ) === true; -<<<<<<< origin/main const hasReflinkWorktreesEnvironment = environments.some( (environment) => environment.connection.phase === "connected" && environment.serverConfig?.environment.capabilities.reflinkWorktrees === true, -======= + ) === true; const hasAgentFeedbackEnvironment = environments.some( (environment) => environment.connection.phase === "connected" && environment.serverConfig?.environment.capabilities.agentFeedback === true, ->>>>>>> upstream/main ) === true; const hasTextGeneratorsEnvironment = environments.some( @@ -99,11 +97,8 @@ export function useAvailableSettingsSearchItems() { managedTunnelActive, hasPeerLinkHost, hasFastWorktreeCheckoutEnvironment, -<<<<<<< origin/main hasReflinkWorktreesEnvironment, -======= hasAgentFeedbackEnvironment, ->>>>>>> upstream/main hasTextGeneratorsEnvironment, hasPrimaryEnvironment: primaryEnvironmentId !== null, hasSecretProvidersEnvironment, diff --git a/apps/web/src/components/workflows/WorkflowRunFeed.tsx b/apps/web/src/components/workflows/WorkflowRunFeed.tsx index d77b54d8dcc11..003603a4cfde9 100644 --- a/apps/web/src/components/workflows/WorkflowRunFeed.tsx +++ b/apps/web/src/components/workflows/WorkflowRunFeed.tsx @@ -1718,6 +1718,8 @@ function WorkflowAgentCard({ text={start !== null && !all ? start : summary.said} cwd={undefined} className="text-sm" + // Fork: the agent's reply, so a single "~" stays text as in its thread. + assistantReply /> {start !== null ? (