From 9b352a04defad2ec5b1af7245a707f2361265d55 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 10 Nov 2026 07:18:43 -0800 Subject: [PATCH 001/170] perf(server): MCP tool calls no longer read the caller's whole thread (#33295) Co-authored-by: Claude Opus 5.5 --- .../src/mcp/OrchestratorMcpService.test.ts | 21 ++- apps/server/src/mcp/OrchestratorMcpService.ts | 143 ++++++------------ ...OrchestratorMcpToolkit.integration.test.ts | 85 ++++++++++- .../DelegatedCompletionDelivery.test.ts | 67 ++++++++ .../src/orchestration-v2/Orchestrator.ts | 87 +++++------ .../orchestration-v2/ProjectionStore.test.ts | 47 ++++++ .../src/orchestration-v2/ProjectionStore.ts | 29 ++-- .../ThreadManagementService.ts | 14 +- 8 files changed, 316 insertions(+), 177 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index df13d037005a..f26397040f0f 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -91,15 +91,6 @@ describe("OrchestratorMcpService", () => { const parentProjection = { thread: { id: parentThreadId }, runs: [], - contextTransfers: [ - { - id: resultTransferId, - type: "subagent_result", - sourceThreadId: childThreadId, - targetThreadId: parentThreadId, - sourcePoint: { runId: childRunId }, - }, - ], subagents: [ { id: taskId, @@ -131,7 +122,15 @@ describe("OrchestratorMcpService", () => { completedAt: DateTime.makeUnsafe("2026-10-03T10:05:00Z"), }, ], - contextTransfers: [], + contextTransfers: [ + { + id: resultTransferId, + type: "subagent_result", + sourceThreadId: childThreadId, + targetThreadId: parentThreadId, + sourcePoint: { runId: childRunId }, + }, + ], messages: [ { id: MessageId.make("message:mcp-ack-result"), @@ -160,6 +159,7 @@ describe("OrchestratorMcpService", () => { return hasNestedWork ? { ...childProjection, + contextTransfers: [], subagents: [ { ...parentProjection.subagents[0]!, status: "running" as const }, ], @@ -169,7 +169,6 @@ describe("OrchestratorMcpService", () => { const snapshot = hasNestedWork ? { ...parentProjection, - contextTransfers: [], subagents: parentProjection.subagents.map((task) => ({ ...task, result: null, diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index a1425d56e8e5..066722ea6625 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -583,8 +583,9 @@ function directAppOwnedChildTasks( ); } +// The child's transfers include the results it sent, so the parent's transfers are never read. function taskResultTransfer( - parent: Pick, + parentThreadId: ThreadId, child: Pick, task: OrchestrationV2Subagent, ) { @@ -599,18 +600,18 @@ function taskResultTransfer( .map((run) => run.id), ); if (originalRun !== undefined) resultRunIds.add(originalRun.id); - return parent.contextTransfers.find( + return child.contextTransfers.find( (transfer) => transfer.type === "subagent_result" && transfer.sourceThreadId === task.childThreadId && - transfer.targetThreadId === parent.thread.id && + transfer.targetThreadId === parentThreadId && ((transfer.sourcePoint.runId !== undefined && resultRunIds.has(transfer.sourcePoint.runId)) || (transfer.sourcePoint.runId === undefined && originalRun?.delegatedTaskId === undefined)), ); } function pageIncludesTerminalTaskResult(input: { - readonly parent: Pick; + readonly parentThreadId: ThreadId; readonly page: ReadonlyArray; readonly task: OrchestrationV2Subagent; readonly target: Pick< @@ -619,7 +620,7 @@ function pageIncludesTerminalTaskResult(input: { >; readonly maxChars: number; }): boolean { - const transfer = taskResultTransfer(input.parent, input.target, input.task); + const transfer = taskResultTransfer(input.parentThreadId, input.target, input.task); if (transfer === undefined) return false; const run = transfer.sourcePoint.runId === undefined @@ -1092,20 +1093,11 @@ const make = Effect.gen(function* () { ), ); - const loadProjection = (threadId: ThreadId, includeUserMessages = true) => - loadThreadRecords( - threadId, - [ - "runs", - "messages", - "providerThreads", - "providerTurns", - "runtimeRequests", - "contextTransfers", - "turnItems", - ], - { turnItemTypes: [], messageRoles: includeUserMessages ? ["user"] : [] }, - ); + // Runs on every MCP call, and long threads hold thousands of records; callers need only active runs. + const loadCallerRecords = (threadId: ThreadId, fields: ReadonlyArray) => + loadThreadRecords(threadId, fields, { + runStatuses: ThreadManagementService.ACTIVE_RUN_STATUSES, + }); // A dispatcher thread holds thousands of tasks, each with its full prompt; read only the ones named. const loadTasks = (threadId: ThreadId, taskIds: ReadonlyArray) => @@ -1116,43 +1108,9 @@ const make = Effect.gen(function* () { ), ); - // Task waits read on every wake of a parent that may hold thousands of - // tasks, so they read only the task they watch and what its status needs. - const loadTaskParent = (threadId: ThreadId) => - threadManagement - .getThreadRecords(threadId, ["runs", "contextTransfers"]) - .pipe( - Effect.mapError((error) => - failure( - "orchestration_error", - `Unable to read thread ${threadId}: ${errorMessage(error)}`, - ), - ), - ); - - const loadProjectThread = ( - projectId: OrchestrationV2ThreadProjection["thread"]["projectId"], - threadId: ThreadId, - ) => - threadManagement - .getProjectThreadRecords( - { projectId, threadId }, - [ - "runs", - "messages", - "subagents", - "providerThreads", - "providerTurns", - "runtimeRequests", - "contextTransfers", - "turnItems", - ], - { turnItemTypes: [], messageRoles: ["user"] }, - ) - .pipe(Effect.mapError(threadManagementFailure)); - - const loadCaller = Effect.fn("OrchestratorMcpService.loadCaller")(function* ( + const loadCaller = Effect.fn("OrchestratorMcpService.loadCaller")(function* ( scope: McpInvocationScope, + fields: ReadonlyArray, ) { yield* requireCapability(scope); if (scope.thread === undefined) { @@ -1161,8 +1119,7 @@ const make = Effect.gen(function* () { limits: clientModeCeiling(scope.client), } as const; } - // No loadCaller consumer reads the caller's own prompts. - const parent = yield* loadProjection(scope.thread.threadId, false); + const parent = yield* loadCallerRecords(scope.thread.threadId, fields); return { parent, limits: { @@ -1178,7 +1135,7 @@ const make = Effect.gen(function* () { ) { yield* requireCapability(scope); const threadScope = yield* requireThreadScope(scope, operation); - const parent = yield* loadProjection(threadScope.thread.threadId); + const parent = yield* loadCallerRecords(threadScope.thread.threadId, ["runs"]); return { scope: threadScope, parent } as const; }); @@ -1199,7 +1156,6 @@ const make = Effect.gen(function* () { const loadTargetThread = Effect.fn("OrchestratorMcpService.loadTargetThread")(function* ( threadId: ThreadId, - includeHistory = true, ) { const shell = yield* threadManagement .getThreadShell(threadId) @@ -1207,24 +1163,21 @@ const make = Effect.gen(function* () { if (shell === null || shell.deletedAt !== null) { return yield* threadNotFound(threadManagement, threadId, `Thread ${threadId} was not found.`); } - // Native wait owns its history reads; keep legacy import and project validation here. - return yield* includeHistory - ? loadProjectThread(shell.projectId, threadId) - : threadManagement - .getProjectThreadRecords({ projectId: shell.projectId, threadId }, []) - .pipe(Effect.mapError(threadManagementFailure)); + // Keeps legacy import and project validation; callers read only the thread row. + return yield* threadManagement + .getProjectThreadRecords({ projectId: shell.projectId, threadId }, []) + .pipe(Effect.mapError(threadManagementFailure)); }); - const loadScopedThread = Effect.fn("OrchestratorMcpService.loadScopedThread")(function* ( - scope: McpInvocationScope, - threadId: ThreadId, - includeHistory = true, - ) { - const caller = yield* loadCaller(scope); - const target = + const loadScopedThread = Effect.fn("OrchestratorMcpService.loadScopedThread")(function* < + K extends "runs", + >(scope: McpInvocationScope, threadId: ThreadId, callerFields: ReadonlyArray) { + const caller = yield* loadCaller(scope, callerFields); + // Only the thread row: the caller's own record holds just its active runs. + const target: Pick = caller.parent !== undefined && threadId === caller.parent.thread.id ? caller.parent - : yield* loadTargetThread(threadId, includeHistory); + : yield* loadTargetThread(threadId); return { ...caller, target } as const; }); @@ -1278,7 +1231,7 @@ const make = Effect.gen(function* () { scope: McpInvocationScope, threadId: ThreadId, ) { - const { parent } = yield* loadCaller(scope); + const { parent } = yield* loadCaller(scope, []); const shell = yield* threadManagement .getThreadShell(threadId) .pipe(Effect.mapError(threadManagementFailure)); @@ -1514,7 +1467,6 @@ const make = Effect.gen(function* () { if (task.childThreadId === null) { return yield* readRemoteTask(scope, task, waitTimedOut, acknowledgeTerminal); } - const parentProjection = yield* loadTaskParent(scope.thread.threadId); const childControls = yield* threadManagement .getThreadRecords( task.childThreadId, @@ -1594,7 +1546,7 @@ const make = Effect.gen(function* () { : taskResultRun !== undefined && isTerminalTaskStatus(status) ? subagentResultForRun(childProjection, taskResultRun).text : null; - const resultTransfers = parentProjection.contextTransfers.filter( + const resultTransfers = childControls.contextTransfers.filter( (transfer) => transfer.type === "subagent_result" && transfer.sourceThreadId === task.childThreadId && @@ -1608,7 +1560,7 @@ const make = Effect.gen(function* () { ? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined) : undefined) ?? null); - const resultTransfer = taskResultTransfer(parentProjection, childProjection, task) ?? null; + const resultTransfer = taskResultTransfer(scope.thread.threadId, childProjection, task) ?? null; const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun); const latestTerminalSummary = canExposeTaskRunResult(terminalRun) ? terminalRun.id === childRun?.id @@ -1677,6 +1629,7 @@ const make = Effect.gen(function* () { task.completionDelivery?.state !== "acknowledged" && task.completionDelivery?.state !== "disposed" ) { + const parentProjection = yield* loadCallerRecords(scope.thread.threadId, ["runs"]); const observingRun = ThreadManagementService.latestActiveRun({ runs: parentProjection.runs.filter( (run) => run.providerInstanceId === scope.thread.providerInstanceId, @@ -1762,17 +1715,7 @@ const make = Effect.gen(function* () { task.completionDelivery?.state !== "acknowledged" && task.completionDelivery?.state !== "disposed" ) { - const parentThreadId = scope.thread.threadId; - const parentProjection = yield* threadManagement - .getThreadRecords(parentThreadId, ["runs"]) - .pipe( - Effect.mapError((error) => - failure( - "orchestration_error", - `Unable to read thread ${parentThreadId}: ${errorMessage(error)}`, - ), - ), - ); + const parentProjection = yield* loadCallerRecords(scope.thread.threadId, ["runs"]); const observingRun = ThreadManagementService.latestActiveRun({ runs: parentProjection.runs.filter( (run) => run.providerInstanceId === scope.thread.providerInstanceId, @@ -2015,7 +1958,7 @@ const make = Effect.gen(function* () { return OrchestratorMcpService.of({ scheduleTask: Effect.fn("OrchestratorMcpService.scheduleTask")(function* (scope, input) { - const { parent, limits } = yield* loadCaller(scope); + const { parent, limits } = yield* loadCaller(scope, ["runs"]); const projectId = yield* resolveProjectTarget(parent, input.projectId); yield* assertLiveCallerForOtherProject(scope, parent, projectId); const project = yield* requireProject(projectId); @@ -2076,7 +2019,7 @@ const make = Effect.gen(function* () { }), listScheduledTasks: Effect.fn("OrchestratorMcpService.listScheduledTasks")( function* (scope, input) { - const { parent, limits } = yield* loadCaller(scope); + const { parent, limits } = yield* loadCaller(scope, ["runs"]); const projectId = input.projectId ?? parent?.thread.projectId; const { tasks } = yield* scheduledTasks .list() @@ -2095,7 +2038,7 @@ const make = Effect.gen(function* () { ), updateScheduledTask: Effect.fn("OrchestratorMcpService.updateScheduledTask")( function* (scope, input) { - const { parent, limits } = yield* loadCaller(scope); + const { parent, limits } = yield* loadCaller(scope, ["runs"]); const existing = yield* loadScheduledTask(input.scheduledTaskId, limits); yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId); if ( @@ -2171,7 +2114,7 @@ const make = Effect.gen(function* () { ), deleteScheduledTask: Effect.fn("OrchestratorMcpService.deleteScheduledTask")( function* (scope, input) { - const { parent, limits } = yield* loadCaller(scope); + const { parent, limits } = yield* loadCaller(scope, ["runs"]); const existing = yield* loadScheduledTask(input.scheduledTaskId, limits); yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId); yield* scheduledTasks @@ -2337,7 +2280,7 @@ const make = Effect.gen(function* () { }), capabilities: Effect.fn("OrchestratorMcpService.capabilities")(function* (scope, input = {}) { - const { parent, limits } = yield* loadCaller(scope); + const { parent, limits } = yield* loadCaller(scope, []); const providers = yield* loadProviders; const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds(); const settings = yield* serverSettings.getSettings.pipe( @@ -2968,7 +2911,7 @@ const make = Effect.gen(function* () { ), ); } - const projection = yield* loadProjection(threadId); + const projection = yield* loadThreadRecords(threadId, ["runs"]); const run = projection.runs.at(-1); yield* threadManagement .dispatch({ @@ -3014,7 +2957,7 @@ const make = Effect.gen(function* () { }, ), listThreads: Effect.fn("OrchestratorMcpService.listThreads")(function* (scope, input) { - const { parent } = yield* loadCaller(scope); + const { parent } = yield* loadCaller(scope, []); const projectId = input.allProjects ? null : yield* resolveProjectTarget(parent, input.projectId); @@ -3118,7 +3061,7 @@ const make = Effect.gen(function* () { (input.textOffset ?? 0) === 0 ) { for (const task of tasks) { - const transfer = taskResultTransfer(parent, target, task); + const transfer = taskResultTransfer(parent.thread.id, target, task); const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id; const resultRunIds = resultRunId === undefined ? [] : [resultRunId]; const resultRecords = yield* threadManagement @@ -3131,7 +3074,7 @@ const make = Effect.gen(function* () { .pipe(Effect.mapError(threadManagementFailure)); if ( pageIncludesTerminalTaskResult({ - parent, + parentThreadId: parent.thread.id, page, task, target: { ...target, ...resultRecords }, @@ -3173,7 +3116,7 @@ const make = Effect.gen(function* () { } satisfies OrchestratorMcpThreadReadResult; }), sendToThread: Effect.fn("OrchestratorMcpService.sendToThread")(function* (scope, input) { - const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId); + const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId, ["runs"]); yield* assertLiveCallerForOtherThread(scope, parent, target); yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode); yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode); @@ -3224,7 +3167,7 @@ const make = Effect.gen(function* () { } satisfies OrchestratorMcpThreadSendResult; }), waitForThread: Effect.fn("OrchestratorMcpService.waitForThread")(function* (scope, input) { - const { parent, target } = yield* loadScopedThread(scope, input.threadId, false); + const { parent, target } = yield* loadScopedThread(scope, input.threadId, []); const result = yield* threadManagement .waitForThread({ projectId: target.thread.projectId, @@ -3274,7 +3217,7 @@ const make = Effect.gen(function* () { } satisfies OrchestratorMcpThreadWaitResult; }), interruptThread: Effect.fn("OrchestratorMcpService.interruptThread")(function* (scope, input) { - const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId); + const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId, ["runs"]); yield* assertLiveCallerForOtherThread(scope, parent, target); yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode); yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode); diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 5ec8dfd49a17..bbeac142dfeb 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -216,13 +216,34 @@ describe("orchestrator MCP toolkit", () => { }, CodexOrchestratorReplayHarness, ); + // SQL spans carry no bound parameters, so this records which thread each tool read. + const threadRecordReads: Array<{ + readonly threadId: ThreadId; + readonly fields: ReadonlyArray; + }> = []; const layerOrchestration = Layer.merge( layerOrchestrator, - ThreadManagementService.layer.pipe( - Layer.provide(layerOrchestrator), - Layer.provide(ServerSettings.layerTest()), + Layer.effect( + ThreadManagementService.ThreadManagementService, + Effect.gen(function* () { + const service = yield* ThreadManagementService.ThreadManagementService; + return ThreadManagementService.ThreadManagementService.of({ + ...service, + getThreadRecords: (threadId, fields, filter) => + Effect.sync(() => threadRecordReads.push({ threadId, fields })).pipe( + Effect.andThen(service.getThreadRecords(threadId, fields, filter)), + ), + }); + }), + ).pipe( Layer.provide( - CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), + ThreadManagementService.layer.pipe( + Layer.provide(layerOrchestrator), + Layer.provide(ServerSettings.layerTest()), + Layer.provide( + CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), + ), + ), ), ), ); @@ -603,6 +624,9 @@ describe("orchestrator MCP toolkit", () => { ); const transferReads: Array = []; const messageReads: Array = []; + const runReads: Array = []; + const projectionTableReads: Array = []; + const acknowledgementReads: Array = []; const tracer = Tracer.make({ span(options) { const span = new Tracer.NativeSpan(options); @@ -611,11 +635,29 @@ describe("orchestrator MCP toolkit", () => { end(endTime, exit); const query = span.attributes.get("db.query.text"); if (typeof query !== "string") return; + let parent = Option.getOrUndefined(span.parent); + while (parent?._tag === "Span") { + if ( + parent.name === "Orchestrator.dispatchDelegatedTaskCompletionDeliveryResolution" + ) { + acknowledgementReads.push(query); + break; + } + parent = Option.getOrUndefined(parent.parent); + } + for (const [, table] of query.matchAll( + /FROM orchestration_v2_projection_(\w+)/gi, + )) { + projectionTableReads.push(table!); + } if ( /SELECT[\s\S]*FROM orchestration_v2_projection_context_transfers/i.test(query) ) { transferReads.push(query); } + if (/SELECT\s+payload_json\s+FROM orchestration_v2_projection_runs/i.test(query)) { + runReads.push(query); + } if ( /SELECT\s+payload_json\s+FROM orchestration_v2_projection_messages/i.test(query) ) { @@ -687,6 +729,18 @@ describe("orchestrator MCP toolkit", () => { expect(read.isError).not.toBe(true); expect(transferReads.length).toBeGreaterThan(0); expect(read.structuredContent).toEqual(parentlessRead.structuredContent); + // The acknowledgement reads the task and its spawning run by id, not the parent's history. + expect(acknowledgementReads.length).toBeGreaterThan(0); + expect( + acknowledgementReads.filter( + (query) => + /FROM orchestration_v2_projection_(nodes|run_attempts)\b/.test(query) || + (/FROM orchestration_v2_projection_runs\b/.test(query) && + !query.includes("AND run_id IN")) || + (/FROM orchestration_v2_projection_subagents\b/.test(query) && + !query.includes("AND subagent_id IN")), + ), + ).toEqual([]); const afterRead = yield* orchestrator.getThreadProjection(parentThreadId); expect( afterRead.subagents.find((task) => task.id === queuedFollowup.taskId) @@ -694,11 +748,34 @@ describe("orchestrator MCP toolkit", () => { ).toBe("acknowledged"); const messageReadsBeforeCapabilities = messageReads.length; + const tableReadsBeforeCapabilities = projectionTableReads.length; const capabilities = yield* invoke("orchestrator_capabilities", {}).pipe( Effect.withTracer(tracer), ); expect(capabilities.isError).not.toBe(true); expect(messageReads).toHaveLength(messageReadsBeforeCapabilities); + // The caller check reads only the thread row, never its history. + expect(new Set(projectionTableReads.slice(tableReadsBeforeCapabilities))).toEqual( + new Set(["threads"]), + ); + const runReadsBeforeStatus = runReads.length; + const transferReadsBeforeStatus = transferReads.length; + const threadRecordReadsBeforeStatus = threadRecordReads.length; + const statusAgain = yield* invoke("task_status", { taskId: delegated.taskId }).pipe( + Effect.withTracer(tracer), + ); + expect(statusAgain.isError).not.toBe(true); + // A task wait reads result transfers and runs from the child; the parent's stay unread. + expect(runReads).toHaveLength(runReadsBeforeStatus + 1); + expect(transferReads).toHaveLength(transferReadsBeforeStatus + 1); + expect( + threadRecordReads + .slice(threadRecordReadsBeforeStatus) + .filter( + ({ fields }) => fields.includes("runs") || fields.includes("contextTransfers"), + ) + .map(({ threadId }) => threadId), + ).toEqual([delegated.childThreadId]); }).pipe(Effect.provide(layerTest)); }), ), diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 7bc7ef37d42d..5cabb1c36372 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -1055,6 +1055,73 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => { }), ); + it.effect("acknowledging a queued wake's results rewrites it, then cancels it", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("queued-wake-ack-parent"); + const runId = RunId.make("queued-wake-ack-origin"); + const taskId = NodeId.make("queued-wake-ack-first"); + const siblingId = NodeId.make("queued-wake-ack-sibling"); + yield* seedParentWithTerminalTask({ + threadId, + projectId: ProjectId.make("queued-wake-ack-project"), + runId, + rootNodeId: NodeId.make("queued-wake-ack-root"), + taskId, + deliveryState: "claimed", + deliveryTaskIds: [taskId, siblingId], + siblingTasks: [{ id: siblingId, deliveryState: "claimed" }], + completionWake: "always", + now, + }); + const delivery = (yield* orchestrator.getThreadProjection(threadId)).runs[0]! + .delegatedCompletion!.delivery!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "server", + commandId: CommandId.make("queued-wake-ack-wake"), + threadId, + messageId: delivery.messageId, + text: "Delegated tasks completed", + attachments: [], + modelSelection, + dispatchMode: { type: "queue_after_active" }, + delegatedCompletion: { + parentRunId: runId, + generation: delivery.generation, + taskIds: delivery.taskIds, + }, + }); + const acknowledge = (id: NodeId) => + orchestrator.dispatch({ + type: "delegated_task.completion-delivery.acknowledge", + commandId: CommandId.make(`queued-wake-ack:${id}`), + parentThreadId: threadId, + taskId: id, + observedByRunId: runId, + }); + + yield* acknowledge(taskId); + const rewritten = yield* orchestrator.getThreadProjection(threadId); + const wake = rewritten.runs.find((run) => run.userMessageId === delivery.messageId)!; + assert.equal(wake.status, "queued"); + const message = rewritten.messages.find((row) => row.id === delivery.messageId); + assert.deepEqual(message?.delegatedCompletion?.taskIds, [siblingId]); + assert.equal(message?.text, `Delegated task ${siblingId} [completed]:\nchild finished`); + + yield* acknowledge(siblingId); + const cancelled = yield* orchestrator.getThreadProjection(threadId); + assert.equal(cancelled.runs.find((run) => run.id === wake.id)?.status, "cancelled"); + assert.equal( + cancelled.nodes.find((node) => node.id === wake.rootNodeId)?.status, + "cancelled", + ); + assert.isNull(cancelled.runs.find((run) => run.id === runId)?.delegatedCompletion?.delivery); + }), + ); + it.effect.each([ { command: "acknowledge", before: "running", after: "failed", capture: false }, { command: "acknowledge", before: "waiting", after: "completed", capture: true }, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index e95fb6ec4865..859cc36e2e9b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -2783,21 +2783,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio >, events: Ref.Ref>, ) { - const projection = yield* projectionStore - .getThreadRecords( - command.parentThreadId, - ["subagents", "runs", "nodes", "attempts", "turnItems"], - { turnItemTypes: [] }, - ) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProjectionError({ - threadId: command.parentThreadId, - cause, - }), - ), - ); + const projection = yield* loadProjectionForCommand(command, ["subagents"], { + subagentIds: [command.taskId], + }); const task = projection.subagents.find( (candidate) => candidate.id === command.taskId && candidate.origin === "app_owned", ); @@ -2814,6 +2802,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : "disposed"; const now = yield* DateTime.now; const emitEvent = emit(events, command); + const { + runs: [parentRun], + } = yield* loadProjectionForCommand(command, ["runs"], { + runIds: task.runId === null ? [] : [task.runId], + }); // A late wait can arrive after finalization held the result for its still-live spawning run. if (isUnobservedAcknowledgement(command)) { if ( @@ -2821,23 +2814,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio task.completionDelivery?.state !== "pending" ) return; - const parentRun = projection.runs.find((run) => run.id === task.runId); if (parentRun !== undefined && isLiveRun(parentRun)) return; - const records = yield* projectionStore - .getThreadRecords(command.parentThreadId, ["messages", "providerTurns"], { - messageRoles: ["user"], - }) - .pipe( - Effect.mapError( - (cause) => - new OrchestratorProjectionError({ - threadId: command.parentThreadId, - cause, - }), - ), - ); + const records = yield* loadProjectionForCommand( + command, + ["runs", "subagents", "messages", "providerTurns"], + { messageRoles: ["user"] }, + ); const plan = yield* planDelegatedCompletionDelivery({ - parentProjection: { ...projection, ...records }, + parentProjection: records, parentRun, task, updatedTask: task, @@ -2907,10 +2891,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: updatedTask, }); - const parentRun = - task.runId === null - ? undefined - : projection.runs.find((candidate) => candidate.id === task.runId); const cohort = parentRun?.delegatedCompletion; const delivery = cohort?.delivery; if ( @@ -2925,17 +2905,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return; } - const { messages } = yield* projectionStore - .getThreadRecords(command.parentThreadId, ["messages"], { - messageRoles: ["user"], - messageIds: [delivery.messageId], - }) - .pipe( - Effect.mapError( - (cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }), - ), - ); - const deliveryProjection = { ...projection, messages }; + const { messages } = yield* loadProjectionForCommand(command, ["messages"], { + messageRoles: ["user"], + messageIds: [delivery.messageId], + }); + const deliveryRunId = completionDeliveryMessage({ messages }, delivery)?.runId ?? null; + const { runs } = yield* loadProjectionForCommand(command, ["runs"], { + runIds: deliveryRunId === null ? [] : [deliveryRunId], + }); + const deliveryProjection = { messages, runs }; const remainingTaskIds = delivery.taskIds.filter((taskId) => taskId !== task.id); const deliveryRun = completionDeliveryRun(deliveryProjection, delivery); const clearDelivery = @@ -2965,10 +2943,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (deliveryRun?.status === "queued") { if (remainingTaskIds.length === 0) { + const rootNodeFilter = { + nodeIds: deliveryRun.rootNodeId === null ? [] : [deliveryRun.rootNodeId], + }; yield* emitQueuedRunCancellation({ command, events, - projection, + // Attempts have no id filter; a wake that never started has no attempt to cancel. + projection: + deliveryRun.activeAttemptId === null + ? { + attempts: [], + ...(yield* loadProjectionForCommand(command, ["nodes"], rootNodeFilter)), + } + : yield* loadProjectionForCommand(command, ["nodes", "attempts"], rootNodeFilter), run: deliveryRun, now, }); @@ -2976,6 +2964,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } const message = completionDeliveryMessage(deliveryProjection, delivery); if (message !== undefined) { + const { subagents: remainingTasks } = yield* loadProjectionForCommand( + command, + ["subagents"], + { subagentIds: remainingTaskIds }, + ); yield* emitEvent({ type: "message.updated", threadId: command.parentThreadId, @@ -2985,7 +2978,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: { ...message, - text: delegatedCompletionWakeDetail(remainingTaskIds, projection.subagents), + text: delegatedCompletionWakeDetail(remainingTaskIds, remainingTasks), delegatedCompletion: { parentRunId: parentRun.id, generation: delivery.generation, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 0721c8212ebe..de54a97ebebf 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -694,6 +694,53 @@ it.effect("idle compaction filters keep the latest run, live work and the newest records.runs.map((run) => run.id), ["run:idle-compaction:rolled-back", "run:idle-compaction:4"], ); + const { statements, tracer } = traceSqlStatements(); + const statusOnly = yield* store + .getThreadRecords(threadId, ["runs"], { + runStatuses: ["preparing", "starting", "running", "rolled_back"], + }) + .pipe(Effect.withTracer(tracer)); + assert.deepEqual( + statusOnly.runs.map((run) => run.id), + ["run:idle-compaction:rolled-back"], + ); + const runQuery = statements.find((statement) => + statement.includes("FROM orchestration_v2_projection_runs"), + ); + assert.isDefined(runQuery); + const sql = yield* SqlClient.SqlClient; + // Read only the matching runs, not every run in ordinal order. + const runPlan = (yield* sql.unsafe<{ readonly detail: string }>( + `EXPLAIN QUERY PLAN ${runQuery}`, + )) + .map((row) => row.detail) + .join("\n"); + assert.notInclude(runPlan, "orchestration_v2_projection_runs_thread_ordinal_idx"); + assert.match(runPlan, /SEARCH orchestration_v2_projection_runs USING INDEX \w*status\w*/); + // An id filter reads by primary key, not every row of the thread. + const byId = traceSqlStatements(); + const found = yield* store + .getThreadRecords(threadId, ["runs", "nodes", "subagents", "messages"], { + runIds: [RunId.make("run:idle-compaction:4")], + nodeIds: [nodeId], + subagentIds: [nodeId], + messageIds: [MessageId.make("message:idle-compaction:4")], + }) + .pipe(Effect.withTracer(byId.tracer)); + assert.deepEqual( + found.runs.map((run) => run.id), + ["run:idle-compaction:4"], + ); + for (const table of ["runs", "nodes", "subagents", "messages"]) { + const query = byId.statements.find((statement) => + statement.includes(`FROM orchestration_v2_projection_${table}`), + ); + assert.isDefined(query); + const plan = (yield* sql.unsafe<{ readonly detail: string }>(`EXPLAIN QUERY PLAN ${query}`)) + .map((row) => row.detail) + .join("\n"); + assert.include(plan, `USING INDEX sqlite_autoindex_orchestration_v2_projection_${table}_1`); + } assert.deepEqual( records.providerTurns.map((turn) => turn.id), ["turn:idle-newest"], diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e40874ab0d7e..7c7bbecafe5a 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -345,6 +345,7 @@ export interface ProjectionRecordFilter { readonly turnItemRunIds?: ReadonlyArray; readonly turnItemNodeIds?: ReadonlyArray; readonly runIds?: ReadonlyArray; + /** Without `includeLatestRun`, reads through a status index and sorts the matches, so keep it to statuses few runs hold. */ readonly runStatuses?: ReadonlyArray; /** Keeps the thread's highest-ordinal run even when `runStatuses` excludes it. */ readonly includeLatestRun?: true; @@ -3167,6 +3168,11 @@ export const layer: Layer.Layer = `; }); + // An id filter reads by primary key. `+` keeps SQLite off the thread index, which walks + // every row of the thread to find the few ids. + const threadColumn = (ids: ReadonlyArray | undefined, column = "thread_id") => + sql.literal(ids === undefined ? column : `+${column}`); + const readCanonicalProjection = Effect.fn("ProjectionStore.readCanonicalProjection")( function* ( threadId: ThreadId, @@ -3400,21 +3406,26 @@ export const layer: Layer.Layer = ? sql` SELECT payload_json FROM orchestration_v2_projection_runs - WHERE thread_id = ${threadId} + WHERE ${threadColumn(filter?.runIds)} = ${threadId} ${filter?.runIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.runIds)}))`} ${ filter?.runStatuses === undefined - ? sql`` - : sql`AND (status IN (SELECT value FROM json_each(${encodeIdList(filter.runStatuses)})) - OR (${filter.includeLatestRun === true ? 1 : 0} = 1 AND run_id = ( + ? sql`ORDER BY ordinal ASC` + : filter.includeLatestRun !== true + ? // `+ordinal` stops SQLite from walking every run in the (thread_id, ordinal) + // index to skip a sort; a status index reads only matching runs. + sql`AND status IN (SELECT value FROM json_each(${encodeIdList(filter.runStatuses)})) + ORDER BY +ordinal ASC` + : sql`AND (status IN (SELECT value FROM json_each(${encodeIdList(filter.runStatuses)})) + OR run_id = ( SELECT run_id FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId} AND (status <> 'cancelled' OR json_extract(payload_json, '$.startedAt') IS NOT NULL) ORDER BY ordinal DESC LIMIT 1 - )))` + )) + ORDER BY ordinal ASC` } - ORDER BY ordinal ASC ` : sql` SELECT payload_json FROM orchestration_v2_projection_runs @@ -3464,7 +3475,7 @@ export const layer: Layer.Layer = ? sql` SELECT payload_json FROM orchestration_v2_projection_nodes AS node - WHERE node.thread_id = ${threadId} + WHERE ${threadColumn(filter?.nodeIds, "node.thread_id")} = ${threadId} ${filter?.nodeIds === undefined ? sql`` : sql`AND node.node_id IN (SELECT value FROM json_each(${encodeIdList(filter.nodeIds)}))`} ${ filter?.omitSettledLeafNodes === true @@ -3503,7 +3514,7 @@ export const layer: Layer.Layer = ? sql` SELECT payload_json FROM orchestration_v2_projection_subagents AS subagent - WHERE thread_id = ${threadId} + WHERE ${threadColumn(filter?.subagentIds)} = ${threadId} ${filter?.subagentIds === undefined ? sql`` : sql`AND subagent_id IN (SELECT value FROM json_each(${encodeIdList(filter.subagentIds)}))`} ${filter?.subagentRunIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.subagentRunIds)}))`} ${ @@ -3638,7 +3649,7 @@ export const layer: Layer.Layer = : window === undefined ? sql` SELECT payload_json FROM orchestration_v2_projection_messages - WHERE thread_id = ${threadId} + WHERE ${threadColumn(filter?.messageIds)} = ${threadId} ${filter?.messageIds === undefined ? sql`` : sql`AND message_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageIds)}))`} ${filter?.messageRoles === undefined ? sql`` : sql`AND role IN (SELECT value FROM json_each(${encodeIdList(filter.messageRoles)}))`} ${filter?.monitorNotificationsOnly === true ? sql`AND json_extract(payload_json, '$.notification.source.kind') = 'monitor'` : sql``} diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 085be554c0c2..de12768ac7b1 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -504,13 +504,15 @@ export class ThreadManagementService extends Context.Service< ThreadManagementServiceShape >()("t3/orchestration-v2/ThreadManagementService") {} +export const ACTIVE_RUN_STATUSES = [ + "preparing", + "starting", + "running", + "waiting", +] as const satisfies ReadonlyArray; + export function isActiveRun(run: OrchestrationV2Run): boolean { - return ( - run.status === "preparing" || - run.status === "starting" || - run.status === "running" || - run.status === "waiting" - ); + return (ACTIVE_RUN_STATUSES as ReadonlyArray).includes(run.status); } export function isTerminalRunStatus( From 20c3dd3689782bfcb1a04332086d08017028c718 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 07:20:27 -0800 Subject: [PATCH 002/170] fix(ssh): concurrent launches on one remote home share one server (#32587) Co-authored-by: Claude Opus 5.5 --- packages/ssh/src/tunnel.test.ts | 138 ++++++++++++++++++++++++++++++++ packages/ssh/src/tunnel.ts | 125 ++++++++++++++++++++++++++--- 2 files changed, 250 insertions(+), 13 deletions(-) diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index 65d6448deaf6..0d9786c22fc3 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -13,7 +13,9 @@ import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as Result from "effect/Result"; @@ -24,6 +26,7 @@ import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as SshAuth from "./auth.ts"; +import { remoteStateKey } from "./command.ts"; import { SshCommandError, SshPasswordPromptError, SshReadinessError } from "./errors.ts"; import * as SshTunnel from "./tunnel.ts"; @@ -92,6 +95,73 @@ function commandArgs(command: ChildProcess.Command): ReadonlyArray { const ARCHIVE = { archiveVersion: "1.2.3-preview.20260911.4" } as const; +// Emulates `t3 serve`: it takes the home owner lock at startup, then binds +// once a second server has tried the same home (or after 2s), so a concurrent +// launch always sees the home still unclaimed. Like the real server, it +// publishes server-runtime.json after it starts answering HTTP, if at all. +const fakeT3Serve = (publishDelayMs: number | null) => `const fs = require("node:fs"); +const http = require("node:http"); +const path = require("node:path"); +const args = process.argv.slice(2); +const port = Number(args[args.indexOf("--port") + 1]); +const userdata = path.join(args[args.indexOf("--base-dir") + 1], "userdata"); +const servers = path.join(process.env.HOME, "servers"); +fs.mkdirSync(userdata, { recursive: true }); +fs.appendFileSync(servers, process.pid + "\\n"); +try { + fs.writeFileSync(path.join(userdata, "server.lock"), String(process.pid), { flag: "wx" }); +} catch { + console.error("ServerAlreadyRunningError: another server owns " + userdata); + process.exit(1); +} +setTimeout(() => process.exit(0), 60_000); +const serve = (tries) => { + if (tries > 0 && fs.readFileSync(servers, "utf8").trim().split("\\n").length < 2) { + setTimeout(() => serve(tries - 1), 50); + return; + } + http.createServer((_, response) => response.end()).listen(port, "127.0.0.1", () => { + const origin = "http://127.0.0.1:" + port; + ${publishDelayMs === null ? "return;" : ""} + setTimeout(() => { + fs.writeFileSync(path.join(userdata, "server-runtime.json"), JSON.stringify({ pid: process.pid, port, origin })); + }, ${publishDelayMs}); + }); +}; +serve(40); +`; + +// Runs the remote half of an SSH command (`sh -l -s -- `) as a local shell +// whose HOME is the given directory. Every launch after the first starts once +// a server is running (or after 10s), which lines up the race deterministically. +const localRemoteShellLayer = (home: string) => + Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + let launches = 0; + return ChildProcessSpawner.make((command) => { + if (command._tag !== "StandardCommand") return spawner.spawn(command); + const gate = + launches++ === 0 + ? "" + : 'i=0; while [ ! -s "$HOME/servers" ] && [ "$i" -lt 200 ]; do sleep 0.05; i=$((i+1)); done; '; + return spawner.spawn( + ChildProcess.make( + "sh", + ["-c", `${gate}exec sh -s -- "$1"`, "sh", ...commandArgs(command).slice(-1)], + { + ...command.options, + env: { ...command.options.env, HOME: home }, + // Like an SSH session ending, the shell's exit leaves its nohup'd server running. + detached: false, + }, + ), + ); + }); + }), + ); + describe("ssh tunnel scripts", () => { it("rejects archive versions that are not a single exact version segment", () => { for (const archiveVersion of [ @@ -630,6 +700,74 @@ describe("ssh tunnel scripts", () => { ); }), ); + + it.live("concurrent launches on one remote home record the server that owns it", () => + // The second row's server never publishes server-runtime.json. + Effect.forEach([1_500, null], (publishDelayMs) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ssh-launch-" }); + const serversFile = path.join(home, "servers"); + yield* Effect.addFinalizer(() => + fs.readFileString(serversFile).pipe( + Effect.map((pids) => { + for (const pid of pids.split("\n").filter(Boolean)) { + try { + process.kill(Number(pid), "SIGKILL"); + } catch {} + } + }), + Effect.ignore, + ), + ); + const serverScript = path.join(home, "fake-t3.cjs"); + yield* fs.writeFileString(serverScript, fakeT3Serve(publishDelayMs)); + // A launch that died holding the lock must not block or double-admit later ones. + const launchLock = path.join(home, ".t3", "ssh-launch", ".launch.lock"); + yield* fs.makeDirectory(path.dirname(launchLock), { recursive: true }); + yield* fs.writeFileString(launchLock, "999999999\n"); + const targets = [ + { alias: "devbox", hostname: "devbox", username: null, port: null }, + { alias: "devbox-tailnet", hostname: "devbox-tailnet", username: null, port: null }, + ]; + + const launches = yield* Effect.forEach( + targets, + (target) => + SshTunnel.launchOrReuseRemoteServer(target, undefined, { + nodeScriptPath: serverScript, + }), + { concurrency: "unbounded" }, + ).pipe(Effect.provide(localRemoteShellLayer(home))); + + const ownerPid = Number( + yield* fs.readFileString(path.join(home, ".t3", "userdata", "server.lock")), + ); + assert.sameMembers( + launches.map((launch) => launch.remoteServerKind), + ["managed", "external"], + ); + assert.equal(launches[0]!.remotePort, launches[1]!.remotePort); + assert.deepEqual((yield* fs.readFileString(serversFile)).trim().split("\n"), [ + String(ownerPid), + ]); + for (const [index, launch] of launches.entries()) { + if (launch.remoteServerKind !== "managed") continue; + const stateKey = yield* remoteStateKey(targets[index]!); + const recordedPid = yield* fs.readFileString( + path.join(home, ".t3", "ssh-launch", stateKey, "pid"), + ); + assert.equal( + Number(recordedPid.trim()), + ownerPid, + `${targets[index]!.alias} reported a managed server, but its recorded PID is not the server that owns the remote home`, + ); + } + assert.isFalse(yield* fs.exists(launchLock)); + }).pipe(Effect.scoped), + ).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); }); // On macOS, Node can bind 127.0.0.1: while another process (such as the diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index 2c55e1a453aa..c214cdbe6cd4 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -53,9 +53,9 @@ const SSH_READY_PROBE_TIMEOUT_MS = 1_000; const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000; const TUNNEL_STDERR_TAIL_CHARS = 16_384; const REMOTE_READY_TIMEOUT_MS = 60_000; -const REMOTE_LAUNCH_TIMEOUT_MS = 90_000; -// Matches the node-script launch command's whole ssh run against the same host. -const SSH_TUNNEL_CONNECT_TIMEOUT_MS = REMOTE_LAUNCH_TIMEOUT_MS; +const REMOTE_LAUNCH_BASE_TIMEOUT_MS = 90_000; +// Matches the node-script launch command's ssh run without the launch lock wait. +const SSH_TUNNEL_CONNECT_TIMEOUT_MS = REMOTE_LAUNCH_BASE_TIMEOUT_MS; const SSH_TUNNEL_FORWARD_PROBE_INTERVAL_MS = 100; // Cold archive launches download and extract ~70 MB and may wait on an install lock. // Lock waits must outlast both downloads and extraction; SSH must outlast install or wait plus readiness. @@ -65,6 +65,23 @@ const REMOTE_ARCHIVE_DOWNLOAD_SECONDS = 240; const REMOTE_ARCHIVE_LOCK_WAIT_SECONDS = 360; const REMOTE_ARCHIVE_LAUNCH_TIMEOUT_MS = 900_000; const REMOTE_REUSE_READY_TIMEOUT_MS = 2_000; +const REMOTE_PID_EXIT_WAIT_MS = 2_000; +// The server answers HTTP before it writes server-runtime.json, which is how +// a launch for another alias finds it. +const REMOTE_RUNTIME_RECORD_WAIT_SECONDS = 10; +// A launch holds the home lock through up to two reuse probes, readiness, two +// server exit waits, and the runtime record wait; each probe may overrun its +// deadline by one request. +const REMOTE_LAUNCH_LOCK_WAIT_SECONDS = Math.ceil( + (REMOTE_READY_TIMEOUT_MS + + 2 * REMOTE_REUSE_READY_TIMEOUT_MS + + 2 * REMOTE_PID_EXIT_WAIT_MS + + REMOTE_RUNTIME_RECORD_WAIT_SECONDS * 1000 + + 4 * SSH_READY_PROBE_TIMEOUT_MS) / + 1000, +); +const REMOTE_LAUNCH_TIMEOUT_MS = + REMOTE_LAUNCH_LOCK_WAIT_SECONDS * 1000 + REMOTE_LAUNCH_BASE_TIMEOUT_MS; export interface RemoteT3RunnerOptions { readonly nodeScriptPath?: string | null; @@ -537,30 +554,82 @@ MANAGED_FILE="$STATE_DIR/managed" LOG_FILE="$STATE_DIR/server.log" RUNNER_FILE="$STATE_DIR/run-t3.sh" RUNNER_NEXT="$STATE_DIR/run-t3.next.$$" +LAUNCH_LOCK="$DEFAULT_SERVER_HOME/ssh-launch/.launch.lock" +LAUNCH_BREAK_LOCK="$LAUNCH_LOCK.break" mkdir -p "$STATE_DIR" -cleanup_runner_next() { +cleanup_launch() { rm -f "$RUNNER_NEXT" + for OWNED_LOCK in "$LAUNCH_LOCK" "$LAUNCH_BREAK_LOCK"; do + if [ "$(cat "$OWNED_LOCK" 2>/dev/null || true)" = "$$" ]; then + rm -f "$OWNED_LOCK" + fi + done } -trap cleanup_runner_next EXIT +trap cleanup_launch EXIT +# A dropped SSH session signals the launch (PIPE on its next write); exit so +# the lock is released. +trap 'exit 1' HUP INT PIPE TERM cat >"$RUNNER_NEXT" <<'SH' @@T3_RUNNER_SCRIPT@@ SH -RUNNER_CHANGED=0 -if [ ! -f "$RUNNER_FILE" ] || ! cmp -s "$RUNNER_NEXT" "$RUNNER_FILE"; then - RUNNER_CHANGED=1 -fi -mv "$RUNNER_NEXT" "$RUNNER_FILE" -chmod 700 "$RUNNER_FILE" +chmod 700 "$RUNNER_NEXT" T3_ARCHIVE_MODE=@@T3_ARCHIVE_MODE@@ if [ "$T3_ARCHIVE_MODE" = "1" ]; then # The archive ships the helpers below inside the executable; the remote # needs no Node at all. Resolving the runner once here also downloads the # archive before the port and readiness probes rely on it. - "$RUNNER_FILE" --version >/dev/null + "$RUNNER_NEXT" --version >/dev/null elif ! ensure_remote_node_path; then printf 'Remote host is missing node on PATH. Install Node or configure a supported version manager for non-interactive shells.\\n' >&2 exit 1 fi +# Recovery runs under its own lock and re-reads the owner there, so a waiter +# that judged an earlier lock stale cannot remove its successor's lock. No +# launch removes another's recovery lock: only SIGKILL inside these lines +# leaves one behind, and the wait below then fails naming it. +discard_stale_launch_lock() { + (set -C; printf '%s\\n' "$$" >"$LAUNCH_BREAK_LOCK") 2>/dev/null || return 1 + if [ "$(cat "$LAUNCH_LOCK" 2>/dev/null || true)" = "$1" ]; then + rm -f "$LAUNCH_LOCK" + fi + rm -f "$LAUNCH_BREAK_LOCK" +} +# Concurrent launches share this home's owner lock and may share this record. +# Hold the lock from comparing the runner until the server is recorded and +# ready, so a waiting launch reuses that server instead of starting or +# replacing one. +LAUNCH_LOCK_WAITED=0 +LAUNCH_LOCK_UNOWNED=0 +while ! (set -C; printf '%s\\n' "$$" >"$LAUNCH_LOCK") 2>/dev/null; do + LAUNCH_LOCK_OWNER="$(cat "$LAUNCH_LOCK" 2>/dev/null || true)" + if [ -n "$LAUNCH_LOCK_OWNER" ]; then + LAUNCH_LOCK_UNOWNED=0 + if ! kill -0 "$LAUNCH_LOCK_OWNER" 2>/dev/null && discard_stale_launch_lock "$LAUNCH_LOCK_OWNER"; then + continue + fi + else + LAUNCH_LOCK_UNOWNED=$((LAUNCH_LOCK_UNOWNED + 1)) + if [ "$LAUNCH_LOCK_UNOWNED" -ge 5 ] && discard_stale_launch_lock ""; then + LAUNCH_LOCK_UNOWNED=0 + continue + fi + fi + if [ "$LAUNCH_LOCK_WAITED" -ge @@T3_LAUNCH_LOCK_WAIT_SECONDS@@ ]; then + if [ -e "$LAUNCH_BREAK_LOCK" ]; then + printf 'A T3 server launch stopped while recovering %s. If no launch is running, delete %s.\\n' "$LAUNCH_LOCK" "$LAUNCH_BREAK_LOCK" >&2 + else + printf 'Another T3 server launch has held %s for too long.\\n' "$LAUNCH_LOCK" >&2 + fi + exit 1 + fi + sleep 1 + LAUNCH_LOCK_WAITED=$((LAUNCH_LOCK_WAITED + 1)) +done +RUNNER_CHANGED=0 +if [ ! -f "$RUNNER_FILE" ] || ! cmp -s "$RUNNER_NEXT" "$RUNNER_FILE"; then + RUNNER_CHANGED=1 +fi +mv "$RUNNER_NEXT" "$RUNNER_FILE" pick_port() { if [ "$T3_ARCHIVE_MODE" = "1" ]; then "$RUNNER_FILE" __ssh-helper pick-port "$PORT_FILE" "@@T3_DEFAULT_REMOTE_PORT@@" "@@T3_REMOTE_PORT_SCAN_WINDOW@@" @@ -582,7 +651,7 @@ NODE wait_for_pid_exit() { PID_TO_WAIT="$1" WAIT_COUNT=0 - while kill -0 "$PID_TO_WAIT" 2>/dev/null && [ "$WAIT_COUNT" -lt 20 ]; do + while kill -0 "$PID_TO_WAIT" 2>/dev/null && [ "$WAIT_COUNT" -lt @@T3_PID_EXIT_WAIT_TICKS@@ ]; do WAIT_COUNT=$((WAIT_COUNT + 1)) sleep 0.1 done @@ -693,6 +762,25 @@ else REMOTE_PORT="" REMOTE_MANAGED="" fi +# The server may answer long before it publishes its runtime record, or never +# publish one; another alias's launch record still names it. Only one server +# owns the home, so the first live one decides. +if [ -z "$REMOTE_PORT" ] && [ -z "$DEFAULT_RUNTIME_INFO" ]; then + for SIBLING_DIR in "$DEFAULT_SERVER_HOME"/ssh-launch/*; do + [ "$SIBLING_DIR" != "$STATE_DIR" ] && [ "$(cat "$SIBLING_DIR/managed" 2>/dev/null || true)" = "managed" ] || continue + server_running "$(cat "$SIBLING_DIR/pid" 2>/dev/null || true)" || continue + REMOTE_PORT="$(cat "$SIBLING_DIR/port" 2>/dev/null || true)" + if [ -n "$REMOTE_PORT" ] && wait_ready "@@T3_REUSE_READY_TIMEOUT_MS@@"; then + REMOTE_MANAGED="external" + rm -f "$PID_FILE" + printf '%s\\n' "$REMOTE_PORT" >"$PORT_FILE" + printf 'external\\n' >"$MANAGED_FILE" + else + REMOTE_PORT="" + fi + break + done +fi if [ -z "$REMOTE_PORT" ]; then REMOTE_PORT="$(pick_port)" || true if [ -z "$REMOTE_PORT" ]; then @@ -720,6 +808,14 @@ if [ -z "$REMOTE_PORT" ]; then rm -f "$PID_FILE" "$PORT_FILE" "$MANAGED_FILE" exit 1 fi + # Keep the lock until another alias's launch can find this server, or it + # would start a second one that loses the home's owner lock. + RECORD_DEADLINE=$(($(date +%s) + @@T3_RUNTIME_RECORD_WAIT_SECONDS@@)) + while [ "$(date +%s)" -lt "$RECORD_DEADLINE" ]; do + DEFAULT_RUNTIME_INFO="$(resolve_default_runtime_port 2>/dev/null || true)" + [ "\${DEFAULT_RUNTIME_INFO%% *}" = "$REMOTE_PID" ] && break + sleep 0.1 + done fi printf '{"remotePort":%s,"serverKind":"%s"}\\n' "$REMOTE_PORT" "\${REMOTE_MANAGED:-managed}" `; @@ -839,6 +935,9 @@ function buildRemoteLaunchScript(input?: RemoteT3RunnerOptions): string { T3_READY_TIMEOUT_MS: String(REMOTE_READY_TIMEOUT_MS), T3_REUSE_READY_TIMEOUT_MS: String(REMOTE_REUSE_READY_TIMEOUT_MS), T3_READY_PROBE_TIMEOUT_MS: String(SSH_READY_PROBE_TIMEOUT_MS), + T3_PID_EXIT_WAIT_TICKS: String(REMOTE_PID_EXIT_WAIT_MS / 100), + T3_LAUNCH_LOCK_WAIT_SECONDS: String(REMOTE_LAUNCH_LOCK_WAIT_SECONDS), + T3_RUNTIME_RECORD_WAIT_SECONDS: String(REMOTE_RUNTIME_RECORD_WAIT_SECONDS), }); } From 80e62619f5c01d84579bcf70ea6d566712007412 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 08:00:21 -0800 Subject: [PATCH 003/170] fix(mobile): iOS 18 iPad sidebar and thread feed start below the header (#32936) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/components/ui/useBarInset.ts | 6 +++--- .../layout/workspace/workspace-list-insets.ts | 6 ------ .../src/features/threads/ThreadDetailScreen.tsx | 1 - apps/mobile/src/features/threads/ThreadFeed.tsx | 11 +++++++---- .../src/features/threads/ThreadNavigationSidebar.tsx | 5 +++-- 5 files changed, 13 insertions(+), 16 deletions(-) diff --git a/apps/mobile/src/components/ui/useBarInset.ts b/apps/mobile/src/components/ui/useBarInset.ts index 2292f2941254..f00b64c8e0b7 100644 --- a/apps/mobile/src/components/ui/useBarInset.ts +++ b/apps/mobile/src/components/ui/useBarInset.ts @@ -38,9 +38,9 @@ export function useBarOverlap(): number { } /** - * The content's top safe area under the AppBar: a translucent bar's height, zero under a solid - * one or on Android, where the bar sits in flow. For scroll content insets, which must not - * double-count a solid bar. + * The content's top safe area under the AppBar: the height of the iOS bar its column lays content + * under, glass or solid, and zero on Android, where the bar sits in flow. For manual scroll + * content insets. */ export function useContentTopInset(): number { const insets = useSafeAreaInsets(); diff --git a/apps/mobile/src/features/layout/workspace/workspace-list-insets.ts b/apps/mobile/src/features/layout/workspace/workspace-list-insets.ts index ae7048bcdba0..52b8a3407158 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-list-insets.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-list-insets.ts @@ -2,12 +2,6 @@ import { useSafeAreaInsets } from "react-native-safe-area-context"; import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../../native/native-glass"; -/** A workspace list scrolls under its bar where the bar is glass; under a solid bar it starts below. */ -export const WORKSPACE_LIST_SCROLL_INSETS = { - automaticallyAdjustsScrollIndicatorInsets: NATIVE_LIQUID_GLASS_SUPPORTED, - contentInsetAdjustmentBehavior: NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never", -} as const; - /** How far an empty workspace list keeps its message below a glass bar and its search. */ export function useWorkspaceListEmptyTopInset(): number { const insets = useSafeAreaInsets(); diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 692518729f44..d9bb48682f89 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1496,7 +1496,6 @@ function ThreadDetailBody( keyboardOffset={composerKeyboardOffset} sendingWithKeyboard={sendingWithKeyboard} fitShortFeedToViewport={questionInFlow && !isKeyboardVisible} - contentTopInset={0} contentBottomInset={ questionInFlow ? 0 diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index e3e9e97e7851..fcc957840d98 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -170,7 +170,7 @@ import { getReviewSectionIdForCheckpoint } from "../review/reviewModel"; import { setReviewSelectedSectionId } from "../review/reviewState"; import { Menu } from "../../components/ui/Menu"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; -import { useBarInset } from "../../components/ui/useBarInset"; +import { useBarInset, useContentTopInset } from "../../components/ui/useBarInset"; import { copyPromptLink } from "../prompt-links/prompt-link-actions"; import { parseReviewCommentMessageSegments } from "../review/reviewCommentSelection"; import { @@ -332,7 +332,6 @@ export interface ThreadFeedProps { readonly keyboardOffset: number; readonly sendingWithKeyboard?: boolean; readonly fitShortFeedToViewport?: boolean; - readonly contentTopInset?: number; readonly contentBottomInset?: number; readonly historyControls?: ThreadFeedHistoryControls; readonly contentMaxWidth?: number; @@ -2772,10 +2771,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const markdownContentWidth = Math.max(0, contentWidth - ASSISTANT_ROW_HORIZONTAL_PADDING * 2); const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth); const barInset = useBarInset(); - const topContentInset = props.contentTopInset ?? barInset; + const columnTopInset = useContentTopInset(); const bottomContentInset = props.contentBottomInset ?? 18; const usesNativeAutomaticInsets = props.usesAutomaticContentInsets === true && Platform.OS === "ios"; + // Without the native contentInset, a list-header spacer clears the bar the column lays content under. + const topContentInset = usesNativeAutomaticInsets ? 0 : columnTopInset; const anchorTopInset = usesNativeAutomaticInsets ? barInset : topContentInset; const theme = useUniwindTheme(); @@ -3200,7 +3201,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { if (state) onIsAtEndChange?.(state.isAtEnd); }; const handleScroll = (event: NativeSyntheticEvent) => { - reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6); + reportHeaderMaterialVisibility( + event.nativeEvent.contentOffset.y + (usesNativeAutomaticInsets ? barInset : 0) > 6, + ); handleMetricsChange(); }; // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the list's end state to report it to the parent diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index dce389c83666..3d0253e2d3a2 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -48,7 +48,6 @@ import { usePendingTaskListActions } from "../home/usePendingTaskListActions"; import { useThreadListActions } from "../home/useThreadListActions"; import { useFabScroll } from "../home/FabScrollContext"; import { WorkspaceListHeader } from "../layout/workspace/WorkspaceListHeader"; -import { WORKSPACE_LIST_SCROLL_INSETS } from "../layout/workspace/workspace-list-insets"; import { WorkspaceSidebarColumn } from "../layout/workspace/WorkspaceSidebarColumn"; import { ThreadListV2PendingRow, @@ -592,7 +591,9 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { itemsAreEqual={sidebarItemsAreEqual} keyExtractor={(item) => item.key} renderItem={renderListItem} - {...WORKSPACE_LIST_SCROLL_INSETS} + automaticallyAdjustsScrollIndicatorInsets + // The column lays the list under its bar, glass or solid; UIKit insets it past both. + contentInsetAdjustmentBehavior="automatic" contentContainerStyle={[ styles.threadListContent, { From e509db3a2f21b8e291d05ef11789c6a4ff662e9c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 08:16:12 -0800 Subject: [PATCH 004/170] fix(web): Tab reaches the add-project and new-project submit buttons (#32605) Co-authored-by: Claude Opus 5.5 --- .../CommandPalette.composition.browser.test.tsx | 16 ++++++++++++++++ .../src/components/CommandPaletteAddProject.tsx | 1 - 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/CommandPalette.composition.browser.test.tsx b/apps/web/src/components/CommandPalette.composition.browser.test.tsx index c0b5b3269ce8..8a56bc6ae931 100644 --- a/apps/web/src/components/CommandPalette.composition.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.composition.browser.test.tsx @@ -56,6 +56,7 @@ vi.mock("../state/environments", async (original) => ({ serverConfig: { environment: { platform: { os: "linux" }, capabilities: { projectCloneTracking: true } }, settings: { addProjectBaseDirectory: "/workspace/" }, + newProjectsRoot: "/workspace/", }, }, ], @@ -147,3 +148,18 @@ it("keeps the caret in place when an edit briefly makes the folder path not a pa await userEvent.keyboard("w"); await expect.element(input()).toHaveValue("/wworkspace/project"); }); + +it.each([ + { flow: "Git URL", value: "https://github.com/pingdotgg/t3code.git", submit: "Continue (Enter)" }, + { flow: "New project", value: "demo-tab-order", submit: /^Create \(/ }, +])("moves focus from the $flow input to its enabled submit button on Tab", async (step) => { + await using _screen = await render({null}); + await act(() => openCommandPalette({ open: "add-project" })); + await page.getByText(step.flow, { exact: true }).click(); + const input = page.getByRole("combobox"); + await input.fill(step.value); + const submit = page.getByRole("button", { name: step.submit }); + await expect.element(submit).toBeEnabled(); + await userEvent.keyboard("{Tab}"); + await expect.element(submit).toHaveFocus(); +}); diff --git a/apps/web/src/components/CommandPaletteAddProject.tsx b/apps/web/src/components/CommandPaletteAddProject.tsx index 808536403a4b..9edbf628889d 100644 --- a/apps/web/src/components/CommandPaletteAddProject.tsx +++ b/apps/web/src/components/CommandPaletteAddProject.tsx @@ -48,7 +48,6 @@ export function CommandPaletteSubmitButton(props: { , document.body)} + + ); + await using screen = await render(panel(false)); + await userEvent.click(screen.getByRole("textbox", { name: "Message New thread" })); + await screen.rerender(panel(true)); + await act(() => screen.getByRole("region", { name: "Open a surface" }).element().focus()); + await act(() => page.getByRole("button", { name: "Add panel surface" }).element().focus()); + await act(() => screen.getByRole("region", { name: "Open a surface" }).element().focus()); + + await screen.rerender(panel(false)); + + await expect.element(screen.getByRole("textbox", { name: "Message New thread" })).toHaveFocus(); + }); + + it("falls back to the toggle without scrolling when the origin has scrolled out of view", async () => { + const layout = (open: boolean) => ( +
+
+ +
+
+ ) : null; diff --git a/oxlint-plugin-t3code/index.ts b/oxlint-plugin-t3code/index.ts index 1efb0fb2a390..98b7ac2bff7c 100644 --- a/oxlint-plugin-t3code/index.ts +++ b/oxlint-plugin-t3code/index.ts @@ -16,6 +16,7 @@ import noMobileUniwindThemeEscapeHatches from "./rules/no-mobile-uniwind-theme-e import noAmbiguousDetailNavigation from "./rules/no-ambiguous-detail-navigation.ts"; import noMobilePullRequestGlyphLiterals from "./rules/no-mobile-pull-request-glyph-literals.ts"; import noNativeTitleTooltip from "./rules/no-native-title-tooltip.ts"; +import noSparklesIcon from "./rules/no-sparkles-icon.ts"; import noUnreasonedStateSync from "./rules/no-unreasoned-state-sync.ts"; import requireRegisteredListScroll from "./rules/require-registered-list-scroll.ts"; import noOutsetStateIndicators from "./rules/no-outset-state-indicators.ts"; @@ -55,6 +56,7 @@ export default definePlugin({ "no-ambiguous-detail-navigation": noAmbiguousDetailNavigation, "no-mobile-pull-request-glyph-literals": noMobilePullRequestGlyphLiterals, "no-native-title-tooltip": noNativeTitleTooltip, + "no-sparkles-icon": noSparklesIcon, "no-unreasoned-state-sync": noUnreasonedStateSync, "require-registered-list-scroll": requireRegisteredListScroll, "no-outset-state-indicators": noOutsetStateIndicators, diff --git a/oxlint-plugin-t3code/rules/no-sparkles-icon.test.ts b/oxlint-plugin-t3code/rules/no-sparkles-icon.test.ts new file mode 100644 index 000000000000..35091b59b973 --- /dev/null +++ b/oxlint-plugin-t3code/rules/no-sparkles-icon.test.ts @@ -0,0 +1,48 @@ +import { describe } from "@effect/vitest"; + +import { createOxlintRuleHarness } from "../test/utils.ts"; + +const rule = createOxlintRuleHarness("t3code/no-sparkles-icon", { + filename: "apps/web/src/components/chat/Example.tsx", +}); + +describe("t3code/no-sparkles-icon", () => { + rule.valid( + "allows icons that name the action", + ` + import { BotIcon, ShieldCheckIcon } from "lucide-react"; + import IconRobot from "@tabler/icons-react-native/IconRobot"; + + const icon = ; + `, + ); + + rule.valid( + "allows copy and identifiers that mention sparkles", + ` + const NIGHTLY_SPARKLES = []; + const label = "Add some sparkles to the release notes"; + `, + ); + + rule.invalid("reports Lucide sparkles icons", `import { SparklesIcon } from "lucide-react";`); + + rule.invalid( + "reports every Lucide sparkle variant", + `import { Sparkle, WandSparklesIcon, LucideSparkles } from "lucide-react";`, + ); + + rule.invalid("reports Lucide icon nodes", `import { Sparkles } from "lucide";`); + + rule.invalid( + "reports Tabler sparkles deep imports", + `import IconSparkles from "@tabler/icons-react-native/IconSparkles";`, + ); + + rule.invalid("reports SF Symbol sparkles names", `const icon = ;`); + + rule.invalid( + "reports platform symbol objects", + `const icon = { ios: "wand.and.sparkles", android: "auto_awesome" };`, + ); +}); diff --git a/oxlint-plugin-t3code/rules/no-sparkles-icon.ts b/oxlint-plugin-t3code/rules/no-sparkles-icon.ts new file mode 100644 index 000000000000..e44c012b1113 --- /dev/null +++ b/oxlint-plugin-t3code/rules/no-sparkles-icon.ts @@ -0,0 +1,50 @@ +import { defineRule } from "@oxlint/plugins"; + +const SPARKLE_NAME = /sparkle/iu; +// SF Symbol (`sparkles`, `sparkles.square.filled.on.square`, `wand.and.sparkles`) and +// Material (`auto_awesome`) names reach native icons as plain strings. +const SPARKLE_SYMBOL_NAME = /^(?:(?:[\w]+\.)*sparkles?(?:\.[\w.]+)?|auto_awesome(?:_\w+)?)$/u; +const TABLER_SOURCE = /^@tabler\/icons(?:-react|-react-native)?(?:\/|$)/u; + +const MESSAGE = + "Sparkles says 'AI', not what the control does. Pick an icon for the action itself, such as Bot for agent work or ShieldCheck for Auto mode."; + +export default defineRule({ + meta: { + type: "problem", + docs: { + description: + "Disallow sparkles icons; they label a control as AI instead of saying what it does.", + }, + }, + create(context) { + return { + ImportDeclaration(node) { + const source = node.source.value; + if (source === "lucide" || source === "lucide-react" || TABLER_SOURCE.test(source)) { + if (TABLER_SOURCE.test(source) && SPARKLE_NAME.test(source.split("/").at(-1) ?? "")) { + context.report({ node: node.source, message: MESSAGE }); + return; + } + for (const specifier of node.specifiers) { + if (specifier.type !== "ImportSpecifier") continue; + const imported = + specifier.imported.type === "Identifier" + ? specifier.imported.name + : specifier.imported.value; + if (SPARKLE_NAME.test(imported)) context.report({ node: specifier, message: MESSAGE }); + } + } + }, + Literal(node) { + if (typeof node.value !== "string" || !SPARKLE_SYMBOL_NAME.test(node.value)) return; + if (node.parent.type === "ImportDeclaration") return; + context.report({ node, message: MESSAGE }); + }, + TemplateElement(node) { + if (!SPARKLE_SYMBOL_NAME.test(node.value.cooked ?? "")) return; + context.report({ node, message: MESSAGE }); + }, + }; + }, +}); diff --git a/vite.config.ts b/vite.config.ts index d891ec91f054..0bca1261c9e5 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -319,6 +319,12 @@ export default defineConfig({ ], rules: { "t3code/prefer-effect-fn": "off" }, }, + { + files: ["apps/web/src/**", "apps/mobile/src/**", "apps/desktop/src/**"], + // Users still pick their own project icon from the full Lucide set. + excludeFiles: ["apps/web/src/projectIconOptions.ts"], + rules: { "t3code/no-sparkles-icon": "error" }, + }, { files: ["apps/web/**/*.test.{ts,tsx}"], rules: { "t3code/require-disposable-render": "error" }, From d290c1f1b6c93416dfda6c9f7cd15d928a9aeb4c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 12:48:03 -0800 Subject: [PATCH 035/170] fix(github): a proxy's 403 with Retry-After is no longer reported as a rate limit (#33676) Co-authored-by: Claude Opus 5.5 --- .../src/server/GitHubRequestPolicy.ts | 14 +++-- .../src/server/GitHubRest.test.ts | 52 +++++++++++++++++++ .../src/server/gitHubGraphQlClient.test.ts | 8 +++ 3 files changed, 71 insertions(+), 3 deletions(-) diff --git a/packages/source-control-github/src/server/GitHubRequestPolicy.ts b/packages/source-control-github/src/server/GitHubRequestPolicy.ts index 0d48932db327..8e37495494c4 100644 --- a/packages/source-control-github/src/server/GitHubRequestPolicy.ts +++ b/packages/source-control-github/src/server/GitHubRequestPolicy.ts @@ -147,7 +147,11 @@ function retryAtFrom( return Number.isFinite(reset) && reset > now ? reset : undefined; } -/** HTTP 200 GraphQL rate limits use RATE_LIMITED or untyped errors with quota headers. */ +/** + * HTTP 200 GraphQL rate limits use RATE_LIMITED or untyped errors with quota headers. A 403 is a + * limit only when its quota, body or GraphQL errors name one (older hosts say "abuse detection + * mechanism"): a proxy in front of GitHub Enterprise can refuse with `Retry-After` alone. + */ export function isRateLimited(input: { readonly status: number; readonly headers: Readonly>; @@ -167,11 +171,15 @@ export function isRateLimited(input: { ))) || (status === 403 && (headers["x-ratelimit-remaining"] === "0" || - headers["retry-after"] !== undefined || - /rate limit/i.test(input.body ?? ""))) + namesLimit(input.body) || + (errors ?? []).some((error) => namesLimit(error.message)))) ); } +function namesLimit(text: unknown): boolean { + return typeof text === "string" && /rate limit|abuse detection mechanism/i.test(text); +} + export type GitHubAnswer = { readonly status: number | undefined; readonly headers: Readonly>; diff --git a/packages/source-control-github/src/server/GitHubRest.test.ts b/packages/source-control-github/src/server/GitHubRest.test.ts index 0c5d4f0eed7d..8ac8e50fc17b 100644 --- a/packages/source-control-github/src/server/GitHubRest.test.ts +++ b/packages/source-control-github/src/server/GitHubRest.test.ts @@ -510,6 +510,58 @@ describe("GitHubRest", () => { }).pipe(Effect.provide(layer)); }); + it.effect("reads a proxy's 403 with Retry-After as a refusal and keeps the host open", () => { + const pages = [ + "403 Forbiddennginx", + "Request blocked by proxy abuse detection; contact your administrator", + ]; + const { layer, requests } = harness( + () => + new Response(pages.shift(), { + status: 403, + headers: { "content-type": "text/html", "retry-after": "5" }, + }), + ); + return Effect.gen(function* () { + yield* TestClock.setTime(NOW); + const api = yield* GitHubRest.GitHubRest; + const read = { + host: "ghes.example.internal", + operation: "checks", + path: "repos/acme/web/pulls/7", + }; + const first = yield* Effect.flip(api.rest(read)); + expect(first).toMatchObject({ _tag: "GitHubApiResponseError", status: 403 }); + const second = yield* Effect.flip(api.rest(read)); + expect(second).toMatchObject({ _tag: "GitHubApiResponseError", status: 403 }); + expect(requests).toHaveLength(2); + }).pipe(Effect.provide(layer)); + }); + + it.effect("pauses the host on an abuse-detection 403 that never says rate limit", () => { + const { layer, requests } = harness(() => + json( + { + message: "You have triggered an abuse detection mechanism. Please wait before retrying.", + documentation_url: + "https://docs.github.com/rest/overview/resources-in-the-rest-api#abuse-rate-limits", + }, + { status: 403, headers: { "retry-after": "60", "x-ratelimit-remaining": "4878" } }, + ), + ); + return Effect.gen(function* () { + yield* TestClock.setTime(NOW); + const api = yield* GitHubRest.GitHubRest; + const read = { host: "github.com", operation: "checks", path: "repos/acme/web/pulls/7" }; + expect(yield* Effect.flip(api.rest(read))).toMatchObject({ + _tag: "GitHubApiRateLimitError", + retryAt: NOW + 60_000, + }); + expect((yield* Effect.flip(api.rest(read)))._tag).toBe("SourceControlRateLimitPausedError"); + expect(requests).toHaveLength(1); + }).pipe(Effect.provide(layer)); + }); + it.effect("drops a refused token so the next request asks the source again", () => { const { layer, requests, invalidations } = harness((request) => request.headers.authorization === "Bearer first" diff --git a/packages/source-control-github/src/server/gitHubGraphQlClient.test.ts b/packages/source-control-github/src/server/gitHubGraphQlClient.test.ts index 769a8ce65f25..4138d5f5a981 100644 --- a/packages/source-control-github/src/server/gitHubGraphQlClient.test.ts +++ b/packages/source-control-github/src/server/gitHubGraphQlClient.test.ts @@ -223,6 +223,10 @@ describe("GitHubGraphQlAuth", () => { const answers = [ json({ message: "You have exceeded a secondary rate limit." }, { status: 403 }), json({ message: "Bad credentials" }, { status: 401 }), + json( + { data: null, errors: [{ message: "You have exceeded a secondary rate limit." }] }, + { status: 403, headers: { "retry-after": "60" } }, + ), ]; const { layer, invalidations } = harness(() => answers.shift()!); return Effect.gen(function* () { @@ -231,6 +235,10 @@ describe("GitHubGraphQlAuth", () => { expect((yield* Effect.flip(readStats("github.example")))._tag).toBe( "GitHubApiAuthenticationError", ); + expect(yield* Effect.flip(readStats("github.acme.test"))).toMatchObject({ + _tag: "GitHubApiRateLimitError", + retryAt: NOW + 60_000, + }); expect(invalidations()).toBe(1); }).pipe(Effect.provide(layer)); }); From 9cd7a04797184c92a8f636ae1e918f42c139d850 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 12:57:50 -0800 Subject: [PATCH 036/170] fix(web): sending from an empty citation comment clears the composer (#33440) Co-authored-by: Claude Opus 5.5 --- ...ditorTiptap.citationDraft.browser.test.tsx | 62 +++++++++++++++++++ .../components/ComposerPromptEditorTiptap.tsx | 41 +++++++----- apps/web/src/components/chat/ChatComposer.tsx | 13 ++-- 3 files changed, 96 insertions(+), 20 deletions(-) diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsx index a1a69a7968ee..8da54f5f7214 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.citationDraft.browser.test.tsx @@ -31,9 +31,11 @@ const promptBefore = `See ${serializeAssistantCitation(citation)} `; function Composer({ question, editorRef, + send = "clears", }: { question: boolean; editorRef: React.RefObject; + send?: "clears" | "blocked" | "refusedLater"; }) { const [prompt, setPrompt] = useState(promptBefore); const [answer, setAnswer] = useState(""); @@ -61,6 +63,11 @@ function Composer({ onCitationDraftSave={(replacedValue, savedValue) => { if (replacedValue === prompt) setPrompt(savedValue); }} + onCitationSubmitAndSend={() => { + if (send === "blocked") return false; + if (send === "clears") setPrompt(""); + return true; + }} onPaste={() => {}} /> @@ -97,3 +104,58 @@ it("keeps an unsaved citation comment when a question takes the composer", async ); await expect.element(page.getByLabelText("Edit citation comment")).toBeInTheDocument(); }); + +it("clears the sent prompt when an empty citation comment sends it", async () => { + const editorRef = createRef(); + await using screen = await render(); + + const sourceAnchor = findAssistantCitationSourceAnchor(document, citation); + if (!sourceAnchor) throw new Error("Citation source did not resolve"); + await act(async () => + editorRef.current?.requestCitationComment({ + previousValue: "See ", + value: promptBefore, + citationStart: "See ".length, + sourceAnchor, + insertedSpaces: { before: false, after: true }, + }), + ); + const comment = page.getByLabelText("Comment on selected text"); + await expect.element(comment).toHaveFocus(); + await userEvent.keyboard("{Control>}{Enter}{/Control}"); + + await expect.element(comment).not.toBeInTheDocument(); + await expect.element(page.getByTestId("composer-editor")).toHaveFocus(); + await expect.element(screen.getByRole("status")).toHaveAttribute("data-prompt", ""); +}); + +it.each(["blocked", "refusedLater"] as const)( + "keeps the caret after the citation when save-and-send is %s", + async (send) => { + const editorRef = createRef(); + await using screen = await render( + , + ); + + const sourceAnchor = findAssistantCitationSourceAnchor(document, citation); + if (!sourceAnchor) throw new Error("Citation source did not resolve"); + await act(async () => + editorRef.current?.requestCitationComment({ + previousValue: "See ", + value: promptBefore, + citationStart: "See ".length, + sourceAnchor, + insertedSpaces: { before: false, after: true }, + }), + ); + const comment = page.getByLabelText("Comment on selected text"); + await expect.element(comment).toHaveFocus(); + await userEvent.keyboard("{Control>}{Enter}{/Control}"); + await expect.element(comment).not.toBeInTheDocument(); + await userEvent.keyboard("x"); + + await expect + .element(screen.getByRole("status")) + .toHaveAttribute("data-prompt", `See ${serializeAssistantCitation(citation)}x `); + }, +); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index bb8f5a5a2211..1986cc888efb 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -21,6 +21,7 @@ import { Plugin, PluginKey, TextSelection, + type Transaction, } from "@tiptap/pm/state"; import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view"; import type { NodeType, ResolvedPos } from "@tiptap/pm/model"; @@ -186,7 +187,7 @@ export interface ComposerPromptEditorProps { onPageScrollKeyDown?: (key: "PageUp" | "PageDown") => void; onPageScrollKeyUp?: (key: string) => void; onPageScrollRelease?: () => void; - onCitationSubmitAndSend?: () => void; + onCitationSubmitAndSend?: () => boolean; /** Saves unsaved citation text into replacedValue when a controlled rewrite replaces the document. */ onCitationDraftSave?: (replacedValue: string, savedValue: string) => void; onPaste: React.ClipboardEventHandler; @@ -213,12 +214,12 @@ const ComposerCitationCommentContext = createContext<{ openComment: OpenCitationComment | null; onOpenChange: (citeKey: string, open: boolean) => void; onDraftChange: (citeKey: string, comment: string) => void; - onSubmitAndSend: () => void; + onSubmitAndSend: () => boolean; }>({ openComment: null, onOpenChange: () => {}, onDraftChange: () => {}, - onSubmitAndSend: () => {}, + onSubmitAndSend: () => false, }); const RichComposerSkillsContext = createContext>([]); @@ -477,13 +478,23 @@ function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) { editor.chain().focus().deleteRange({ from, to }).run(); }; + const sentRef = useRef(false); const onRestoreFocus = () => { + const sent = sentRef.current; + sentRef.current = false; if (!editor.isEditable) return; const pos = nodePos(); - if (pos === null) return; - const current = editor.state.doc.nodeAt(pos); - if (!current || current.type.name !== "composer-citation") return; - editor.commands.focus(pos + current.nodeSize); + const current = pos === null ? null : editor.state.doc.nodeAt(pos); + if (pos === null || current?.type.name !== "composer-citation") { + if (sent) editor.view.focus(); + return; + } + // The send's controlled rewrite may still be pending; emitting this caret move would restore the old prompt. + editor + .chain() + .setMeta(SILENT_SELECTION_META, sent) + .focus(pos + current.nodeSize) + .run(); }; return ( @@ -525,7 +536,7 @@ function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) { onDraftChange: (comment) => commentContext.onDraftChange(citeKey, comment), onSaveAndSend: (comment) => { if (!onSaveComment(comment)) return false; - commentContext.onSubmitAndSend(); + sentRef.current = commentContext.onSubmitAndSend(); return true; }, onRestoreFocus, @@ -729,6 +740,8 @@ function chipSelectionDecorations({ doc, selection }: EditorState): DecorationSe type TiptapEditor = NonNullable>; +const SILENT_SELECTION_META = "composerSilentSelection"; + function replaceSkillChips( editor: TiptapEditor, replacements: ReturnType, @@ -995,10 +1008,10 @@ function ComposerPromptEditorTiptapInner( onDraftChange: (nodeKey: string, comment: string) => { citationDraftRef.current = { key: nodeKey, comment }; }, - onSubmitAndSend: onCitationSubmitAndSend ?? (() => {}), + onSubmitAndSend: onCitationSubmitAndSend ?? (() => false), }; - const handleEditorChange = (updated: TiptapEditor) => { + const handleEditorChange = (updated: TiptapEditor, transaction: Transaction) => { const map = serializeEditorDoc(updated.state.doc); const contextIds = literalText ? [] : [...map.contextIds]; const { from, to } = updated.state.selection; @@ -1025,7 +1038,7 @@ function ComposerPromptEditorTiptapInner( previousSnapshot.contextIds.length === contextIds.length && previousSnapshot.contextIds.every((id, index) => id === contextIds[index]) ); - if (isApplyingControlledUpdateRef.current) return; + if (isApplyingControlledUpdateRef.current || transaction.getMeta(SILENT_SELECTION_META)) return; if (!snapshotChanged) { if (didComposerSelectionChangeVisibly(previousSelectionRange, nextSelectionRange)) { readCallbacks().onVisibleSelectionChange?.(); @@ -1459,10 +1472,10 @@ function ComposerPromptEditorTiptapInner( return; } } - handleEditorChange(updated); + handleEditorChange(updated, transaction); }, - onSelectionUpdate: ({ editor: updated }) => { - handleEditorChange(updated); + onSelectionUpdate: ({ editor: updated, transaction }) => { + handleEditorChange(updated, transaction); }, }, [], diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index f722fd1eb6e1..cba7c434b1ba 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2096,7 +2096,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (voiceInputActive) { event?.preventDefault(); submitAfterDictation(() => submitComposerRef.current(dispatchMode, submissionIntent)); - return; + return false; } if ( noProviderAvailable || @@ -2104,7 +2104,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ) { event?.preventDefault(); - return; + return false; } // A send while a pasted image is still compressing would strand that image: // the turn snapshot wouldn't include it, and it would surface in the *next* @@ -2116,7 +2116,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) title: "Still compressing a pasted image.", description: "Send again once its thumbnail appears.", }); - return; + return false; } if (pendingDraftWork.has(attachmentTargetKey)) { event?.preventDefault(); @@ -2125,7 +2125,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) title: "Still bringing attached context into this message.", description: "Send again once its chip resolves.", }); - return; + return false; } const submission = submitComposerDraft({ prompt: promptRef.current, @@ -2148,11 +2148,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }, }); setComposerSubmissionError(submission.validationMessage); - if (!submission.didDispatch) return; + if (!submission.didDispatch) return false; onTypingGuardSend(); if (shouldBlurMobileComposerOnSubmit()) { blurMobileComposerAfterSend(); } + return true; }; const submitComposerStable = useStableCallback(submitComposer); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed submission handler to the asynchronous dictation completion @@ -2201,7 +2202,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const handleSubmitMessageStable = useStableCallback(handleSubmitMessage); const submitCitationAndSend = () => { - submitComposer( + return submitComposer( undefined, resolveComposerDispatchMode({ running: phase === "running", From 78201b07d0b68dc9d410c14a1a3fe13d0b20ed03 Mon Sep 17 00:00:00 2001 From: Muzammil Hussain <58479501+Muzammil-Bit@users.noreply.github.com> Date: Wed, 11 Nov 2026 02:33:26 +0500 Subject: [PATCH 037/170] fix(server): text generation fallback respects project provider settings (#33741) Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge --- apps/server/src/git/GitManager.ts | 5 +++ .../orchestration-v2/ThreadLaunchService.ts | 1 + .../ThreadTitleRegenerationService.ts | 1 + .../PullRequestReviewGuideService.ts | 1 + .../CodexTextGeneration.test.ts | 14 +++++++- .../src/textGeneration/TextGeneration.ts | 35 +++++++++++++------ .../src/server/textGeneration.ts | 6 ++++ 7 files changed, 52 insertions(+), 11 deletions(-) diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index d9e1d7d4c09e..db0d3c91ad19 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -114,6 +114,7 @@ export type GitBranchPullRequest = NonNullable & { interface SourceControlTextGenerationSettings { readonly modelSelection: ModelSelection; + readonly projectId: ProjectId | null; readonly style: SourceControlWritingStyleSettings; } @@ -2156,6 +2157,7 @@ export const make = Effect.gen(function* () { ...(input.includeBranch ? { includeBranch: true } : {}), ...(policy ? { policy } : {}), modelSelection: input.settings.modelSelection, + projectId: input.settings.projectId, }) .pipe(Effect.map((result) => sanitizeCommitMessage(result))); @@ -2386,6 +2388,7 @@ export const make = Effect.gen(function* () { ...(threadContext ? { threadContext } : {}), ...(policy ? { policy } : {}), modelSelection: settings.modelSelection, + projectId: settings.projectId, }); const bodyFile = path.join( @@ -3231,6 +3234,7 @@ export const make = Effect.gen(function* () { settings.sourceControlWriterModelSelection === null ? Effect.succeed({ modelSelection: settings.textGenerationModelSelection, + projectId, style: settings.sourceControlWritingStyle, }) : providerRegistry.getProviders.pipe( @@ -3240,6 +3244,7 @@ export const make = Effect.gen(function* () { providers, projectId, ), + projectId, style: settings.sourceControlWritingStyle, })), ), diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 7e7829ba947c..6397bfdb3bc7 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -361,6 +361,7 @@ const make = Effect.gen(function* () { attachments: message.attachments, ...(message.context ? { context: message.context } : {}), modelSelection, + projectId: input.projectId, }) .pipe( Effect.map((result) => ({ diff --git a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts index 6c80def39059..395e8768996e 100644 --- a/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts +++ b/apps/server/src/orchestration-v2/ThreadTitleRegenerationService.ts @@ -175,6 +175,7 @@ const make = Effect.gen(function* () { ...(inherited === undefined ? {} : { forkSource: inherited }), instructions: settings.threadTitleInstructions, modelSelection: settings.textGenerationModelSelection, + projectId: projection.thread.projectId, }); const generatedTitle = result.title.trim(); return generatedTitle === "New thread" || diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts index 8994837fcdd8..450d42ebc3cb 100644 --- a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts +++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts @@ -403,6 +403,7 @@ const make = Effect.gen(function* () { ...reviewGuideInputFromPullRequest(detail, activity, checkout.baseCommit), cwd: checkout.path, modelSelection, + projectId: input.projectId, instructions: projectSettings.reviewGuideInstructions, stack: checkout.stack, }), diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index 40fd6e7eed9c..86c6cb9a8cfe 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -1,5 +1,6 @@ import { DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER, + ProjectId, ProviderDriverKind, type ModelSelection, type ServerProvider, @@ -542,6 +543,7 @@ const PREFLIGHT_PRIMARY_STATES = [ "pending", "exhausted", "not installed", + "not installed, fallback disabled for project", "signed out", "signed out, fallback failed", ] as const; @@ -550,6 +552,7 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima Effect.gen(function* () { const primary = ProviderInstanceId.make("codex"); const fallback = ProviderInstanceId.make("claude_work"); + const projectId = ProjectId.make("project-a"); const selection = { instanceId: primary, model: "chat-model", @@ -573,7 +576,7 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima ...(primaryState === "pending" && instanceId === primary ? { installed: false, status: "warning", auth: { status: "unknown" } } : {}), - ...(primaryState === "not installed" && instanceId === primary + ...(primaryState.startsWith("not installed") && instanceId === primary ? { installed: false, status: "error", auth: { status: "unknown" } } : {}), ...(primaryState.startsWith("signed out") && instanceId === primary @@ -625,6 +628,13 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima providerInstances: { [fallback]: { driver: ProviderDriverKind.make("claudeAgent"), config: {} }, }, + ...(primaryState === "not installed, fallback disabled for project" + ? { + projectSettingsOverrides: { + [projectId]: { providerInstances: { [fallback]: { enabled: false } } }, + }, + } + : {}), }), Layer.mock(TextGenerators.TextGenerators)({ runner: () => Effect.undefined }), Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ @@ -639,11 +649,13 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima message: "hello", linkedContext: "", modelSelection: selection, + projectId, }), ).toEqual({ title: "Generated title" }); expect(calls).toEqual([ primaryState === "ready" || primaryState === "pending" || + primaryState === "not installed, fallback disabled for project" || primaryState === "signed out, fallback failed" ? selection : { diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.ts index fcdddd2052d8..612d473071bc 100644 --- a/apps/server/src/textGeneration/TextGeneration.ts +++ b/apps/server/src/textGeneration/TextGeneration.ts @@ -1,7 +1,7 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import type { ModelSelection, ProviderInstanceId } from "@t3tools/contracts"; +import type { ModelSelection, ProjectId, ProviderInstanceId } from "@t3tools/contracts"; import { isProviderAvailable, isProviderTextGenerationCapable, @@ -81,6 +81,7 @@ export const make = Effect.gen(function* () { const generate = Effect.fn("TextGeneration.generate")(function* ( operation: TextGenerationOp, selection: ModelSelection, + projectId: ProjectId | null | undefined, invoke: ( service: ProviderTextGeneration, modelSelection: ModelSelection, @@ -129,7 +130,7 @@ export const make = Effect.gen(function* () { return ( instanceId !== selection.instanceId && provider?.enabled === true && - resolveProjectProviderInstanceEnabled(settings, null, instanceId) && + resolveProjectProviderInstanceEnabled(settings, projectId ?? null, instanceId) && provider.installed && provider.auth.status !== "unauthenticated" && provider.status !== "error" && @@ -155,23 +156,35 @@ export const make = Effect.gen(function* () { }); return TextGeneration.of({ generateCommitMessage: Effect.fn("TextGeneration.generateCommitMessage")(function (input) { - return generate("generateCommitMessage", input.modelSelection, (service, modelSelection) => - service.generateCommitMessage({ ...input, modelSelection }), + return generate( + "generateCommitMessage", + input.modelSelection, + input.projectId, + (service, modelSelection) => service.generateCommitMessage({ ...input, modelSelection }), ); }), generatePrContent: Effect.fn("TextGeneration.generatePrContent")(function (input) { - return generate("generatePrContent", input.modelSelection, (service, modelSelection) => - service.generatePrContent({ ...input, modelSelection }), + return generate( + "generatePrContent", + input.modelSelection, + input.projectId, + (service, modelSelection) => service.generatePrContent({ ...input, modelSelection }), ); }), generateBranchName: Effect.fn("TextGeneration.generateBranchName")(function (input) { - return generate("generateBranchName", input.modelSelection, (service, modelSelection) => - service.generateBranchName({ ...input, modelSelection }), + return generate( + "generateBranchName", + input.modelSelection, + input.projectId, + (service, modelSelection) => service.generateBranchName({ ...input, modelSelection }), ); }), generateReviewGuide: Effect.fn("TextGeneration.generateReviewGuide")(function (input) { - return generate("generateReviewGuide", input.modelSelection, (service, modelSelection) => - service.generateReviewGuide({ ...input, modelSelection }), + return generate( + "generateReviewGuide", + input.modelSelection, + input.projectId, + (service, modelSelection) => service.generateReviewGuide({ ...input, modelSelection }), ); }), generateTranscriptionPostProcessing: Effect.fn( @@ -180,6 +193,7 @@ export const make = Effect.gen(function* () { return generate( "generateTranscriptionPostProcessing", input.modelSelection, + null, (service, modelSelection) => service.generateTranscriptionPostProcessing({ ...input, modelSelection }), ); @@ -188,6 +202,7 @@ export const make = Effect.gen(function* () { return generate( "generateThreadTitle", input.modelSelection, + input.projectId, (textGeneration, modelSelection) => Effect.gen(function* () { const linkedContext = diff --git a/packages/provider-core/src/server/textGeneration.ts b/packages/provider-core/src/server/textGeneration.ts index 62369d754aba..5e6600f31809 100644 --- a/packages/provider-core/src/server/textGeneration.ts +++ b/packages/provider-core/src/server/textGeneration.ts @@ -2,6 +2,7 @@ import type { BranchNamingOptions, ChatAttachment, ModelSelection, + ProjectId, PullRequestReviewGuide, TextGenerationError, } from "@t3tools/contracts"; @@ -18,6 +19,7 @@ export interface CommitMessageGenerationInput { includeBranch?: boolean; policy?: TextGenerationPolicy | undefined; modelSelection: ModelSelection; + projectId?: ProjectId | null | undefined; } export interface CommitMessageGenerationResult { @@ -37,6 +39,7 @@ export interface PrContentGenerationInput { threadContext?: string | undefined; policy?: TextGenerationPolicy | undefined; modelSelection: ModelSelection; + projectId?: ProjectId | null | undefined; } export interface PrContentGenerationResult { @@ -50,6 +53,7 @@ export interface BranchNameGenerationInput { message: string; attachments?: ReadonlyArray | undefined; modelSelection: ModelSelection; + projectId?: ProjectId | null | undefined; } export interface BranchNameGenerationResult { @@ -65,6 +69,7 @@ export interface ThreadTitleGenerationInput { attachments?: ReadonlyArray | undefined; instructions?: string | undefined; modelSelection: ModelSelection; + projectId?: ProjectId | null | undefined; } export interface ThreadTitleGenerationResult { @@ -90,6 +95,7 @@ export interface ReviewGuideGenerationInput { instructions?: string | undefined; stack?: ReadonlyArray | undefined; modelSelection: ModelSelection; + projectId?: ProjectId | null | undefined; } export type ReviewGuideGenerationResult = Omit< From 44ebb2fe57465d32f2bd07c5eb3d8e871bdf5ed5 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:36:21 +0100 Subject: [PATCH 038/170] feat(usage): show Muse Code limits, and xAI and Antigravity accounts from a CLIProxyAPI hub (#33800) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../features/threads/ComposerUsageLimits.tsx | 5 +- .../src/features/usage/UsageLimitsPooled.tsx | 15 +- .../src/provider/antigravityUsageLimits.ts | 39 +- apps/server/src/usage/cliproxyApi.test.ts | 198 ++++++++- apps/server/src/usage/cliproxyApi.ts | 391 ++++++++++++------ .../test/fixtures/usage-limits-hub/README.md | 21 +- .../test/fixtures/usage-limits-hub/hub.mjs | 35 +- .../fixtures/usage-limits-hub/scenarios.json | 86 ++++ docs/user/usage.md | 6 +- .../src/server/managedProvider.test.ts | 111 ++++- .../src/server/managedProvider.ts | 83 +++- packages/provider-core/src/server/snapshot.ts | 14 +- packages/provider-grok/src/server.ts | 5 + .../provider-grok/src/server/usageLimits.ts | 7 +- .../provider-muse/src/server/adapter.test.ts | 30 +- packages/provider-muse/src/server/adapter.ts | 12 +- .../provider-muse/src/server/driver.test.ts | 216 ++++++++++ packages/provider-muse/src/server/driver.ts | 38 +- .../src/server/usageLimits.test.ts | 34 +- .../provider-muse/src/server/usageLimits.ts | 33 +- packages/shared/src/usageLimits.test.ts | 39 ++ 21 files changed, 1201 insertions(+), 217 deletions(-) create mode 100644 packages/provider-muse/src/server/driver.test.ts diff --git a/apps/mobile/src/features/threads/ComposerUsageLimits.tsx b/apps/mobile/src/features/threads/ComposerUsageLimits.tsx index ef39ef51ff4c..49f43cc2161b 100644 --- a/apps/mobile/src/features/threads/ComposerUsageLimits.tsx +++ b/apps/mobile/src/features/threads/ComposerUsageLimits.tsx @@ -1,3 +1,4 @@ +import { providerClients } from "@t3tools/client-runtime/provider-clients"; import type { EnvironmentId, UsageLimitsReport } from "@t3tools/contracts"; import { Pressable, ScrollView, View } from "react-native"; @@ -5,8 +6,6 @@ import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { AccountLimits, ResetCredits } from "../usage/UsageLimitsSection"; -const DRIVER_LABEL: Partial> = { codex: "Codex", claudeAgent: "Claude" }; - export function ComposerUsageLimits({ report, environmentId, @@ -37,7 +36,7 @@ export function ComposerUsageLimits({ const resetCreditInput = account.resetCreditInput ?? (account.instanceId ? { instanceId: account.instanceId } : undefined); - const driverLabel = DRIVER_LABEL[account.driver] ?? String(account.driver); + const driverLabel = providerClients.get(account.driver)?.label ?? account.driver; return ( > = { - codex: "Codex", - claudeAgent: "Claude", - grok: "Grok", - antigravity: "Antigravity", -}; const PACE_LABEL = { ahead: "Ahead of pace", on: "On pace", under: "Under pace" } as const; function accountName(account: LimitAccount) { if (account.displayName) return account.displayName; - if (!account.email) return DRIVER_LABEL[account.driver] ?? String(account.driver); + if (!account.email) return providerClients.get(account.driver)?.label ?? account.driver; return emailInitials(account.email) || "Account"; } @@ -444,7 +439,7 @@ export function UsageLimitsSection({ - {DRIVER_LABEL[pool.driver] ?? pool.driver} + {providerClients.get(pool.driver)?.label ?? pool.driver} {windows.map((window) => { @@ -559,7 +554,9 @@ export function UsageLimitAccountScreen({ route }: AccountScreenProps) { - {account.displayName ?? DRIVER_LABEL[account.driver] ?? account.driver} + {account.displayName ?? + providerClients.get(account.driver)?.label ?? + account.driver} {account.email ? ( diff --git a/apps/server/src/provider/antigravityUsageLimits.ts b/apps/server/src/provider/antigravityUsageLimits.ts index da21333dad95..ede0e5c47d20 100644 --- a/apps/server/src/provider/antigravityUsageLimits.ts +++ b/apps/server/src/provider/antigravityUsageLimits.ts @@ -15,6 +15,10 @@ import { makeUsageLimits, } from "@t3tools/provider-core/server/usageLimits"; +export function antigravityUserAgent(platform: NodeJS.Platform, architecture: NodeJS.Architecture) { + return `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`; +} + const DAILY_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com"; const PROD_ENDPOINT = "https://cloudcode-pa.googleapis.com"; // The ACP runtime meters consumer tiers on the daily host and GCP-terms tiers on prod. @@ -120,6 +124,22 @@ function summaryResetTime( return untouched ? undefined : bucket.resetTime; } +const sha256 = Effect.fnUntraced(function* (text: string) { + const digest = yield* (yield* Digest.Digest).digest( + Digest.sha256, + new TextEncoder().encode(text), + ); + return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(""); +}); + +/** Keys an account by its Google ID, which matches across machines and hubs; refresh tokens do not. */ +export const antigravityAccountFingerprint = (userInfo: unknown) => + decodeUserInfo(userInfo).pipe(Effect.flatMap((info) => sha256(`google-account\0${info.id}`))); + +/** Windows from a `retrieveUserQuotaSummary` answer requested at `requestedAt`. */ +export const antigravitySummaryWindows = (response: unknown, requestedAt: number) => + decodeSummary(response).pipe(Effect.map((summary) => summaryWindows(summary, requestedAt))); + function summaryWindows(summary: typeof Summary.Type, requestedAt: number) { const windows = new Map(); const groups = summary.groups?.some((group) => group.buckets?.length) @@ -203,15 +223,6 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( | undefined; let generation = 0; - const sha256 = (text: string) => - crypto - .digest(Digest.sha256, new TextEncoder().encode(text)) - .pipe( - Effect.map((digest) => - Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join(""), - ), - ); - const request = (request: HttpClientRequest.HttpClientRequest) => client.execute(request).pipe( Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT), @@ -259,8 +270,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), ), ).pipe( - Effect.flatMap(decodeUserInfo), - Effect.flatMap((info) => sha256(`google-account\0${info.id}`)), + Effect.flatMap(antigravityAccountFingerprint), Effect.orElseSucceed(() => fingerprint), ); if (generation === startedGeneration) { @@ -294,7 +304,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( HttpClientRequest.post(`${endpoint}/v1internal:${operation}`).pipe( HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}`, - "User-Agent": `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`, + "User-Agent": antigravityUserAgent(platform, architecture), }), HttpClientRequest.bodyJsonUnsafe( token.project_id ? { project: token.project_id } : {}, @@ -313,9 +323,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( } return [...windows.values()]; }); - const summary = yield* fetchWindows("retrieveUserQuotaSummary", (response, requestedAt) => - decodeSummary(response).pipe(Effect.map((summary) => summaryWindows(summary, requestedAt))), - ); + const summary = yield* fetchWindows("retrieveUserQuotaSummary", antigravitySummaryWindows); const windows = summary.length ? summary : yield* fetchWindows("fetchAvailableModels", (response) => @@ -331,6 +339,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( return { ...makeUsageLimits({ checkedAt, windows }), credentialFingerprint: account }; }); const probe = read.pipe( + Effect.provideService(Digest.Digest, crypto), Effect.timeout("30 seconds"), Effect.catch(() => Effect.gen(function* () { diff --git a/apps/server/src/usage/cliproxyApi.test.ts b/apps/server/src/usage/cliproxyApi.test.ts index b9f357522bb7..431af7b5971f 100644 --- a/apps/server/src/usage/cliproxyApi.test.ts +++ b/apps/server/src/usage/cliproxyApi.test.ts @@ -1,4 +1,5 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -48,12 +49,15 @@ const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); function fixture( options: { - accounts?: Array< - (typeof accounts)[number] & { - disabled?: boolean; - id_token: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string }; - } - >; + accounts?: Array<{ + id: string; + auth_index: string; + provider: string; + email?: string; + disabled?: boolean; + project_id?: string; + id_token?: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string }; + }>; upstream?: (request: RequestBody) => { status: number; body: unknown }; cooldownStatus?: number; } = {}, @@ -433,6 +437,188 @@ describe("CLIProxyAPI built-in management API", () => { }), ); + const antigravitySummary = { + buckets: [ + { + bucketId: "gemini-weekly", + window: "weekly", + remainingFraction: 0.75, + resetTime: "2099-01-01T00:00:00Z", + }, + ], + }; + + it.effect("reads an xAI account as Grok with Grok CLI headers", () => + Effect.gen(function* () { + const test = fixture({ + accounts: [{ id: "xai.json", auth_index: "x", provider: "xai", email: "x@example.com" }], + upstream: () => ({ + status: 200, + body: { + config: { + creditUsagePercent: 40, + currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY", end: "2099-01-01T00:00:00Z" }, + }, + }, + }), + }); + const [account] = yield* (yield* test.api).readAccounts(config); + expect(account).toMatchObject({ driver: "grok", email: "x@example.com" }); + expect(account?.usageLimits.windows).toMatchObject([ + { id: "subscription", kind: "weekly", usedPercent: 40 }, + ]); + const call = test.requests.find((request) => request.body?.url)?.body; + expect(call?.method).toBe("GET"); + expect(call?.url).toBe("https://cli-chat-proxy.grok.com/v1/billing?format=credits"); + expect(call?.header).toMatchObject({ + "x-xai-token-auth": "xai-grok-cli", + "x-grok-client-version": expect.any(String), + "User-Agent": expect.stringMatching(/^grok-cli\//), + }); + }), + ); + + it.effect("reads an Antigravity summary and keys the account by its Google ID", () => + Effect.gen(function* () { + const test = fixture({ + accounts: [ + { + id: "antigravity-g@example.com.json", + auth_index: "g", + provider: "antigravity", + email: "g@example.com", + project_id: "project-7", + }, + ], + upstream: (request) => ({ + status: 200, + body: request.url?.endsWith("/userinfo") ? { id: "google-42" } : antigravitySummary, + }), + }); + const [account] = yield* (yield* test.api).readAccounts(config); + expect(account?.driver).toBe("antigravity"); + expect(account?.email).toBeUndefined(); + expect(account?.usageLimits.credentialFingerprint).toBe( + // sha256("google-account\0google-42"), as a local Antigravity probe reports it. + "136d4952771fd67a3600053f37492cbd05828712e0b1c89ebab03d4c22ab6554", + ); + expect(account?.usageLimits.windows).toMatchObject([ + { id: "gemini-weekly", kind: "weekly", usedPercent: 25 }, + ]); + const summary = test.requests.find((request) => request.body?.method === "POST")?.body; + expect(summary?.url).toBe( + "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary", + ); + expect(summary?.data).toBe(encodeJson({ project: "project-7" })); + expect(summary).toMatchObject({ + auth_index: "g", + method: "POST", + header: { + Authorization: "Bearer $TOKEN$", + "Content-Type": "application/json", + "User-Agent": + "antigravity/hub/2.24.0 (aidev_client; os_type=linux; arch=x64; cl=963137146)", + }, + }); + const identityCalls = test.requests.filter((request) => + request.body?.url?.endsWith("/userinfo"), + ); + expect(identityCalls).toHaveLength(1); + expect(identityCalls[0]?.body).toMatchObject({ + method: "GET", + url: "https://www.googleapis.com/oauth2/v2/userinfo", + header: { Authorization: "Bearer $TOKEN$" }, + }); + }).pipe( + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Architecture, "x64"), + ), + ); + + it.effect("keeps Antigravity limits and listing email when its identity read fails", () => + Effect.gen(function* () { + const test = fixture({ + accounts: [ + { + id: "antigravity.json", + auth_index: "g", + provider: "antigravity", + email: "g@example.com", + project_id: "project-7", + }, + ], + upstream: (request) => + request.url?.endsWith("/userinfo") + ? { status: 403, body: { error: "denied" } } + : { + status: 200, + body: antigravitySummary, + }, + }); + const result = yield* (yield* test.api).readAccounts(config); + expect(result).toHaveLength(1); + const [account] = result; + expect(account).toMatchObject({ driver: "antigravity", email: "g@example.com" }); + expect(account?.usageLimits.credentialFingerprint).toBeUndefined(); + expect(account?.usageLimits.unavailable).toBeUndefined(); + expect(account?.usageLimits.windows).toMatchObject([ + { id: "gemini-weekly", kind: "weekly", usedPercent: 25 }, + ]); + }), + ); + + it.effect.each([ + { name: "a refused xAI call", provider: "xai", status: 403, body: { error: "denied" } }, + { name: "a malformed xAI answer", provider: "xai", status: 200, body: { config: "x" } }, + { name: "a refused Antigravity call", provider: "antigravity", status: 401, body: {} }, + { name: "a malformed Antigravity answer", provider: "antigravity", status: 200, body: [] }, + { name: "an empty Antigravity summary", provider: "antigravity", status: 200, body: {} }, + ])("reports $name as unreadable", ({ provider, status, body }) => + Effect.gen(function* () { + const test = fixture({ + accounts: [{ id: `${provider}.json`, auth_index: "a", provider, project_id: "project-7" }], + upstream: () => ({ status, body }), + }); + const [account] = yield* (yield* test.api).readAccounts(config); + expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed"); + }), + ); + + it.effect.each([undefined, "", " "])( + "rejects a missing or blank Antigravity project (%s) before upstream calls", + (project_id) => + Effect.gen(function* () { + const test = fixture({ + accounts: [ + { + id: "antigravity.json", + auth_index: "a", + provider: "antigravity", + ...(project_id === undefined ? {} : { project_id }), + }, + ], + }); + const [account] = yield* (yield* test.api).readAccounts(config); + expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed"); + expect(test.requests.map((request) => request.path)).toEqual(["/v0/management/auth-files"]); + }), + ); + + it.effect("skips accounts of providers the hub table does not know", () => + Effect.gen(function* () { + const test = fixture({ + accounts: [ + { id: "kiro.json", auth_index: "k", provider: "kiro", email: "k@example.com" }, + { ...accounts[0]!, provider: "claude" }, + ], + upstream: () => ({ status: 200, body: { five_hour: { utilization: 1, resets_at: null } } }), + }); + const result = yield* (yield* test.api).readAccounts(config); + expect(result.map((account) => account.driver)).toEqual(["claudeAgent"]); + expect(test.requests.map((request) => request.body?.auth_index)).not.toContain("k"); + }), + ); + it.effect("pins redemption to the displayed credit and clears only that account's cooldown", () => Effect.gen(function* () { const test = fixture(); diff --git a/apps/server/src/usage/cliproxyApi.ts b/apps/server/src/usage/cliproxyApi.ts index 87ec1e05b8f7..030983f50e33 100644 --- a/apps/server/src/usage/cliproxyApi.ts +++ b/apps/server/src/usage/cliproxyApi.ts @@ -5,18 +5,33 @@ import { type UsageLimitSourceAccount, type UsageLimitSourceConfig, } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { + GROK_USAGE_URL, + GrokUsageResponse, + grokUsageResponseToLimits, +} from "@t3tools/provider-grok/server"; import { codexPlanLabel } from "../provider/CodexProvider.ts"; import { codexRateLimitsToLimits } from "../provider/codexUsageLimits.ts"; import { claudeUsageResponseToLimits } from "../provider/claudeUsageLimits.ts"; -import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits"; +import { + antigravityAccountFingerprint, + antigravitySummaryWindows, + antigravityUserAgent, +} from "../provider/antigravityUsageLimits.ts"; +import { + makeUnavailableUsageLimits, + makeUsageLimits, +} from "@t3tools/provider-core/server/usageLimits"; /** A hub with its management key already read from wherever the setting keeps it. */ export interface CliproxyHub { @@ -30,6 +45,7 @@ const AuthFile = Schema.Struct({ provider: Schema.String, email: Schema.optional(Schema.String), disabled: Schema.optional(Schema.Boolean), + project_id: Schema.optional(Schema.String), id_token: Schema.optional( Schema.Struct({ chatgpt_account_id: Schema.optional(Schema.String), @@ -106,6 +122,8 @@ const decodeApiResponse = Schema.decodeUnknownEffect(ApiResponse); const decodeCreditList = Schema.decodeUnknownEffect(Schema.fromJsonString(CreditList)); const decodeClaudeUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(ClaudeUsage)); const decodeCodexUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(CodexUsage)); +const decodeGrokUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(GrokUsageResponse)); +const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); const isUsageLimitSourceError = Schema.is(UsageLimitSourceError); // Extra CAs can fix untrusted chains; expiry/hostname failures report codes only. @@ -174,9 +192,216 @@ const creditRedeemRequestId = Effect.fn("CliproxyApi.creditRedeemRequestId")(fun return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; }); +type AuthFile = typeof AuthFile.Type; +/** Sends one upstream request with the account's token, as GET or as a JSON POST of `data`. */ +type HubCall = ( + url: string, + data?: unknown, +) => Effect.Effect; +type HubReading = Omit; +interface HubProvider { + readonly driver: ProviderDriverKind; + readonly header: ( + account: AuthFile, + platform: NodeJS.Platform, + architecture: NodeJS.Architecture, + ) => Record; + readonly read: (input: { + readonly account: AuthFile; + readonly call: HubCall; + readonly checkedAt: string; + }) => Effect.Effect; +} + +const listedIdentity = (account: AuthFile) => ({ + ...(account.email ? { email: account.email } : {}), + ...(account.id_token?.chatgpt_account_id?.trim() + ? { workspaceId: account.id_token.chatgpt_account_id.trim() } + : {}), +}); + +const credits = Effect.fn("CliproxyApi.credits")(function* (call: HubCall) { + const response = yield* decodeCreditList(yield* call(CREDIT_URL)); + const now = DateTime.toEpochMillis(yield* DateTime.now); + return response.credits + .filter( + (credit) => + credit.reset_type === "codex_rate_limits" && + credit.status === "available" && + Date.parse(credit.expires_at) > now, + ) + .toSorted((a, b) => Date.parse(a.expires_at) - Date.parse(b.expires_at)); +}); + +const CODEX_HUB: HubProvider = { + driver: ProviderDriverKind.make("codex"), + header: (account) => ({ + Authorization: "Bearer $TOKEN$", + "Content-Type": "application/json", + "OpenAI-Beta": "codex-1", + Originator: "Codex Desktop", + ...(account.id_token?.chatgpt_account_id + ? { "Chatgpt-Account-Id": account.id_token.chatgpt_account_id } + : {}), + }), + read: Effect.fnUntraced(function* ({ account, call, checkedAt }) { + const usage = yield* decodeCodexUsage(yield* call(`${CODEX_BASE}/usage`)); + const toWindow = (window: typeof CodexWindow.Type | null | undefined) => + window + ? { + usedPercent: window.used_percent, + resetsAt: window.reset_at ?? null, + ...(window.limit_window_seconds === undefined + ? {} + : { windowDurationMins: window.limit_window_seconds / 60 }), + } + : null; + const available = yield* credits(call).pipe(Effect.orElseSucceed(() => undefined)); + const next = available?.[0]; + const planType = + usage.plan_type ?? account.id_token?.plan_type ?? account.id_token?.chatgpt_plan_type; + return { + ...listedIdentity(account), + plan: codexPlanLabel(planType), + usageLimits: { + ...codexRateLimitsToLimits({ + checkedAt, + snapshot: { + planType: planType ?? null, + primary: toWindow(usage.rate_limit?.primary_window), + secondary: toWindow(usage.rate_limit?.secondary_window), + }, + }), + ...(available + ? { + resetCredits: { + availableCount: available.length, + ...(next + ? { + nextCreditId: next.id, + nextExpiresAt: DateTime.formatIso(DateTime.makeUnsafe(next.expires_at)), + } + : {}), + }, + } + : {}), + }, + }; + }), +}; + +const GROK_CLI_VERSION = "1.0.77"; +const ANTIGRAVITY_SUMMARY_URL = + "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary"; + +// Keyed by the auth-files `provider`; accounts of any other provider are skipped. +const HUB_PROVIDERS = new Map([ + ["codex", CODEX_HUB], + [ + "claude", + { + driver: ProviderDriverKind.make("claudeAgent"), + header: () => ({ + Authorization: "Bearer $TOKEN$", + "anthropic-beta": "oauth-2025-04-20", + // The OAuth usage endpoint can return 429 without a Claude Code user agent. + "User-Agent": "claude-code/2.1.273", + }), + read: Effect.fnUntraced(function* ({ account, call, checkedAt }) { + const usage = yield* decodeClaudeUsage( + yield* call("https://api.anthropic.com/api/oauth/usage"), + ); + const model_scoped = (usage.limits ?? []).flatMap((limit) => + limit.kind === "weekly_scoped" && limit.scope?.model && typeof limit.percent === "number" + ? [ + { + display_name: limit.scope.model.display_name, + utilization: limit.percent, + resets_at: limit.resets_at ?? null, + }, + ] + : [], + ); + const rateLimits = { + five_hour: usage.five_hour ?? null, + seven_day: usage.seven_day ?? null, + model_scoped, + spend: usage.spend, + extra_usage: usage.extra_usage ?? null, + }; + return { + ...listedIdentity(account), + plan: "Claude Subscription", + usageLimits: claudeUsageResponseToLimits({ + checkedAt, + response: { rate_limits_available: true, rate_limits: rateLimits }, + }).limits, + }; + }), + }, + ], + [ + "xai", + { + driver: ProviderDriverKind.make("grok"), + header: () => ({ + Authorization: "Bearer $TOKEN$", + "x-xai-token-auth": "xai-grok-cli", + "x-grok-client-version": GROK_CLI_VERSION, + "User-Agent": `grok-cli/${GROK_CLI_VERSION}`, + }), + read: Effect.fnUntraced(function* ({ account, call, checkedAt }) { + const usage = yield* decodeGrokUsage(yield* call(GROK_USAGE_URL)); + return { + ...listedIdentity(account), + usageLimits: grokUsageResponseToLimits(usage, checkedAt), + }; + }), + }, + ], + [ + "antigravity", + { + driver: ProviderDriverKind.make("antigravity"), + header: (_account, platform, architecture) => ({ + Authorization: "Bearer $TOKEN$", + "Content-Type": "application/json", + "User-Agent": antigravityUserAgent(platform, architecture), + }), + read: Effect.fnUntraced(function* ({ account, call, checkedAt }) { + const project = account.project_id?.trim(); + if (!project) { + return yield* new UsageLimitSourceError({ detail: "No Antigravity project reported." }); + } + const requestedAt = DateTime.toEpochMillis(yield* DateTime.now); + const summary = yield* call(ANTIGRAVITY_SUMMARY_URL, { project }); + const windows = yield* antigravitySummaryWindows(yield* decodeJson(summary), requestedAt); + if (windows.length === 0) { + return yield* new UsageLimitSourceError({ detail: "No Antigravity quota reported." }); + } + // Local Antigravity reports no e-mail, so the Google account fingerprint is what pools the two. + const fingerprint = yield* call("https://www.googleapis.com/oauth2/v2/userinfo").pipe( + Effect.flatMap(decodeJson), + Effect.flatMap(antigravityAccountFingerprint), + Effect.option, + ); + const usageLimits = makeUsageLimits({ checkedAt, windows }); + return Option.match(fingerprint, { + onNone: () => ({ ...listedIdentity(account), usageLimits }), + onSome: (credentialFingerprint) => ({ + usageLimits: { ...usageLimits, credentialFingerprint }, + }), + }); + }), + }, + ], +]); + export const makeCliproxyApi = Effect.gen(function* () { const client = yield* HttpClient.HttpClient; const digest = yield* Digest.Digest; + const platform = yield* HostProcess.Platform; + const architecture = yield* HostProcess.Architecture; const management = Effect.fn("CliproxyApi.management")(function* ( hub: CliproxyHub, @@ -215,27 +440,11 @@ export const makeCliproxyApi = Effect.gen(function* () { const apiCall = Effect.fn("CliproxyApi.apiCall")(function* ( hub: CliproxyHub, - account: typeof AuthFile.Type, + account: AuthFile, + header: Record, url: string, data?: unknown, ) { - const header = - account.provider === "codex" - ? { - Authorization: "Bearer $TOKEN$", - "Content-Type": "application/json", - "OpenAI-Beta": "codex-1", - Originator: "Codex Desktop", - ...(account.id_token?.chatgpt_account_id - ? { "Chatgpt-Account-Id": account.id_token.chatgpt_account_id } - : {}), - } - : { - Authorization: "Bearer $TOKEN$", - "anthropic-beta": "oauth-2025-04-20", - // The OAuth usage endpoint can return 429 without a Claude Code user agent. - "User-Agent": "claude-code/2.1.273", - }; const raw = yield* management(hub, "api-call", { auth_index: account.auth_index, method: data === undefined ? "GET" : "POST", @@ -252,117 +461,18 @@ export const makeCliproxyApi = Effect.gen(function* () { return response.body; }); - const credits = Effect.fn("CliproxyApi.credits")(function* ( - hub: CliproxyHub, - account: typeof AuthFile.Type, - ) { - const body = yield* apiCall(hub, account, CREDIT_URL); - const response = yield* decodeCreditList(body); - const now = DateTime.toEpochMillis(yield* DateTime.now); - return response.credits - .filter( - (credit) => - credit.reset_type === "codex_rate_limits" && - credit.status === "available" && - Date.parse(credit.expires_at) > now, - ) - .toSorted((a, b) => Date.parse(a.expires_at) - Date.parse(b.expires_at)); - }); - const readAccount = Effect.fn("CliproxyApi.readAccount")(function* ( hub: CliproxyHub, - account: typeof AuthFile.Type, + account: AuthFile, + provider: HubProvider, ) { const checkedAt = DateTime.formatIso(yield* DateTime.now); - const base = { - id: account.id, - driver: ProviderDriverKind.make(account.provider === "codex" ? "codex" : "claudeAgent"), - ...(account.email ? { email: account.email } : {}), - ...(account.id_token?.chatgpt_account_id?.trim() - ? { workspaceId: account.id_token.chatgpt_account_id.trim() } - : {}), - }; - const read = Effect.gen(function* () { - if (account.provider === "claude") { - const body = yield* apiCall(hub, account, "https://api.anthropic.com/api/oauth/usage"); - const usage = yield* decodeClaudeUsage(body); - const model_scoped = (usage.limits ?? []).flatMap((limit) => - limit.kind === "weekly_scoped" && limit.scope?.model && typeof limit.percent === "number" - ? [ - { - display_name: limit.scope.model.display_name, - utilization: limit.percent, - resets_at: limit.resets_at ?? null, - }, - ] - : [], - ); - const rateLimits = { - five_hour: usage.five_hour ?? null, - seven_day: usage.seven_day ?? null, - model_scoped, - spend: usage.spend, - extra_usage: usage.extra_usage ?? null, - }; - return { - ...base, - plan: "Claude Subscription", - usageLimits: claudeUsageResponseToLimits({ - checkedAt, - response: { - rate_limits_available: true, - rate_limits: rateLimits, - }, - }).limits, - }; - } - const body = yield* apiCall(hub, account, `${CODEX_BASE}/usage`); - const usage = yield* decodeCodexUsage(body); - const toWindow = (window: typeof CodexWindow.Type | null | undefined) => - window - ? { - usedPercent: window.used_percent, - resetsAt: window.reset_at ?? null, - ...(window.limit_window_seconds === undefined - ? {} - : { windowDurationMins: window.limit_window_seconds / 60 }), - } - : null; - const available = yield* credits(hub, account).pipe(Effect.orElseSucceed(() => undefined)); - const next = available?.[0]; - const planType = - usage.plan_type ?? account.id_token?.plan_type ?? account.id_token?.chatgpt_plan_type; - return { - ...base, - plan: codexPlanLabel(planType), - usageLimits: { - ...codexRateLimitsToLimits({ - checkedAt, - snapshot: { - planType: planType ?? null, - primary: toWindow(usage.rate_limit?.primary_window), - secondary: toWindow(usage.rate_limit?.secondary_window), - }, - }), - ...(available - ? { - resetCredits: { - availableCount: available.length, - ...(next - ? { - nextCreditId: next.id, - nextExpiresAt: DateTime.formatIso(DateTime.makeUnsafe(next.expires_at)), - } - : {}), - }, - } - : {}), - }, - }; - }); - return yield* read.pipe( + const call: HubCall = (url, data) => + apiCall(hub, account, provider.header(account, platform, architecture), url, data); + const reading = yield* provider.read({ account, call, checkedAt }).pipe( + Effect.provideService(Digest.Digest, digest), Effect.orElseSucceed(() => ({ - ...base, + ...listedIdentity(account), usageLimits: makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed", @@ -370,6 +480,7 @@ export const makeCliproxyApi = Effect.gen(function* () { }), })), ); + return { id: account.id, driver: provider.driver, ...reading }; }); const readAccounts = Effect.fn("CliproxyApi.readAccounts")(function* ( @@ -383,11 +494,11 @@ export const makeCliproxyApi = Effect.gen(function* () { ), ); return yield* Effect.forEach( - accounts.filter( - (account) => - !account.disabled && (account.provider === "codex" || account.provider === "claude"), - ), - (account) => readAccount(hub, account), + accounts.flatMap((account) => { + const provider = HUB_PROVIDERS.get(account.provider); + return provider && !account.disabled ? [{ account, provider }] : []; + }), + ({ account, provider }) => readAccount(hub, account, provider), { concurrency: 4 }, ); }); @@ -404,13 +515,19 @@ export const makeCliproxyApi = Effect.gen(function* () { detail: "The Codex hub account is missing or disabled.", }); } - const body = yield* apiCall(hub, account, `${CREDIT_URL}/consume`, { - redeem_request_id: yield* creditRedeemRequestId( - account.id_token?.chatgpt_account_id ?? account.id, - creditId, - ).pipe(Effect.provideService(Digest.Digest, digest)), - credit_id: creditId, - }); + const body = yield* apiCall( + hub, + account, + CODEX_HUB.header(account, platform, architecture), + `${CREDIT_URL}/consume`, + { + redeem_request_id: yield* creditRedeemRequestId( + account.id_token?.chatgpt_account_id ?? account.id, + creditId, + ).pipe(Effect.provideService(Digest.Digest, digest)), + credit_id: creditId, + }, + ); const response = yield* decodeConsumeResponse(body); const outcome = ( { diff --git a/apps/web/test/fixtures/usage-limits-hub/README.md b/apps/web/test/fixtures/usage-limits-hub/README.md index 102f8a31e573..ec33b471b9ca 100644 --- a/apps/web/test/fixtures/usage-limits-hub/README.md +++ b/apps/web/test/fixtures/usage-limits-hub/README.md @@ -2,15 +2,18 @@ A fake CLIProxyAPI hub that serves the Limits evidence scenarios in `scenarios.json`: -| Scenario | Accounts | -| -------- | -------------------------------------------------------------- | -| A | mixed Codex and Claude accounts | -| B | one account per provider | -| C | six long-email Codex accounts | -| L | named accounts (no email, so segments show the auth-file name) | -| T | forty accounts, so pooled segments are 4px wide at 390px | - -Reset times are minute offsets from `n0`. +| Scenario | Accounts | +| -------- | ------------------------------------------------------------------------ | +| A | mixed Codex and Claude accounts | +| B | one account per provider | +| C | six long-email Codex accounts | +| F | xAI and Antigravity accounts that read, answer malformed, or are refused | +| L | named accounts (no email, so segments show the auth-file name) | +| P | one account per read hub provider, plus an unread Kiro account | +| T | forty accounts, so pooled segments are 4px wide at 390px | + +Reset times are minute offsets from `n0`. An account's `state` of `malformed` or `refused` makes +its usage unreadable, so Limits leaves it out. ## Rebuild a capture diff --git a/apps/web/test/fixtures/usage-limits-hub/hub.mjs b/apps/web/test/fixtures/usage-limits-hub/hub.mjs index a2ba8d7c2ef0..5d10671fd7f0 100644 --- a/apps/web/test/fixtures/usage-limits-hub/hub.mjs +++ b/apps/web/test/fixtures/usage-limits-hub/hub.mjs @@ -13,8 +13,29 @@ const MINUTE = 60_000; // A window is [usedPercent, minutesFromN0 | null]; null is unknown reset timing. const at = (n0, minutes) => (minutes === null ? null : n0 + minutes * MINUTE); +const iso = (n0, minutes) => + minutes === null ? undefined : new Date(at(n0, minutes)).toISOString(); const usage = (account, n0) => { const [session, weekly, fable] = account.windows; + if (account.provider === "xai") { + return { + config: { + creditUsagePercent: session[0], + currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY", end: iso(n0, session[1]) }, + }, + }; + } + if (account.provider === "antigravity") { + const bucket = (bucketId, window, [used, minutes]) => ({ + bucketId, + window, + remainingFraction: 1 - used / 100, + resetTime: iso(n0, minutes), + }); + return { + buckets: [bucket("gemini-5h", "5h", session), bucket("gemini-weekly", "weekly", weekly)], + }; + } if (account.provider === "codex") { const window = ([used, minutes], seconds) => ({ used_percent: used, @@ -68,6 +89,7 @@ NodeHttp.createServer((request, response) => { auth_index: id, provider: account.provider, ...(account.email ? { email: account.email } : {}), + ...(account.project_id ? { project_id: account.project_id } : {}), })), }); } @@ -75,6 +97,13 @@ NodeHttp.createServer((request, response) => { const call = JSON.parse(raw); const account = accounts[call.auth_index]; if (!account) return json(response, { status_code: 404, body: "{}" }); + // "refused" fails every upstream call; "malformed" answers the usage call with the wrong shape. + if (account.state === "refused") { + return json(response, { status_code: 403, body: JSON.stringify({ error: "refused" }) }); + } + if (call.url.endsWith("/userinfo")) { + return json(response, { status_code: 200, body: JSON.stringify({ id: call.auth_index }) }); + } if (call.url.endsWith("/rate-limit-reset-credits")) { const credits = Array.from({ length: account.credits ?? 0 }, (_, index) => ({ id: `${call.auth_index}-credit-${index}`, @@ -84,7 +113,11 @@ NodeHttp.createServer((request, response) => { })); return json(response, { status_code: 200, body: JSON.stringify({ credits }) }); } - return json(response, { status_code: 200, body: JSON.stringify(usage(account, n0)) }); + const body = + account.state === "malformed" + ? { config: "malformed", buckets: "malformed" } + : usage(account, n0); + return json(response, { status_code: 200, body: JSON.stringify(body) }); } response.writeHead(404).end(); }); diff --git a/apps/web/test/fixtures/usage-limits-hub/scenarios.json b/apps/web/test/fixtures/usage-limits-hub/scenarios.json index 70e9be83f9a1..b1d267ad18e0 100644 --- a/apps/web/test/fixtures/usage-limits-hub/scenarios.json +++ b/apps/web/test/fixtures/usage-limits-hub/scenarios.json @@ -512,5 +512,91 @@ [20, 4480] ] } + }, + "P": { + "c1": { + "provider": "codex", + "email": "c1.codex.owner@example.com", + "windows": [ + [30, 120], + [60, 7560.0] + ] + }, + "a1": { + "provider": "claude", + "email": "a1.claude.owner@example.com", + "windows": [ + [50, 150.0], + [10, 9273.6], + [0, 10140] + ] + }, + "x1": { + "provider": "xai", + "email": "x1.grok.owner@example.com", + "windows": [[35, 4320]] + }, + "g1": { + "provider": "antigravity", + "project_id": "fixture-project", + "email": "g1.antigravity.owner@example.com", + "windows": [ + [60, 200], + [25, 6000] + ] + }, + "k1": { + "provider": "kiro", + "email": "k1.kiro.owner@example.com", + "windows": [[10, 60]] + } + }, + "F": { + "x1": { + "provider": "xai", + "email": "x1.grok.owner@example.com", + "windows": [[35, 4320]] + }, + "x2": { + "provider": "xai", + "email": "x2.grok.owner@example.com", + "windows": [[35, 4320]], + "state": "malformed" + }, + "x3": { + "provider": "xai", + "email": "x3.grok.owner@example.com", + "windows": [[35, 4320]], + "state": "refused" + }, + "g1": { + "provider": "antigravity", + "project_id": "fixture-project", + "email": "g1.antigravity.owner@example.com", + "windows": [ + [60, 200], + [25, 6000] + ] + }, + "g2": { + "provider": "antigravity", + "project_id": "fixture-project", + "email": "g2.antigravity.owner@example.com", + "windows": [ + [60, 200], + [25, 6000] + ], + "state": "malformed" + }, + "g3": { + "provider": "antigravity", + "project_id": "fixture-project", + "email": "g3.antigravity.owner@example.com", + "windows": [ + [60, 200], + [25, 6000] + ], + "state": "refused" + } } } diff --git a/docs/user/usage.md b/docs/user/usage.md index d7e0dad901be..e6b3a46d5a14 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -165,6 +165,9 @@ Grok reports the remaining subscription allowance and reset time for its current after signing in with `grok login`. Explicit `XAI_API_KEY` connections and custom authentication or endpoint configurations do not report subscription limits. +Muse Code reports its session and weekly windows and its tier once the Muse CLI has run in a thread. +Until then it shows no limits. Readings are not kept across a server restart. + API-key accounts may not report subscription limits. This also applies to Claude connections using a proxy through `ANTHROPIC_AUTH_TOKEN`. @@ -173,7 +176,8 @@ using a proxy through `ANTHROPIC_AUTH_TOKEN`. To see pooled accounts, open **Settings → Providers → Usage providers → Add hub**. Choose the environment that will connect to the hub and enter its URL and management key. -The accounts appear under **Usage → Limits**. Codex accounts show banked reset credits; select an +The hub's Codex, Claude, xAI (shown as Grok) and Antigravity accounts appear under **Usage → Limits**; +accounts for other providers are not read. Codex accounts show banked reset credits; select an account and choose **Use reset** to redeem one. No hub plugin is required. This connection supplies usage information; configure diff --git a/packages/provider-core/src/server/managedProvider.test.ts b/packages/provider-core/src/server/managedProvider.test.ts index 9df85130d601..5295232d3b14 100644 --- a/packages/provider-core/src/server/managedProvider.test.ts +++ b/packages/provider-core/src/server/managedProvider.test.ts @@ -609,10 +609,16 @@ describe("makeManagedServerProvider", () => { yield* provider.applyUsageLimits({ checkedAt: "2026-04-10T00:05:00.000Z", windows: [{ id: "seven_day", kind: "weekly", label: "Weekly", usedPercent: 25 }], + authLabel: "tier-1", + }); + yield* provider.applyUsageLimits({ + checkedAt: "2026-04-10T00:06:00.000Z", + windows: [], + authLabel: "tier-2", }); - yield* provider.applyUsageLimits({ checkedAt: "2026-04-10T00:06:00.000Z", windows: [] }); const [update] = Array.from(yield* Fiber.join(updatesFiber)); + assert.strictEqual(update?.auth.label, "tier-1"); assert.deepStrictEqual(update?.usageLimits, { checkedAt: "2026-04-10T00:05:00.000Z", windows: [ @@ -631,7 +637,10 @@ describe("makeManagedServerProvider", () => { ).pipe(Effect.provide(layerAlwaysRunTest)), ); - it.effect("keeps live usage windows across a failed probe and a stale enrichment", () => + it.effect.each([ + { name: "a live plan", clearPlan: false }, + { name: "a cleared plan", clearPlan: true }, + ])("keeps $name and usage across a failed probe and stale enrichment", ({ clearPlan }) => Effect.scoped( Effect.gen(function* () { const releaseEnrichment = yield* Deferred.make(); @@ -651,7 +660,7 @@ describe("makeManagedServerProvider", () => { count === 1 ? { ...refreshedSnapshot, - auth: { ...refreshedSnapshot.auth, workspaceId: "ws-a" }, + auth: { ...refreshedSnapshot.auth, workspaceId: "ws-a", label: "tier-1" }, usageLimits: probedLimits, } : { @@ -689,9 +698,18 @@ describe("makeManagedServerProvider", () => { } as const; yield* provider.applyUsageLimits({ checkedAt: "2026-04-10T00:00:02.000Z", + authLabel: "tier-2", windows: [liveWindow], }); + if (clearPlan) { + yield* provider.applyUsageLimits({ + checkedAt: "2026-04-10T00:00:02.000Z", + complete: true, + windows: [liveWindow], + }); + } + yield* Deferred.succeed(releaseEnrichment, undefined); const enriched = yield* Stream.take(provider.streamChanges, 1).pipe( Stream.runCollect, @@ -699,11 +717,13 @@ describe("makeManagedServerProvider", () => { ); assert.deepStrictEqual(enriched.models, enrichedSnapshot.models); assert.deepStrictEqual(enriched.usageLimits?.windows, [liveWindow]); + assert.strictEqual(enriched.auth.label, clearPlan ? undefined : "tier-2"); const refreshed = yield* provider.refresh; assert.strictEqual(refreshed.message, refreshedSnapshotSecond.message); assert.deepStrictEqual(refreshed.usageLimits?.windows, [liveWindow]); assert.strictEqual(refreshed.auth.workspaceId, "ws-a"); + assert.strictEqual(refreshed.auth.label, clearPlan ? undefined : "tier-2"); const switched = yield* provider.refresh; assert.strictEqual(switched.auth.workspaceId, "ws-b"); @@ -712,6 +732,91 @@ describe("makeManagedServerProvider", () => { ).pipe(Effect.provide(layerAlwaysRunTest)), ); + it.effect.each([ + { name: "an empty reading", hasUsage: true, clearPlan: false }, + { name: "no reading", hasUsage: false, clearPlan: false }, + { name: "an empty reading after clearing the plan", hasUsage: true, clearPlan: true }, + { name: "no reading after clearing the plan", hasUsage: false, clearPlan: true }, + ])("keeps the live plan and limits after $name", ({ hasUsage, clearPlan }) => + Effect.scoped( + Effect.gen(function* () { + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + const count = yield* Ref.make(0); + const provider = yield* makeManagedServerProvider({ + resolveMaintenance: () => Effect.succeed(maintenanceCapabilities), + getSettings: Effect.succeed({ enabled: true }), + streamSettings: Stream.empty, + haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled, + initialSnapshot: () => Effect.succeed(initialSnapshot), + checkProvider: Effect.gen(function* () { + if ((yield* Ref.updateAndGet(count, (n) => n + 1)) > 1) { + yield* Deferred.succeed(started, undefined); + yield* Deferred.await(release); + } + return { + ...refreshedSnapshot, + auth: { status: "authenticated", label: "tier-1" }, + ...(hasUsage + ? { usageLimits: { checkedAt: refreshedSnapshot.checkedAt, windows: [] } } + : {}), + } satisfies ServerProvider; + }), + }); + yield* Stream.take(provider.streamChanges, 1).pipe(Stream.runDrain); + const refresh = yield* provider.refresh.pipe(Effect.forkChild); + yield* Deferred.await(started); + yield* provider.applyUsageLimits({ + checkedAt: "2026-04-10T00:00:04.000Z", + authLabel: "tier-2", + complete: true, + windows: [{ id: "session", kind: "session", label: "Session", usedPercent: 70 }], + }); + if (clearPlan) { + yield* provider.applyUsageLimits({ + checkedAt: "2026-04-10T00:00:04.000Z", + complete: true, + windows: [{ id: "session", kind: "session", label: "Session", usedPercent: 70 }], + }); + } + yield* Deferred.succeed(release, undefined); + const refreshed = yield* Fiber.join(refresh); + assert.strictEqual(refreshed.auth.label, clearPlan ? undefined : "tier-2"); + assert.strictEqual(refreshed.usageLimits?.windows[0]?.usedPercent, 70); + assert.strictEqual(refreshed.usageLimits?.unavailable, undefined); + }), + ).pipe(Effect.provide(layerAlwaysRunTest)), + ); + + it.effect("drops an earlier plan override after a complete reading without a label", () => + Effect.scoped( + Effect.gen(function* () { + const usageLimits = { + checkedAt: "2026-04-10T00:00:04.000Z", + windows: [{ id: "session", kind: "session", label: "Session", usedPercent: 70 }], + } as const; + const provider = yield* makeManagedServerProvider({ + resolveMaintenance: () => Effect.succeed(maintenanceCapabilities), + getSettings: Effect.succeed({ enabled: true }), + streamSettings: Stream.empty, + haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled, + initialSnapshot: () => Effect.succeed(initialSnapshot), + checkProvider: Effect.succeed({ ...refreshedSnapshot, usageLimits }), + refreshOnInterval: false, + }); + yield* Stream.take(provider.streamChanges, 1).pipe(Stream.runDrain); + yield* provider.applyUsageLimits({ ...usageLimits, complete: true, authLabel: "tier-2" }); + assert.strictEqual((yield* provider.refresh).auth.label, "tier-2"); + + yield* provider.applyUsageLimits({ ...usageLimits, complete: true }); + assert.strictEqual((yield* provider.getSnapshot).auth.label, undefined); + const refreshed = yield* provider.refresh; + assert.strictEqual(refreshed.auth.label, undefined); + assert.deepStrictEqual(refreshed.usageLimits, usageLimits); + }), + ).pipe(Effect.provide(layerAlwaysRunTest)), + ); + it.effect("keeps sparse usage unavailable after probe failure until a full probe recovers", () => Effect.scoped( Effect.gen(function* () { diff --git a/packages/provider-core/src/server/managedProvider.ts b/packages/provider-core/src/server/managedProvider.ts index 9471be743f79..39332d013e2c 100644 --- a/packages/provider-core/src/server/managedProvider.ts +++ b/packages/provider-core/src/server/managedProvider.ts @@ -16,12 +16,18 @@ import * as Stream from "effect/Stream"; import * as Semaphore from "effect/Semaphore"; import * as ProviderHost from "./ProviderHost.ts"; -import { applyUsageLimitsUpdate, resolveUsageLimitsAfterProbe } from "./usageLimits.ts"; +import { + applyUsageLimitsUpdate, + makeUsageLimits, + resolveUsageLimitsAfterProbe, +} from "./usageLimits.ts"; import type { ManagedServerProvider } from "./snapshot.ts"; interface ProviderSnapshotState { readonly snapshot: ServerProvider; readonly enrichmentGeneration: number; + // null preserves an explicitly cleared plan across probes and enrichment. + readonly usageAuthLabel: string | null | undefined; } function withUsageLimits( @@ -72,6 +78,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( const snapshotStateRef = yield* Ref.make({ snapshot: initialSnapshot, enrichmentGeneration: 0, + usageAuthLabel: undefined, }); const settingsRef = yield* Ref.make(initialSettings); const enrichmentFiberRef = yield* Ref.make | null>(null); @@ -86,7 +93,15 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( return [null, state] as const; } // Enrichment must not revert usage updates newer than its input snapshot. - const merged = withUsageLimits(nextSnapshot, state.snapshot.usageLimits); + const merged = withUsageLimits( + state.usageAuthLabel === undefined + ? nextSnapshot + : { + ...nextSnapshot, + auth: { ...nextSnapshot.auth, label: state.usageAuthLabel ?? undefined }, + }, + state.snapshot.usageLimits, + ); if (Equal.equals(state.snapshot, merged)) { return [null, state] as const; } @@ -150,6 +165,8 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( return state.snapshot; } + // A probe without usage must not erase a report published while its I/O was in flight. + const usageBeforeProbe = (yield* Ref.get(snapshotStateRef)).snapshot.usageLimits; const probedSnapshot = yield* input.checkProvider; const { snapshot: nextSnapshot, generation: nextGeneration } = yield* Ref.modify( snapshotStateRef, @@ -167,21 +184,35 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( probedSnapshot.auth.workspaceId !== previous.workspaceId); const usageLimits = switchedAccount ? probedSnapshot.usageLimits - : resolveUsageLimitsAfterProbe({ - published: state.snapshot.usageLimits, - probed: probedSnapshot.usageLimits, - }); + : probedSnapshot.usageLimits === undefined && + state.snapshot.usageLimits !== usageBeforeProbe + ? state.snapshot.usageLimits + : resolveUsageLimitsAfterProbe({ + published: state.snapshot.usageLimits, + probed: probedSnapshot.usageLimits, + }); const workspaceId = usageLimits === probedSnapshot.usageLimits ? undefined : state.snapshot.auth.workspaceId; + const usageAuthLabel = + !switchedAccount && usageLimits?.checkedAt === state.snapshot.usageLimits?.checkedAt + ? state.usageAuthLabel + : undefined; + const labeledProbe = + usageAuthLabel === undefined + ? probedSnapshot + : { + ...probedSnapshot, + auth: { ...probedSnapshot.auth, label: usageAuthLabel ?? undefined }, + }; const snapshot = withUsageLimits( workspaceId && !probedSnapshot.auth.workspaceId - ? { ...probedSnapshot, auth: { ...probedSnapshot.auth, workspaceId } } - : probedSnapshot, + ? { ...labeledProbe, auth: { ...labeledProbe.auth, workspaceId } } + : labeledProbe, usageLimits, ); return [ { snapshot, generation }, - { snapshot, enrichmentGeneration: generation }, + { snapshot, enrichmentGeneration: generation, usageAuthLabel }, ] as const; }, ); @@ -197,16 +228,34 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( const applyUsageLimits: ManagedServerProvider["applyUsageLimits"] = Effect.fnUntraced( function* (update) { const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => { - const usageLimits = applyUsageLimitsUpdate({ - previous: state.snapshot.usageLimits, - update, - checkedAt: update.checkedAt, - }); - if (usageLimits === state.snapshot.usageLimits) { + const complete = update.complete && update.windows.length > 0; + const usageLimits = complete + ? makeUsageLimits(update) + : applyUsageLimitsUpdate({ + previous: state.snapshot.usageLimits, + update, + checkedAt: update.checkedAt, + }); + const { auth } = state.snapshot; + const label = update.windows.length > 0 ? update.authLabel : undefined; + const relabel = + (label !== undefined || (complete && state.usageAuthLabel !== undefined)) && + label !== auth.label; + if (usageLimits === state.snapshot.usageLimits && !relabel) { return [null, state] as const; } - const snapshot = withUsageLimits(state.snapshot, usageLimits); - return [snapshot, { ...state, snapshot }] as const; + const snapshot = withUsageLimits( + relabel ? { ...state.snapshot, auth: { ...auth, label } } : state.snapshot, + usageLimits, + ); + return [ + snapshot, + { + ...state, + snapshot, + usageAuthLabel: label ?? (complete ? null : state.usageAuthLabel), + }, + ] as const; }); if (snapshotToPublish !== null) { yield* PubSub.publish(changesPubSub, snapshotToPublish); diff --git a/packages/provider-core/src/server/snapshot.ts b/packages/provider-core/src/server/snapshot.ts index 88f2c1f11384..6cb7ea15c5b1 100644 --- a/packages/provider-core/src/server/snapshot.ts +++ b/packages/provider-core/src/server/snapshot.ts @@ -7,6 +7,14 @@ import type * as Effect from "effect/Effect"; import type * as Stream from "effect/Stream"; import type { ProviderMaintenanceCapabilities } from "./maintenance.ts"; +/** authLabel names the plan, for drivers whose usage report carries it. */ +export type ProviderUsageLimitsReport = ProviderUsageLimitsUpdate & { + readonly checkedAt: string; + readonly authLabel?: string; + /** A full reading replaces sparse windows and clears a previous probe failure. */ + readonly complete?: boolean; +}; + export interface ManagedServerProvider { /** Cached; pass { fresh: true } before executing updates. */ readonly resolveMaintenance: (options?: { @@ -16,8 +24,6 @@ export interface ManagedServerProvider { readonly refresh: Effect.Effect; readonly refreshUsage?: Effect.Effect; readonly streamChanges: Stream.Stream; - /** Merge windows by ID; updates with no usable window leave the snapshot untouched. */ - readonly applyUsageLimits: ( - update: ProviderUsageLimitsUpdate & { readonly checkedAt: string }, - ) => Effect.Effect; + /** Merge windows by ID and set any authLabel; an update with no window leaves the snapshot untouched. */ + readonly applyUsageLimits: (update: ProviderUsageLimitsReport) => Effect.Effect; } diff --git a/packages/provider-grok/src/server.ts b/packages/provider-grok/src/server.ts index 858f66ac31c1..4837089cf86a 100644 --- a/packages/provider-grok/src/server.ts +++ b/packages/provider-grok/src/server.ts @@ -1,2 +1,7 @@ export { GrokDriver, type GrokDriverEnv } from "./server/driver.ts"; export { type GrokAdapterV2DriverEnv } from "./server/adapter.ts"; +export { + GROK_USAGE_URL, + GrokUsageResponse, + grokUsageResponseToLimits, +} from "./server/usageLimits.ts"; diff --git a/packages/provider-grok/src/server/usageLimits.ts b/packages/provider-grok/src/server/usageLimits.ts index c6ba583c139c..5bf1ab4fda57 100644 --- a/packages/provider-grok/src/server/usageLimits.ts +++ b/packages/provider-grok/src/server/usageLimits.ts @@ -24,7 +24,8 @@ const GrokCredentials = Schema.Record( }), ); const decodeCredentials = Schema.decodeEffect(Schema.fromJsonString(GrokCredentials)); -const GrokUsageResponse = Schema.Struct({ +export const GROK_USAGE_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits"; +export const GrokUsageResponse = Schema.Struct({ config: Schema.optional( Schema.Struct({ creditUsagePercent: Schema.optional(Schema.Number), @@ -179,9 +180,7 @@ export const readGrokAccount = Effect.fn("readGrokAccount")(function* ( const usageLimits = yield* Effect.gen(function* () { const client = yield* HttpClient.HttpClient; const response = yield* client.execute( - HttpClientRequest.get("https://cli-chat-proxy.grok.com/v1/billing?format=credits").pipe( - HttpClientRequest.bearerToken(token), - ), + HttpClientRequest.get(GROK_USAGE_URL).pipe(HttpClientRequest.bearerToken(token)), ); if (response.status === 403) { const { error } = yield* HttpClientResponse.schemaBodyJson(GrokErrorResponse)(response); diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index f903f457af17..76b46715c602 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -42,6 +42,7 @@ import type { MuseItem, MuseSubscriptionUsage } from "./protocol.ts"; import type { MuseSdkHost, MuseSdkHostOptions } from "./sdk.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import type { ProviderUsageLimitsReport } from "@t3tools/provider-core/server/snapshot"; import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { makeMuseAdapterV2, type MuseAdapterV2Options } from "./adapter.ts"; @@ -208,7 +209,7 @@ const makeHarness = Effect.fnUntraced(function* ( policy = runtimePolicy, overrides: Pick< MuseAdapterV2Options, - "createHost" | "nativeEventLogger" | "modelCatalog" | "continuationRequests" + "createHost" | "nativeEventLogger" | "modelCatalog" | "continuationRequests" | "onUsageLimits" > = {}, ) { let hostCount = 0; @@ -607,7 +608,16 @@ describe("MuseAdapterV2", () => { it.effect("stops at a Meta usage limit until every exhausted window resets", () => Effect.gen(function* () { const fake = yield* makeFakeMuse(); - const harness = yield* makeHarness(fake); + const reports: Array = []; + const harness = yield* makeHarness( + fake, + INSTANCE_ID, + undefined, + undefined, + undefined, + runtimePolicy, + { onUsageLimits: (report) => Effect.sync(() => void reports.push(report)) }, + ); yield* fake.emitHostWide("usage/changed", { ...SUBSCRIPTION_USAGE, window: { ...SUBSCRIPTION_USAGE.window, usedPercent: 103 }, @@ -624,6 +634,10 @@ describe("MuseAdapterV2", () => { assert.strictEqual(terminal.threadDisposition, "reusable"); assert.strictEqual(terminal.failure?.class, "usage_limit"); assert.strictEqual(terminal.failure?.resetAt, "2026-10-08T13:19:17.000Z"); + assert.deepStrictEqual( + reports.map((report) => [report.authLabel, report.windows[0]?.usedPercent]), + [["tier-1", 100]], + ); assert.isTrue( harness.allEvents.some( (event) => @@ -685,7 +699,16 @@ describe("MuseAdapterV2", () => { it.effect("skips an unreadable usage report without ending the session", () => Effect.gen(function* () { const fake = yield* makeFakeMuse(); - const harness = yield* makeHarness(fake); + const reports: Array = []; + const harness = yield* makeHarness( + fake, + INSTANCE_ID, + undefined, + undefined, + undefined, + runtimePolicy, + { onUsageLimits: (report) => Effect.sync(() => void reports.push(report)) }, + ); yield* fake.emitHostWide("usage/changed", { window: "not usage" }); yield* fake.emitHostWide("usage/changed", { ...SUBSCRIPTION_USAGE, @@ -700,6 +723,7 @@ describe("MuseAdapterV2", () => { const terminal = yield* harness.takeEvent("turn.terminal"); assert.strictEqual(terminal.failure?.class, "usage_limit"); assert.isUndefined(terminal.failure?.resetAt); + assert.deepStrictEqual(reports, []); assert.strictEqual(fake.closeCount(), 0); }).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 82e1adcb4227..d4b58e806517 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -63,7 +63,11 @@ import { museApprovalOptions, type MuseItem, } from "./protocol.ts"; -import { isMuseUsageLimitFailure, museUsageLimitResetAt } from "./usageLimits.ts"; +import { + isMuseUsageLimitFailure, + museUsageLimitResetAt, + museUsageToLimits, +} from "./usageLimits.ts"; import { createMuseSdkHostEffect, MuseSdkError, @@ -75,6 +79,7 @@ import { type MuseSdkHost, } from "./sdk.ts"; import type * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; +import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot"; import { providerMessageTextWithAttachmentPaths, isProviderNativeImageAttachment, @@ -202,6 +207,8 @@ export interface MuseAdapterV2Options { readonly createHost?: typeof createMuseSdkHost; readonly requestTimeoutMs?: number; readonly nativeEventLogger?: ProviderEventLoggers.EventNdjsonLogger; + /** Receives every account-wide usage report, whichever session's host sent it. */ + readonly onUsageLimits?: ManagedServerProvider["applyUsageLimits"]; readonly continuationRequests?: { readonly offer: ( request: ProviderContinuationRequests.ProviderContinuationRequest, @@ -1378,6 +1385,9 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( // usage/changed is account-wide and carries no session ID. if (method === "usage/changed") { latestSubscriptionUsage = yield* decode(MuseSubscriptionUsage, params); + if (options.onUsageLimits) { + yield* options.onUsageLimits(museUsageToLimits(latestSubscriptionUsage)); + } return; } if (params.sessionId !== nativeSessionId) return; diff --git a/packages/provider-muse/src/server/driver.test.ts b/packages/provider-muse/src/server/driver.test.ts new file mode 100644 index 000000000000..7017b3f4e35a --- /dev/null +++ b/packages/provider-muse/src/server/driver.test.ts @@ -0,0 +1,216 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { + DEFAULT_SERVER_SETTINGS, + ProviderInstanceId, + ProviderSessionId, + ThreadId, +} from "@t3tools/contracts"; +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 Sink from "effect/Sink"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as HttpClient from "effect/http/HttpClient"; +import { vi } from "vite-plus/test"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; +import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; +import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; +import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as sdk from "./sdk.ts"; +import { MuseDriver } from "./driver.ts"; + +vi.mock("./sdk.ts", { spy: true }); + +const layerTest = TestProviderHost.layer({ + runBackgroundWork: false, + settings: { ...DEFAULT_SERVER_SETTINGS, enableProviderUpdateChecks: false }, +}).pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(IdAllocator.layer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provideMerge(ProviderLatestVersions.layer), + Layer.provideMerge( + Layer.succeed( + ProviderEventLoggers.ProviderEventLoggers, + ProviderEventLoggers.NoOpProviderEventLoggers, + ), + ), + Layer.provideMerge( + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("Unexpected HTTP request")), + ), + ), +); + +function nativeHost() { + let notify: Parameters[0] = () => {}; + let close!: () => void; + const closed = new Promise((resolve) => { + close = resolve; + }); + const host: sdk.MuseSdkHost = { + connection: { + mintCommandId: () => "command", + request: async (method) => + method.startsWith("session/") + ? { + session: { sessionId: "command", modelId: "muse-wonder-1.0", activeTurnId: null }, + history: { items: [] }, + } + : method === "model/list" + ? { + providerId: "meta", + models: [ + { + modelId: "muse-wonder-1.0", + displayLabel: "Muse", + providerId: "meta", + isDefault: true, + }, + ], + } + : {}, + command: async (_method, params) => ({ + session: { sessionId: params.sessionId, modelId: "muse-wonder-1.0", activeTurnId: null }, + history: { items: [] }, + }), + onNotification: (handler) => { + notify = handler; + }, + onProtocolError: () => {}, + onServerRequest: () => {}, + closed, + }, + initializeResult: { grantedCapabilities: [] }, + exited: closed.then(() => ({ code: 0, signal: null })), + close: async () => { + close(); + }, + }; + return { + host, + emit: (method: string, params: Record) => + notify({ jsonrpc: "2.0", method, params }), + }; +} + +it.layer(layerTest)("MuseDriver usage", (it) => { + it.effect( + "keeps the newest complete account report across late reports and refresh without probing for usage", + () => + Effect.gen(function* () { + const hosts: ReturnType[] = []; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + using spawn = vi.spyOn(spawner, "spawn").mockImplementation(() => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.encodeText(Stream.make("muse 1.0.3-R2198.1")), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ); + const createHost: typeof sdk.createMuseSdkHost = async () => { + const fake = nativeHost(); + hosts.push(fake); + return fake.host; + }; + const original = (yield* Effect.promise(() => vi.importActual("./sdk.ts"))) + .createMuseSdkHostEffect; + using _hostEffect = vi + .spyOn(sdk, "createMuseSdkHostEffect") + .mockImplementation((options) => original(options, createHost)); + using _host = vi.spyOn(sdk, "createMuseSdkHost").mockImplementation(createHost); + const instanceId = ProviderInstanceId.make("muse-test"); + const instance = yield* MuseDriver.create({ + instanceId, + displayName: "Muse test", + enabled: true, + environment: [], + config: { ...MuseDriver.defaultConfig(), binaryPath: process.execPath }, + }); + yield* Stream.take(instance.snapshot.streamChanges, 1).pipe(Stream.runDrain); + expect((yield* instance.snapshot.getSnapshot).status).toBe("ready"); + expect((yield* instance.snapshot.getSnapshot).usageLimits).toBeUndefined(); + const policy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: null, + }); + const sessions = yield* Effect.forEach( + ["one", "two"], + Effect.fnUntraced(function* (id) { + const runtime = yield* instance.orchestrationAdapter.openSession({ + threadId: ThreadId.make(id), + providerSessionId: ProviderSessionId.make(id), + modelSelection: { instanceId, model: "muse-wonder-1.0", options: [] }, + runtimePolicy: policy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + yield* runtime.ensureThread({ + threadId: ThreadId.make(id), + modelSelection: { instanceId, model: "muse-wonder-1.0", options: [] }, + runtimePolicy: policy, + }); + return { fake: hosts.at(-1)!, events }; + }), + ); + const reading = (observedAtMs: number, usedPercent: number, tier: string) => ({ + window: { usedPercent, windowDurationMins: 300, resetsAtMs: 1791465557000 }, + weekly: { usedPercent: 50, resetsAtMs: 1791763200000 }, + observedAtMs, + tier, + }); + const publish = Effect.fnUntraced(function* ( + index: number, + report: ReturnType, + ) { + const session = sessions[index]!; + session.fake.emit("usage/changed", report); + // The following context event acknowledges that this host has processed the report. + session.fake.emit("session/contextUsage", { + sessionId: "command", + usedTokens: report.observedAtMs, + }); + yield* Queue.take(session.events).pipe( + Effect.repeat({ + until: (event) => + event.type === "provider_thread.updated" && + event.providerThread.contextUsage?.usedTokens === report.observedAtMs, + }), + ); + }); + yield* publish(1, reading(1791447762610, 70, "tier-2")); + const latest = yield* instance.snapshot.getSnapshot; + expect(latest.usageLimits?.unavailable).toBeUndefined(); + expect(latest.usageLimits?.windows.map((window) => window.usedPercent)).toEqual([70, 50]); + expect(latest.auth.label).toBe("tier-2"); + yield* publish(0, reading(1791447761610, 10, "tier-1")); + expect((yield* instance.snapshot.getSnapshot).usageLimits).toEqual(latest.usageLimits); + expect((yield* instance.snapshot.getSnapshot).auth.label).toBe("tier-2"); + const callsBeforeUsageRefresh = spawn.mock.calls.length; + yield* instance.snapshot.refreshUsage!; + expect(spawn.mock.calls.length).toBe(callsBeforeUsageRefresh); + const refreshed = yield* instance.snapshot.refresh; + expect(refreshed.usageLimits).toEqual(latest.usageLimits); + expect(refreshed.auth.label).toBe("tier-2"); + }).pipe(Effect.scoped), + ); +}); diff --git a/packages/provider-muse/src/server/driver.ts b/packages/provider-muse/src/server/driver.ts index c24111f07d15..197a219e54ec 100644 --- a/packages/provider-muse/src/server/driver.ts +++ b/packages/provider-muse/src/server/driver.ts @@ -1,8 +1,10 @@ -import { ProviderDriverKind } from "@t3tools/contracts"; +import { ProviderDriverKind, type ServerProvider } from "@t3tools/contracts"; import { MuseSettings } from "../settings.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Ref from "effect/Ref"; +import * as Semaphore from "effect/Semaphore"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as HttpClient from "effect/http/HttpClient"; @@ -20,6 +22,8 @@ import * as ProviderContinuationRequests from "@t3tools/provider-core/server/Pro import { checkMuseProviderStatus, makePendingMuseProvider } from "./status.ts"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider"; +import type { ProviderUsageLimitsReport } from "@t3tools/provider-core/server/snapshot"; +import { makeUsageLimits } from "@t3tools/provider-core/server/usageLimits"; import { enrichMuseSnapshot, latestMuseVersion, museMaintenance } from "./maintenance.ts"; import { makeMuseEnvironment } from "./sdk.ts"; import { museUsageReader } from "./usage.ts"; @@ -104,6 +108,26 @@ export const MuseDriver: ProviderDriver< accentColor, continuationGroupKey: continuationIdentity.continuationKey, }); + // Only a running CLI reports usage; status probes cannot fetch it. + const latestUsage = yield* Ref.make(undefined); + const usagePermit = yield* Semaphore.make(1); + const withLatestUsage = (provider: ServerProvider) => + Ref.get(latestUsage).pipe( + Effect.map((report): ServerProvider => + report + ? { + ...provider, + ...(report.authLabel + ? { auth: { ...provider.auth, label: report.authLabel } } + : {}), + usageLimits: makeUsageLimits({ + checkedAt: report.checkedAt, + windows: report.windows, + }), + } + : provider, + ), + ); const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); const resolveInstallation = yield* makeCachedProviderMaintenanceResolution( resolveProviderMaintenanceCapabilitiesEffect(museMaintenance, { @@ -148,6 +172,7 @@ export const MuseDriver: ProviderDriver< makePendingMuseProvider(settings.provider).pipe(Effect.map(stampIdentity)), checkProvider: checkMuseProviderStatus(effectiveConfig, processEnvironment, cwd).pipe( Effect.map(stampIdentity), + Effect.flatMap(withLatestUsage), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), @@ -185,6 +210,15 @@ export const MuseDriver: ProviderDriver< modelCatalog, ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), continuationRequests, + onUsageLimits: (report) => + usagePermit.withPermits(1)( + Effect.gen(function* () { + const previous = yield* Ref.get(latestUsage); + if (previous && Date.parse(report.checkedAt) < Date.parse(previous.checkedAt)) return; + yield* Ref.set(latestUsage, report); + yield* snapshot.applyUsageLimits({ ...report, complete: true }); + }), + ), }); const textGeneration = yield* makeMuseTextGeneration(effectiveConfig, { environment: processEnvironment, @@ -197,7 +231,7 @@ export const MuseDriver: ProviderDriver< displayName, accentColor, enabled, - snapshot: { ...snapshot, resolveMaintenance }, + snapshot: { ...snapshot, resolveMaintenance, refreshUsage: Effect.void }, orchestrationAdapter, textGeneration, } satisfies ProviderInstance; diff --git a/packages/provider-muse/src/server/usageLimits.test.ts b/packages/provider-muse/src/server/usageLimits.test.ts index a633a06e8218..dddea9e6ac74 100644 --- a/packages/provider-muse/src/server/usageLimits.test.ts +++ b/packages/provider-muse/src/server/usageLimits.test.ts @@ -1,7 +1,11 @@ import { describe, expect, it } from "@effect/vitest"; import type { MuseSubscriptionUsage } from "./protocol.ts"; -import { isMuseUsageLimitFailure, museUsageLimitResetAt } from "./usageLimits.ts"; +import { + isMuseUsageLimitFailure, + museUsageLimitResetAt, + museUsageToLimits, +} from "./usageLimits.ts"; const usage = { observedAtMs: 1791447762610, @@ -54,3 +58,31 @@ describe("Muse usage limit failures", () => { expect(museUsageLimitResetAt(undefined, afterNamedReset, { message: realRefusal })).toBeNull(); }); }); + +describe("Muse account usage", () => { + it("reports the session and weekly windows, capped at 100, with the tier as plan", () => { + expect(museUsageToLimits({ ...usage, window: { ...usage.window, usedPercent: 103 } })).toEqual({ + checkedAt: "2026-10-08T08:22:42.610Z", + authLabel: "tier-1", + windows: [ + { + id: "session", + kind: "session", + label: "Session", + usedPercent: 100, + resetsAt: "2026-10-08T13:19:17.000Z", + windowDurationMins: 300, + }, + { + id: "weekly", + kind: "weekly", + label: "Weekly", + usedPercent: 5, + resetsAt: "2026-10-12T00:00:00.000Z", + windowDurationMins: 10080, + }, + ], + }); + expect(museUsageToLimits({ ...usage, tier: " " })).not.toHaveProperty("authLabel"); + }); +}); diff --git a/packages/provider-muse/src/server/usageLimits.ts b/packages/provider-muse/src/server/usageLimits.ts index 1f97451c9338..be981ebc009a 100644 --- a/packages/provider-muse/src/server/usageLimits.ts +++ b/packages/provider-muse/src/server/usageLimits.ts @@ -1,7 +1,38 @@ import * as DateTime from "effect/DateTime"; +import { clampPercent } from "@t3tools/provider-core/server/usageLimits"; +import type { ProviderUsageLimitsReport } from "@t3tools/provider-core/server/snapshot"; import { LATEST_DATE_MS, type MuseSubscriptionUsage } from "./protocol.ts"; +const isoMillis = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); + +/** Muse's account-wide report as Limits windows, with its tier as the plan. */ +export function museUsageToLimits(usage: MuseSubscriptionUsage): ProviderUsageLimitsReport { + const tier = usage.tier.trim(); + return { + checkedAt: isoMillis(usage.observedAtMs), + windows: [ + { + id: "session", + kind: "session", + label: "Session", + usedPercent: clampPercent(usage.window.usedPercent), + resetsAt: isoMillis(usage.window.resetsAtMs), + windowDurationMins: usage.window.windowDurationMins, + }, + { + id: "weekly", + kind: "weekly", + label: "Weekly", + usedPercent: clampPercent(usage.weekly.usedPercent), + resetsAt: isoMillis(usage.weekly.resetsAtMs), + windowDurationMins: 7 * 24 * 60, + }, + ], + ...(tier ? { authLabel: tier } : {}), + }; +} + /** Credential proxies may omit error.quota from 429 refusals; inspect text too. */ export function isMuseUsageLimitFailure(message: string | undefined): boolean { return message !== undefined && /\b429\b/.test(message) && /quota|usage limit/i.test(message); @@ -30,5 +61,5 @@ export function museUsageLimitResetAt( (ms): ms is number => ms !== undefined && Number.isFinite(ms) && ms > nowMs && ms <= LATEST_DATE_MS, ); - return resets.length > 0 ? DateTime.formatIso(DateTime.makeUnsafe(Math.max(...resets))) : null; + return resets.length > 0 ? isoMillis(Math.max(...resets)) : null; } diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index 236a8baa13a2..e9d5f6e604f3 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -344,6 +344,45 @@ describe("pools", () => { expect(collectLimitAccounts(input)).toHaveLength(1); }); + it("merges a local Antigravity login with its hub account by Google account fingerprint", () => { + const antigravity = ProviderDriverKind.make("antigravity"); + const local = provider({ + driver: antigravity, + instanceId: ProviderInstanceId.make("antigravity"), + auth: { status: "authenticated" }, + usageLimits: { + checkedAt, + credentialFingerprint: "google-key", + windows: [{ ...window, id: "gemini-weekly", usedPercent: 20 }], + }, + }); + const hubAccount = { + id: "antigravity-g@example.com.json", + driver: antigravity, + usageLimits: { + checkedAt: "2026-09-03T11:30:00.000Z", + credentialFingerprint: "google-key", + windows: [{ ...window, id: "gemini-weekly", usedPercent: 30 }], + }, + }; + const accounts = collectLimitAccounts( + new Map([ + [ + EnvironmentId.make("env-a"), + { + ...laptop, + serverConfig: { + providers: [local], + usageLimitSources: [{ ...source, accounts: [hubAccount] }], + }, + }, + ], + ]), + ); + expect(accounts).toHaveLength(1); + expect(accounts[0]?.limits.windows[0]?.usedPercent).toBe(30); + }); + it("takes windows from a fresher hub read but credits and redeem from the native instance", () => { const native = provider({ driver: claude, From 8fc6fd01d70a8da940781d04802c633ea782a9a7 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 10 Nov 2026 15:54:58 -0600 Subject: [PATCH 039/170] fix(web): preserve previews during attachment preparation (#33949) --- .../chat/ComposerAttachmentStrip.tsx | 71 ++++++++++---- .../ComposerImageThumbnail.browser.test.tsx | 69 +++++++++++++ .../chat/ComposerImageThumbnail.tsx | 31 +++--- .../composerContextPresentation.tsx | 21 ++-- ...eAttachmentUploadProgress.browser.test.tsx | 47 +++++++++ .../src/hooks/useAttachmentUploadProgress.ts | 18 ++++ apps/web/src/hooks/useDelayedStatus.ts | 6 +- apps/web/src/lib/imageCompression.test.ts | 70 +++++++++++--- apps/web/src/lib/imageCompression.ts | 96 +++++++++++++++---- 9 files changed, 350 insertions(+), 79 deletions(-) create mode 100644 apps/web/src/components/chat/ComposerImageThumbnail.browser.test.tsx create mode 100644 apps/web/src/hooks/useAttachmentUploadProgress.browser.test.tsx create mode 100644 apps/web/src/hooks/useAttachmentUploadProgress.ts diff --git a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx index e3560312925e..ca98b4d2f6c7 100644 --- a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx +++ b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx @@ -6,7 +6,7 @@ import type { SnapShotSource, } from "@t3tools/contracts"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; -import { CircleAlertIcon, PaperclipIcon, PlayIcon, XIcon } from "lucide-react"; +import { CircleAlertIcon, ImageIcon, PaperclipIcon, PlayIcon, XIcon } from "lucide-react"; import { type ComponentProps, useLayoutEffect, useRef } from "react"; import { @@ -16,7 +16,8 @@ import { composerFileNeedsReattach, } from "../../composerDraftStore"; import { retryAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue"; -import { formatAttachmentUploadProgress } from "../../lib/attachmentUploadState"; +import type { AttachmentUploadState } from "../../lib/attachmentUploadState"; +import { useAttachmentUploadProgress } from "../../hooks/useAttachmentUploadProgress"; import { isHeicImageFile } from "../../lib/imageCompression"; import { type PendingSnapShotAnimation, @@ -47,6 +48,30 @@ import { } from "./SnapShotAttachmentDetails"; import { prepareVideoFirstFrame } from "../../lib/videoFirstFrame"; +function ComposerAttachmentUploadProgress({ + id, + upload, + fallback, +}: { + id: string; + upload: AttachmentUploadState | undefined; + fallback?: string; +}) { + return useAttachmentUploadProgress(id, upload) ?? fallback ?? null; +} + +function ComposerImageFallback() { + return ( + + + ); +} + function ComposerVideoThumbnail({ file }: { file: File }) { const setVideo = (video: HTMLVideoElement | null) => { if (!video) return; @@ -214,21 +239,17 @@ export function ComposerAttachmentMediaRow({ name={ready.name} mimeType={ready.mimeType} src={ready.previewUrl} - alt={image.name} + alt="" className="h-full w-full object-cover" /> ) : ( - - {image.name} - + ) } /> ) : ( -
- {image.name} -
+ )} {source?.kind === "snap-shot" ? ( )} - {(ready ? upload?.status === "uploading" : supportsAttachmentUploads) && ( + {(!ready || upload?.status === "uploading") && ( - {formatAttachmentUploadProgress( - upload?.status === "uploading" ? upload.progress : 0, + {upload?.status === "uploading" ? ( + + ) : ( + "Preparing" )} )} @@ -359,7 +382,7 @@ export function ComposerAttachmentMediaRow({ {upload?.status === "uploading" && ( - {formatAttachmentUploadProgress(upload.progress)} + )} {upload?.status === "failed" && ( @@ -453,13 +476,21 @@ export function ComposerAttachmentFileList({ {file.name} - {needsReattach - ? canReattachFile - ? "Attach again" - : "Remove to send" - : upload?.status === "uploading" - ? formatAttachmentUploadProgress(upload.progress) - : formatAttachmentSize(file.sizeBytes)} + {needsReattach ? ( + canReattachFile ? ( + "Attach again" + ) : ( + "Remove to send" + ) + ) : upload?.status === "uploading" ? ( + + ) : ( + formatAttachmentSize(file.sizeBytes) + )} {!needsReattach && upload?.status === "failed" ? ( diff --git a/apps/web/src/components/chat/ComposerImageThumbnail.browser.test.tsx b/apps/web/src/components/chat/ComposerImageThumbnail.browser.test.tsx new file mode 100644 index 000000000000..9994d1552027 --- /dev/null +++ b/apps/web/src/components/chat/ComposerImageThumbnail.browser.test.tsx @@ -0,0 +1,69 @@ +import { expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../../test/render"; +import { createComposerImageThumbnail } from "../../lib/imageCompression"; +import { ComposerImageThumbnail } from "./ComposerImageThumbnail"; + +it("keeps a native preview available after thumbnail generation has failed", async () => { + const canvas = document.createElement("canvas"); + canvas.width = 2; + canvas.height = 2; + const blob = await new Promise((resolve) => canvas.toBlob((blob) => resolve(blob!))); + const file = new File([blob], "screenshot.png", { type: "image/png" }); + using _bitmap = vi + .spyOn(window, "createImageBitmap") + .mockRejectedValue(new Error("Thumbnail decoder unavailable")); + expect(await createComposerImageThumbnail(file)).toBeNull(); + + const container = document.createElement("div"); + const holdLoad = (event: Event) => event.stopPropagation(); + container.addEventListener("load", holdLoad, true); + using complete = vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(false); + await using screen = await render( + Preview unavailable} + />, + { container }, + ); + using revoke = vi.spyOn(URL, "revokeObjectURL"); + await expect.element(screen.getByText("Preview unavailable")).toBeVisible(); + const loadingImage = screen.container.querySelector("img")!; + await loadingImage.decode(); + complete.mockRestore(); + container.removeEventListener("load", holdLoad, true); + await act(() => loadingImage.dispatchEvent(new Event("load"))); + const image = screen.getByRole("img", { name: file.name }); + await expect.element(image).toBeVisible(); + await expect.element(screen.getByText("Preview unavailable")).not.toBeInTheDocument(); + const src = image.element().getAttribute("src"); + expect(src).toMatch(/^blob:/); + await screen.unmount(); + expect(revoke).toHaveBeenCalledWith(src); +}); + +it("shows the fallback while HEIC preparation is pending", async () => { + let finishReading!: (bytes: ArrayBuffer) => void; + const metadata = new Promise((resolve) => { + finishReading = resolve; + }); + using _read = vi.spyOn(Blob.prototype, "arrayBuffer").mockReturnValue(metadata); + const file = new File(["pending"], "photo.heic", { type: "image/heic" }); + + await using screen = await render( + } + />, + ); + try { + expect(screen.container.querySelector('[aria-label="Preparing image"]')).not.toBeNull(); + } finally { + finishReading(new ArrayBuffer(0)); + await createComposerImageThumbnail(file); + } +}); diff --git a/apps/web/src/components/chat/ComposerImageThumbnail.tsx b/apps/web/src/components/chat/ComposerImageThumbnail.tsx index 68158c7151b2..b6fc4d2b9a48 100644 --- a/apps/web/src/components/chat/ComposerImageThumbnail.tsx +++ b/apps/web/src/components/chat/ComposerImageThumbnail.tsx @@ -33,11 +33,7 @@ export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({ let disposed = false; let localUrl: string | undefined; const cached = readComposerImageThumbnail(file); - if ( - file.size <= MAX_COMPRESSIBLE_SOURCE_BYTES && - !isHeicImageFile(file) && - cached === undefined - ) { + if (file.size <= MAX_COMPRESSIBLE_SOURCE_BYTES && !isHeicImageFile(file) && !cached) { localUrl = URL.createObjectURL(file); // oxlint-disable-next-line react/set-state-in-effect -- the blob URL is created and revoked by this effect setPreview({ file, src: localUrl }); @@ -66,17 +62,20 @@ export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({ }, [file]); return src && failedSrc !== src ? ( - { - if (image?.complete && image.naturalWidth > 0) setLoadedSrc(src); - }} - src={src} - alt={alt} - onLoad={() => setLoadedSrc(src)} - onError={() => setFailedSrc(src)} - className={cn(className, loadedSrc !== src && "invisible")} - /> - ) : src === undefined ? null : ( + + {loadedSrc !== src && fallback} + { + if (image?.complete && image.naturalWidth > 0) setLoadedSrc(src); + }} + src={src} + alt={alt} + onLoad={() => setLoadedSrc(src)} + onError={() => setFailedSrc(src)} + className={cn(className, loadedSrc !== src && "invisible absolute inset-0")} + /> + + ) : ( fallback ); }); diff --git a/apps/web/src/components/composerContextPresentation.tsx b/apps/web/src/components/composerContextPresentation.tsx index 845e921725b5..ad9be211cb3c 100644 --- a/apps/web/src/components/composerContextPresentation.tsx +++ b/apps/web/src/components/composerContextPresentation.tsx @@ -15,10 +15,8 @@ import { ComposerContextActionsContext } from "./composerContextActions"; import type { ComposerFileAttachment, ComposerImageAttachment } from "~/composerDraftStore"; import { composerFileNeedsReattach } from "~/composerDraftStore"; import { useTheme } from "~/hooks/useTheme"; -import { - formatAttachmentUploadProgress, - type AttachmentUploadState, -} from "~/lib/attachmentUploadState"; +import type { AttachmentUploadState } from "~/lib/attachmentUploadState"; +import { useAttachmentUploadProgress } from "~/hooks/useAttachmentUploadProgress"; import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons"; import { fileContextReference, @@ -167,10 +165,13 @@ function ContextChip(props: { ); } -function uploadStatusSuffix(upload: AttachmentUploadState | undefined): string | null { - if (upload?.status === "uploading") return formatAttachmentUploadProgress(upload.progress); +function useUploadStatusSuffix( + key: string, + upload: AttachmentUploadState | undefined, +): string | null { + const progress = useAttachmentUploadProgress(key, upload); if (upload?.status === "failed") return "upload failed"; - return null; + return progress; } function attachmentTooltip( @@ -187,6 +188,7 @@ function ImageContextChip(props: { upload: AttachmentUploadState | undefined; }) { const actions = use(ComposerContextActionsContext); + const suffix = useUploadStatusSuffix(props.record.id, props.upload); return ( actions.expandImage(props.record.id)} /> } @@ -214,7 +216,8 @@ function FileContextChip(props: { const actions = use(ComposerContextActionsContext); const { resolvedTheme } = useTheme(); const needsReattach = composerFileNeedsReattach(props.record); - const suffix = needsReattach ? "attach again" : uploadStatusSuffix(props.upload); + const uploadSuffix = useUploadStatusSuffix(props.record.id, props.upload); + const suffix = needsReattach ? "attach again" : uploadSuffix; const size = formatAttachmentSize(props.record.sizeBytes); const isVideo = videoMimeType(props.record) !== null; return ( diff --git a/apps/web/src/hooks/useAttachmentUploadProgress.browser.test.tsx b/apps/web/src/hooks/useAttachmentUploadProgress.browser.test.tsx new file mode 100644 index 000000000000..daebd55c0f52 --- /dev/null +++ b/apps/web/src/hooks/useAttachmentUploadProgress.browser.test.tsx @@ -0,0 +1,47 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, fakeTimers, render } from "../../test/render"; +import type { AttachmentUploadState } from "../lib/attachmentUploadState"; +import { useAttachmentUploadProgress } from "./useAttachmentUploadProgress"; + +function Probe({ id = "image", upload }: { id?: string; upload: AttachmentUploadState }) { + const progress = useAttachmentUploadProgress(id, upload); + return {progress ?? "hidden"}; +} + +it("skips fast uploads and delays each attempt without delaying later progress or completion", async () => { + const environmentId = EnvironmentId.make("environment"); + const uploading = (progress: number) => ({ + status: "uploading" as const, + environmentId, + progress, + }); + const ready = { status: "ready" as const, environmentId, attachmentId: "attachment" }; + // The first render reads the clock to schedule the badge. + using _timers = fakeTimers({ now: 0 }); + await using screen = await render(); + await expect.element(screen.getByText("hidden")).toBeInTheDocument(); + await act(() => vi.advanceTimersByTime(75)); + await screen.rerender(); + await act(() => vi.advanceTimersByTime(75)); + await expect.element(screen.getByText("hidden")).toBeInTheDocument(); + + await screen.rerender(); + await act(() => vi.advanceTimersByTime(149)); + await screen.rerender(); + await expect.element(screen.getByText("hidden")).toBeInTheDocument(); + await act(() => vi.advanceTimersByTime(1)); + await expect.element(screen.getByText("45%")).toBeInTheDocument(); + await screen.rerender(); + await expect.element(screen.getByText("70%")).toBeInTheDocument(); + await screen.rerender(); + await expect.element(screen.getByText("hidden")).toBeInTheDocument(); + + await screen.rerender(); + await expect.element(screen.getByText("hidden")).toBeInTheDocument(); + await act(() => vi.advanceTimersByTime(150)); + await expect.element(screen.getByText("0%")).toBeInTheDocument(); + await screen.rerender(); + await expect.element(screen.getByText("hidden")).toBeInTheDocument(); +}); diff --git a/apps/web/src/hooks/useAttachmentUploadProgress.ts b/apps/web/src/hooks/useAttachmentUploadProgress.ts new file mode 100644 index 000000000000..bc320b9eed6d --- /dev/null +++ b/apps/web/src/hooks/useAttachmentUploadProgress.ts @@ -0,0 +1,18 @@ +import { + type AttachmentUploadState, + formatAttachmentUploadProgress, +} from "../lib/attachmentUploadState"; +import { useDelayedStatus } from "./useDelayedStatus"; + +export function useAttachmentUploadProgress( + key: string, + upload: AttachmentUploadState | undefined, +) { + const uploading = upload?.status === "uploading"; + const shown = useDelayedStatus( + `${key}:${upload?.environmentId ?? ""}:${uploading ? "uploading" : "idle"}`, + uploading ? true : null, + 150, + ); + return uploading && shown ? formatAttachmentUploadProgress(upload.progress) : null; +} diff --git a/apps/web/src/hooks/useDelayedStatus.ts b/apps/web/src/hooks/useDelayedStatus.ts index 718c0f03538e..d9a4c15c695c 100644 --- a/apps/web/src/hooks/useDelayedStatus.ts +++ b/apps/web/src/hooks/useDelayedStatus.ts @@ -7,12 +7,12 @@ import { useState } from "react"; import { useDeadlinePassed } from "./useDeadline"; -export function useDelayedStatus
(key: string, value: A | null): A | null { +export function useDelayedStatus(key: string, value: A | null, showDelayMs?: number): A | null { const [state, setState] = useState(() => - stepDelayedStatus(null, { key, value, deadlinePassed: false }, Date.now), + stepDelayedStatus(null, { key, value, deadlinePassed: false, showDelayMs }, Date.now), ); const deadlinePassed = useDeadlinePassed(delayedStatusDeadline(state)); - const next = stepDelayedStatus(state, { key, value, deadlinePassed }, Date.now); + const next = stepDelayedStatus(state, { key, value, deadlinePassed, showDelayMs }, Date.now); if (next !== state) setState(next); return shownDelayedStatus(next, key); } diff --git a/apps/web/src/lib/imageCompression.test.ts b/apps/web/src/lib/imageCompression.test.ts index 079c52df5d57..a8d4cfcc1d54 100644 --- a/apps/web/src/lib/imageCompression.test.ts +++ b/apps/web/src/lib/imageCompression.test.ts @@ -96,6 +96,7 @@ function stubCanvasPipeline( const supportsWebp = options?.supportsWebp ?? true; const close = vi.fn(); const fillRect = vi.fn(); + const canvasSizes: Array<{ width: number; height: number }> = []; vi.stubGlobal( "createImageBitmap", vi.fn(async () => ({ width: 4000, height: 3000, close })), @@ -106,7 +107,9 @@ function stubCanvasPipeline( constructor( public width: number, public height: number, - ) {} + ) { + canvasSizes.push({ width, height }); + } getContext() { return { fillStyle: "", @@ -131,7 +134,7 @@ function stubCanvasPipeline( vi.stubGlobal("HTMLCanvasElement", HtmlCanvas); vi.stubGlobal("document", { createElement: () => new HtmlCanvas(0, 0) }); } - return { close, fillRect }; + return { close, fillRect, canvasSizes }; } afterEach(() => { @@ -263,22 +266,57 @@ describe("composer image thumbnails", () => { }); describe("HEIC attachment preparation", () => { + it("shares the native decode and shows its thumbnail before JPEG encoding finishes", async () => { + const { close } = stubCanvasPipeline(() => 3); + let finishEncoding!: (blob: Blob) => void; + const jpeg = new Promise((resolve) => { + finishEncoding = resolve; + }); + const Canvas = globalThis.OffscreenCanvas; + vi.stubGlobal( + "OffscreenCanvas", + class extends Canvas { + override convertToBlob(options?: ImageEncodeOptions) { + return options?.type === "image/jpeg" ? jpeg : super.convertToBlob(options); + } + }, + ); + const original = makeHeicFile(); + const preparation = prepareImageForAttachment(original, 1024); + const queued = prepareImageForAttachment(makeHeicFile({ name: "next.heic" }), 1024); + const results = Promise.all([preparation, queued]); + try { + const thumbnail = await createComposerImageThumbnail(original); + expect(thumbnail).toMatch(/^data:image\/png;base64,/); + expect(mocks.heicTo).not.toHaveBeenCalled(); + expect(createImageBitmap).toHaveBeenCalledTimes(1); + expect(close).not.toHaveBeenCalled(); + } finally { + finishEncoding(new Blob([new Uint8Array(4)], { type: "image/jpeg" })); + await results; + } + const [result, next] = await results; + expect(result.ok && result.file.type).toBe("image/jpeg"); + expect(result.ok && result.file.size).toBe(4); + expect(next.ok).toBe(true); + expect(close).toHaveBeenCalledTimes(2); + }); + it("converts a HEIC photo with a missing MIME type into a named JPEG", async () => { const original = makeHeicFile({ name: "IMG_1234.HEIC", type: "", lastModified: 123, }); - mocks.heicTo.mockResolvedValueOnce( - new Blob([new Uint8Array([4, 5, 6, 7])], { type: "image/jpeg" }), - ); + const { close } = stubCanvasPipeline(() => 4); + vi.mocked(createImageBitmap).mockRejectedValue(new Error("HEIC is not supported natively")); + mocks.heicTo.mockResolvedValueOnce({ width: 4000, height: 3000, close }); const result = await prepareImageForAttachment(original, 1024); expect(mocks.heicTo).toHaveBeenCalledWith({ blob: original, - type: "image/jpeg", - quality: 0.92, + type: "bitmap", }); expect(result.ok && result.file.name).toBe("IMG_1234.jpg"); expect(result.ok && result.file.type).toBe("image/jpeg"); @@ -287,24 +325,26 @@ describe("HEIC attachment preparation", () => { expect(result.ok && result.recompressed).toBe(true); }); - it("compresses JPEG intermediates above the source safety ceiling", async () => { + it("resizes decoded HEIC pixels before encoding the JPEG", async () => { const original = makeHeicFile({ name: "large.heic", type: "image/heic", }); - mocks.heicTo.mockResolvedValueOnce( - new Blob([new Uint8Array(MAX_COMPRESSIBLE_SOURCE_BYTES + 1)], { - type: "image/jpeg", - }), - ); - const { close } = stubCanvasPipeline(() => 200_000); + const { close, canvasSizes } = stubCanvasPipeline(() => 200_000); + vi.mocked(createImageBitmap).mockRejectedValue(new Error("HEIC is not supported natively")); + mocks.heicTo.mockResolvedValueOnce({ width: 4000, height: 3000, close }); const result = await prepareImageForAttachment(original, 1_000_000); expect(result.ok && result.file.name).toBe("large.jpg"); expect(result.ok && result.file.type).toBe("image/jpeg"); expect(result.ok && result.file.size).toBeLessThanOrEqual(1_000_000); - expect(close).toHaveBeenCalled(); + expect(close).toHaveBeenCalledTimes(1); + expect(createImageBitmap).toHaveBeenCalledTimes(1); + expect(canvasSizes).toEqual([ + { width: 2000, height: 1500 }, + { width: 256, height: 256 }, + ]); }); it("rejects oversized HEIC dimensions before loading the decoder", async () => { diff --git a/apps/web/src/lib/imageCompression.ts b/apps/web/src/lib/imageCompression.ts index ed41b9ec4532..e174bebf4b9e 100644 --- a/apps/web/src/lib/imageCompression.ts +++ b/apps/web/src/lib/imageCompression.ts @@ -240,11 +240,22 @@ export function inheritComposerImageThumbnail(source: File, target: File): void } async function renderComposerImageThumbnail(file: File): Promise { + if (isHeicImageFile(file)) return prepareHeicImage(file).thumbnail; // Placeholders thumbnail the uncompressed source, which can be big enough to OOM the decode. if (!canRecompress() || file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) return null; let bitmap: ImageBitmap | undefined; try { bitmap = await createImageBitmap(file); + return await renderComposerImageThumbnailFromBitmap(bitmap); + } catch { + return null; + } finally { + bitmap?.close(); + } +} + +async function renderComposerImageThumbnailFromBitmap(bitmap: ImageBitmap): Promise { + try { const side = Math.min(bitmap.width, bitmap.height); if (side <= 0) return null; const dimension = Math.min(256, side); @@ -265,8 +276,6 @@ async function renderComposerImageThumbnail(file: File): Promise return blob ? await readFileAsDataUrl(blob) : null; } catch { return null; - } finally { - bitmap?.close(); } } @@ -454,35 +463,90 @@ export async function compressImageToByteLimit( }; } -export async function prepareImageForAttachment( +const heicPreparations = new WeakMap< + File, + { image: Promise; thumbnail: Promise } +>(); +// Preparing tiles share full-size decodes, so keep only one HEIC bitmap alive at a time. +let heicPreparationQueue = Promise.resolve(); + +function prepareHeicImage(file: File) { + const cached = heicPreparations.get(file); + if (cached) return cached; + let resolveThumbnail!: (src: string | null) => void; + const thumbnail = new Promise((resolve) => { + resolveThumbnail = resolve; + }); + const image = heicPreparationQueue + .then(() => convertHeicImage(file, resolveThumbnail)) + .finally(() => resolveThumbnail(null)); + heicPreparationQueue = image.then( + () => undefined, + () => undefined, + ); + const preparation = { image, thumbnail }; + heicPreparations.set(file, preparation); + return preparation; +} + +async function convertHeicImage( file: File, - maxBytes: number, + onThumbnail: (src: string | null) => void, ): Promise { - if (!isHeicImageFile(file)) { - return compressImageToByteLimit(file, maxBytes); - } - if (file.size > MAX_COMPRESSIBLE_SOURCE_BYTES) { return { ok: false, reason: "too-large" }; } - let converted: Blob; + let bitmap: ImageBitmap | undefined; try { const dimensionError = await validateHeicImageDimensions(file); if (dimensionError) { return { ok: false, reason: dimensionError }; } - const { heicTo } = await import("heic-to/csp"); - converted = await heicTo({ blob: file, type: "image/jpeg", quality: QUALITY_STEPS[0] }); + bitmap = + typeof createImageBitmap === "function" + ? await createImageBitmap(file).catch(() => undefined) + : undefined; + if (!bitmap) { + const { heicTo } = await import("heic-to/csp"); + bitmap = await heicTo({ blob: file, type: "bitmap" }); + } + const imageSize = fitImageAttachmentSize(bitmap) ?? { + width: bitmap.width, + height: bitmap.height, + }; + const surface = createCanvas(imageSize.width, imageSize.height); + if (!surface) return { ok: false, reason: "unreadable" }; + surface.context.drawImage(bitmap, 0, 0, imageSize.width, imageSize.height); + const [converted] = await Promise.all([ + encodeCanvas(surface.canvas, QUALITY_STEPS[0], "image/jpeg"), + renderComposerImageThumbnailFromBitmap(bitmap).then(onThumbnail), + ]); + if (!converted) return { ok: false, reason: "unreadable" }; + return { + ok: true, + file: new File([converted], fileNameForMimeType(file.name || "image", "image/jpeg"), { + type: "image/jpeg", + lastModified: file.lastModified, + }), + recompressed: true, + imageSize, + }; } catch { return { ok: false, reason: "unreadable" }; + } finally { + bitmap?.close(); } +} - const jpeg = new File([converted], fileNameForMimeType(file.name || "image", "image/jpeg"), { - type: "image/jpeg", - lastModified: file.lastModified, - }); - const result = await compressImageToByteLimit(jpeg, maxBytes, { +export async function prepareImageForAttachment( + file: File, + maxBytes: number, +): Promise { + if (!isHeicImageFile(file)) return compressImageToByteLimit(file, maxBytes); + const prepared = await prepareHeicImage(file).image; + if (!prepared.ok || prepared.file.size <= maxBytes) return prepared; + const result = await compressImageToByteLimit(prepared.file, maxBytes, { preferredMimeType: "image/jpeg", sourceSizeBytes: file.size, }); From 3725817edc7d0a29d9259502c87b08c9f0e3d6f5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 13:59:01 -0800 Subject: [PATCH 040/170] fix(desktop): input during window teardown no longer throws in the main process (#33620) --- apps/desktop/src/window/DesktopWindow.test.ts | 49 +++++++++++++++++++ apps/desktop/src/window/DesktopWindow.ts | 2 + 2 files changed, 51 insertions(+) diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 3e461303556a..91d034cbd772 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -697,6 +697,55 @@ describe("DesktopWindow", () => { }), ); + it.effect("ignores input that arrives after the window is destroyed", () => + Effect.gen(function* () { + const fakeWindow = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const layer = layerTest({ + window: fakeWindow.window, + createCount, + mainWindow, + }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + + const beforeInput = fakeWindow.webContentsListeners.get("before-input-event"); + const inputEvent = fakeWindow.webContentsListeners.get("input-event"); + if (!beforeInput || !inputEvent) { + return yield* Effect.die("input listeners were not registered"); + } + + // Electron throws on any member access of a destroyed BrowserWindow. + fakeWindow.isDestroyed.mockReturnValue(true); + Object.defineProperty(fakeWindow.window, "webContents", { + get: () => { + throw new TypeError("Object has been destroyed"); + }, + }); + + // A held Cmd+Q quits from the grace timer, so the trailing Q keyUp lands here. + assert.doesNotThrow(() => + beforeInput( + { preventDefault: () => {} }, + { + type: "keyUp", + isAutoRepeat: false, + key: "q", + meta: true, + control: false, + alt: false, + shift: false, + }, + ), + ); + assert.doesNotThrow(() => inputEvent({}, { type: "gestureScrollEnd" })); + }).pipe(Effect.provide(layer)); + }), + ); + // Chromium hands the main window's zoom level down to embedded preview // guests, so every app zoom has to put the preview browser back at its own // zoom or zooming the UI drags the previewed page with it. diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index b8446f78740c..45a54714ca26 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -705,6 +705,7 @@ export const make = Effect.gen(function* () { }); window.webContents.on("before-input-event", (event, input) => { quitShortcutHandler(event, input); + if (window.isDestroyed()) return; // Cmd/Ctrl+W reaches the renderer; DevTools uses the native menu shortcut. window.webContents.setIgnoreMenuShortcuts( (environment.platform === "darwin" ? input.meta : input.control) && @@ -720,6 +721,7 @@ export const make = Effect.gen(function* () { } }); window.webContents.on("input-event", (_event, input) => { + if (window.isDestroyed()) return; if (input.type === "gestureScrollBegin") { window.webContents.send(TRACKPAD_SCROLL_BEGIN_CHANNEL); } else if (input.type === "gestureScrollEnd") { From d6d1763d415c59735708036ab790c540ef962cf0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anton=20=F0=9F=8C=BB?= Date: Tue, 10 Nov 2026 22:59:40 +0100 Subject: [PATCH 041/170] fix(web): sent messages keep the numbers written on list items (#33820) Co-authored-by: Claude Opus 5.5 Co-authored-by: Yash Singh --- .../components/ChatMarkdown.browser.test.tsx | 33 ++++++++++ apps/web/src/components/ChatMarkdown.tsx | 22 ++++--- .../chat/TimelineUserMessageRow.tsx | 6 +- apps/web/src/index.css | 4 ++ apps/web/src/markdown-clipboard.test.ts | 12 ++++ apps/web/src/markdown-clipboard.ts | 11 +++- .../shared/src/markdownListIndentation.ts | 5 ++ .../shared/src/markdownOrderedListNumbers.ts | 62 +++++++++++++++++++ packages/shared/src/markdownPipeline.test.ts | 44 ++++++++++++- packages/shared/src/markdownPipeline.ts | 5 ++ 10 files changed, 192 insertions(+), 12 deletions(-) create mode 100644 packages/shared/src/markdownOrderedListNumbers.ts diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index 76b77f15ea67..b03612507f91 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -9,6 +9,7 @@ import "../index.css"; import { filesystemEnvironment } from "../state/filesystem"; import { useRightPanelStore } from "../rightPanelStore"; +import { remarkEnableOrderedListNumbers } from "@t3tools/shared/markdownPipeline"; import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; import { HostImageUrlContext } from "./chat/hostImageUrl"; @@ -162,6 +163,38 @@ function buttonsLabelled(container: HTMLElement, label: string) { ); } +const SOURCE_NUMBER_PLUGINS = [remarkEnableOrderedListNumbers]; + +it("keeps decimal markers in nested user lists while documents keep their counter styles", async () => { + setup(); + const text = "1. Outer\n 1. Nested\n 7. Skipped\n 1. Deeper\n 4. Fourth"; + await using screen = await render( +
+
+

User message

+ +
+
+

Markdown preview

+ +
+
, + ); + await expect.element(screen.getByText("User message", { exact: true })).toBeVisible(); + const [message, preview] = screen.container.querySelectorAll(".chat-markdown"); + expect( + [...message!.querySelectorAll("ol")].map((list) => getComputedStyle(list).listStyleType), + ).toEqual(["decimal", "decimal", "decimal"]); + expect( + [...preview!.querySelectorAll("ol")].map((list) => getComputedStyle(list).listStyleType), + ).toEqual(["decimal", "lower-alpha", "lower-roman"]); +}); + it("shows unavailable audio when a workspace embed has no thread", async () => { setup(); await using screen = await renderText("![recording](clip.wav)"); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index e7e55fd07832..0b0116be549c 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -322,13 +322,18 @@ function CodexArtifactTemplateCard(props: { const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/; function orderedListGutterStyle( - itemCount: number, + itemValues: ReadonlyArray, start: unknown, ): { "--list-gutter": string } | undefined { const parsedStart = Number.parseInt(String(start ?? 1), 10); - const firstNumber = Number.isNaN(parsedStart) ? 1 : parsedStart; - const lastNumber = firstNumber + Math.max(itemCount - 1, 0); - const markerWidth = Math.max(String(firstNumber).length, String(lastNumber).length); + let number = Number.isNaN(parsedStart) ? 1 : parsedStart; + let markerWidth = String(number).length; + for (const value of itemValues) { + const written = Number.parseInt(String(value ?? ""), 10); + if (!Number.isNaN(written)) number = written; + markerWidth = Math.max(markerWidth, String(number).length); + number += 1; + } if (markerWidth <= 1) return undefined; return { "--list-gutter": `${markerWidth + 2}ch` }; } @@ -1017,10 +1022,11 @@ const CHAT_MARKDOWN_COMPONENTS = { ); }, ol: function MarkdownOrderedList({ node, start, style, ...props }) { - const itemCount = - node?.children?.filter((child) => child.type === "element" && child.tagName === "li") - .length ?? 0; - const gutterStyle = orderedListGutterStyle(itemCount, start); + const itemValues = + node?.children?.flatMap((child) => + child.type === "element" && child.tagName === "li" ? [child.properties.value] : [], + ) ?? []; + const gutterStyle = orderedListGutterStyle(itemValues, start); return (
    ); diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsx index 79f0c1fc9a41..808e52714da3 100644 --- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx +++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx @@ -1,5 +1,6 @@ import { InlineAudioPreview } from "../files/InlineAudioPreview"; import { filePreviewKind } from "@t3tools/shared/filePreview"; +import { remarkEnableOrderedListNumbers } from "@t3tools/shared/markdownPipeline"; import { findRevealRef } from "./markdownFindContext"; import { type EnvironmentId, @@ -1184,6 +1185,8 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop ); }); +const USER_MESSAGE_REMARK_PLUGINS = [remarkEnableOrderedListNumbers]; + const UserMessageBody = memo(function UserMessageBody(props: { text: string; renderContextReference?: (reference: ChatMarkdownContextReference) => ReactNode; @@ -1200,9 +1203,10 @@ const UserMessageBody = memo(function UserMessageBody(props: { cwd={props.markdownCwd} threadRef={ctx.threadRef ?? undefined} skills={props.skills} - className="text-foreground" + className="text-foreground user-message-markdown" lineBreaks parseRawHtml={false} + extraRemarkPlugins={USER_MESSAGE_REMARK_PLUGINS} renderContextReference={props.renderContextReference} headingLevelOffset={MESSAGE_HEADING_LEVEL} /> diff --git a/apps/web/src/index.css b/apps/web/src/index.css index b24265d02197..40daa0da7dcc 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -2012,6 +2012,10 @@ code { list-style-type: lower-roman; } +.chat-markdown.user-message-markdown ol { + list-style-type: decimal; +} + .chat-markdown li + li { margin-top: 0.25rem; } diff --git a/apps/web/src/markdown-clipboard.test.ts b/apps/web/src/markdown-clipboard.test.ts index ac7afbc8145a..f389b686742a 100644 --- a/apps/web/src/markdown-clipboard.test.ts +++ b/apps/web/src/markdown-clipboard.test.ts @@ -197,6 +197,18 @@ describe("serializeRenderedMarkdownFragment", () => { expect(serializeRenderedMarkdownFragment(asNode(container))).toBe("first line\nsecond line"); }); + it("preserves explicit ordered-list values and continues from resets when copying", () => { + const list = new FakeElement("OL", [], { start: "0" }).append( + new FakeElement("LI").append(new FakeText("A")), + new FakeElement("LI", [], { value: "5" }).append(new FakeText("B")), + new FakeElement("LI").append(new FakeText("C")), + new FakeElement("LI", [], { value: "0" }).append(new FakeText("D")), + ); + expect(serializeRenderedMarkdownFragment(asNode(new FakeElement("DIV").append(list)))).toBe( + "0. A\n5. B\n6. C\n0. D", + ); + }); + it("keeps fences when a bare list item sits alongside the code block", () => { const container = new FakeElement("DIV").append( new FakeElement("UL").append(new FakeElement("LI")), diff --git a/apps/web/src/markdown-clipboard.ts b/apps/web/src/markdown-clipboard.ts index 2364a6c77c4e..cf55bb8101ae 100644 --- a/apps/web/src/markdown-clipboard.ts +++ b/apps/web/src/markdown-clipboard.ts @@ -144,10 +144,17 @@ function serializeListItem( } function serializeList(list: Element, ordered: boolean, inTableCell: boolean): string { - const start = Number.parseInt(list.getAttribute("start") ?? "1", 10) || 1; + const start = Number.parseInt(list.getAttribute("start") ?? "1", 10); const items = [...list.children].filter((child) => child.tagName === "LI"); if (items.length === 0) return ""; - return `${items.map((item, index) => serializeListItem(item, ordered, start + index, inTableCell)).join("\n")}\n\n`; + let next = Number.isNaN(start) ? 1 : start; + return `${items + .map((item) => { + const value = Number.parseInt(item.getAttribute("value") ?? "", 10); + if (ordered && !Number.isNaN(value)) next = value; + return serializeListItem(item, ordered, next++, inTableCell); + }) + .join("\n")}\n\n`; } function serializeBlockquote(quote: Element, inTableCell: boolean): string { diff --git a/packages/shared/src/markdownListIndentation.ts b/packages/shared/src/markdownListIndentation.ts index f41e6d2eddde..39342890d1c2 100644 --- a/packages/shared/src/markdownListIndentation.ts +++ b/packages/shared/src/markdownListIndentation.ts @@ -1,3 +1,5 @@ +import { keepOrderedListNumbers, keepsOrderedListNumbers } from "./markdownOrderedListNumbers.ts"; + interface MarkdownPosition { readonly start?: { readonly line?: number; @@ -91,6 +93,9 @@ function parseRecoveredMarkdown(value: string, parser: MarkdownParser): Recovere function blocksFromIndentedCode(node: MarkdownAstNode, parser: MarkdownParser): RecoveredMarkdown { const value = typeof node.value === "string" ? node.value.trim() : ""; const recovered = parseRecoveredMarkdown(value, parser); + if (keepsOrderedListNumbers(parser)) { + for (const block of recovered.blocks) keepOrderedListNumbers(block, recovered.source); + } const first = recovered.blocks[0]; return { ...recovered, diff --git a/packages/shared/src/markdownOrderedListNumbers.ts b/packages/shared/src/markdownOrderedListNumbers.ts new file mode 100644 index 000000000000..32b3b38de563 --- /dev/null +++ b/packages/shared/src/markdownOrderedListNumbers.ts @@ -0,0 +1,62 @@ +import type { Root } from "mdast"; +import type { Transformer } from "unified"; + +interface MarkdownListNode { + readonly type: string; + readonly ordered?: boolean | null | undefined; + readonly start?: number | null | undefined; + readonly position?: + | { readonly start?: { readonly offset?: number | undefined } | undefined } + | undefined; + data?: { hProperties?: Record | undefined } | undefined; + children?: MarkdownListNode[] | undefined; +} + +const WRITTEN_NUMBER = /[ \t]*(\d{1,9})[.)]/y; + +/** + * CommonMark numbers an ordered list from its first marker only, so answers to questions 3 and 5 + * would render as 3 and 4. An item whose written number breaks the sequence keeps it. `source` is + * the text the node's offsets point into. + */ +export function keepOrderedListNumbers(node: MarkdownListNode, source: string): void { + if (!node.children) return; + if (node.type === "list" && node.ordered) { + let expected = node.start ?? 1; + for (const item of node.children) { + 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.data = { + ...item.data, + hProperties: { ...item.data?.hProperties, value: String(value) }, + }; + } + expected = value + 1; + } + } + for (const child of node.children) keepOrderedListNumbers(child, source); +} + +const enabledProcessors = new WeakSet(); + +/** + * Opts a processor in. User messages use it so the sent bubble shows the numbers the composer + * showed and the agent received; agent replies and files keep CommonMark numbering. + */ +export function remarkEnableOrderedListNumbers(this: object): undefined { + enabledProcessors.add(this); +} + +export function keepsOrderedListNumbers(processor: object): boolean { + return enabledProcessors.has(processor); +} + +/** Sits before list recovery so offsets still point into the file. */ +export function remarkKeepOrderedListNumbers(this: object): Transformer { + return (tree, file) => { + if (enabledProcessors.has(this)) keepOrderedListNumbers(tree, String(file)); + }; +} diff --git a/packages/shared/src/markdownPipeline.test.ts b/packages/shared/src/markdownPipeline.test.ts index 0493580e9362..3d4e69be16d9 100644 --- a/packages/shared/src/markdownPipeline.test.ts +++ b/packages/shared/src/markdownPipeline.test.ts @@ -1,5 +1,5 @@ import { expect, it } from "vite-plus/test"; -import { unified } from "unified"; +import { type PluggableList, unified } from "unified"; import rehypeRaw from "rehype-raw"; import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; @@ -8,6 +8,7 @@ import { CHAT_MARKDOWN_REHYPE_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, + remarkEnableOrderedListNumbers, } from "./markdownPipeline.ts"; it.each([ @@ -309,6 +310,47 @@ it("keeps an image on its own line under a label but leaves inline images inline expect(render("Hard-wrapped\nprose")).toBe("Hard-wrapped\nprose"); }); +it("keeps the number written on each ordered list item only when enabled", () => { + type Node = { tagName?: string; properties?: { value?: unknown }; children?: Node[] }; + const values = (node: Node): unknown[] => [ + ...(node.tagName === "li" ? [node.properties?.value] : []), + ...(node.children ?? []).flatMap(values), + ]; + const renderer = (plugins: PluggableList) => { + const processor = unified() + .use(remarkParse) + .use(plugins) + .use(remarkRehype, { allowDangerousHtml: true }); + return (markdown: string) => + values(processor.runSync(processor.parse(markdown), markdown) as Node); + }; + const render = renderer([ + ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, + remarkEnableOrderedListNumbers, + ]); + + expect(render("3. first\n5. second\n6. third")).toEqual([undefined, "5", undefined]); + expect(render("1. one\n1. one again")).toEqual([undefined, "1"]); + expect(render("> 1. quoted\n> 4. skipped")).toEqual([undefined, "4"]); + expect(render("1. outer\n 1. nested\n 7. jump\n9. back")).toEqual([ + undefined, + undefined, + "7", + "9", + ]); + expect(render("1. one\n2. two\n- bullet")).toEqual([undefined, undefined, undefined]); + expect(render("- first block\n\n 3. first\n 5. second")).toEqual([ + undefined, + undefined, + "5", + ]); + expect( + renderer(CHAT_MARKDOWN_REMARK_PLUGINS)( + "3. first\n5. second\n\n- first block\n\n 3. first\n 5. second", + ), + ).toEqual([undefined, undefined, undefined, undefined, undefined]); +}); + it("moves a 's color-scheme sources onto its , which the renderer resolves", () => { const processor = unified() .use(remarkParse) diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index e4527a8a017c..6a49d0023b0a 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -11,6 +11,7 @@ import remarkBreaks from "remark-breaks"; import remarkGfm from "remark-gfm"; import { remarkGithubAlerts } from "./markdownGithubAlerts.ts"; import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts"; +import { remarkKeepOrderedListNumbers } from "./markdownOrderedListNumbers.ts"; import { CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES, remarkCodexDirectives, @@ -18,6 +19,8 @@ import { import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts"; import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts"; +export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts"; + type MarkdownImageHastNode = { type?: string; value?: string; @@ -230,6 +233,7 @@ export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ remarkKeepAutolinkSuffixes, remarkKeepWindowsPaths, remarkGithubAlerts, + remarkKeepOrderedListNumbers, remarkNormalizeListItemIndentation, remarkCodexDirectives, remarkBreakAroundImageLines, @@ -242,6 +246,7 @@ export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [ remarkKeepAutolinkSuffixes, remarkKeepWindowsPaths, remarkGithubAlerts, + remarkKeepOrderedListNumbers, remarkNormalizeListItemIndentation, remarkCodexDirectives, remarkBreakAroundImageLines, From 1a2a4a5e9684585c31eb55c1974fb32f8b1db2b7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 14:09:31 -0800 Subject: [PATCH 042/170] fix(server): quitting stops an agent-device daemon left by an earlier server (#33587) Co-authored-by: Claude Opus 5.5 --- apps/server/src/device/DeviceToolchain.ts | 13 +++ .../server/src/device/LocalDeviceHost.test.ts | 85 ++++++++++++++++++- apps/server/src/device/LocalDeviceHost.ts | 67 +++++++++------ 3 files changed, 136 insertions(+), 29 deletions(-) diff --git a/apps/server/src/device/DeviceToolchain.ts b/apps/server/src/device/DeviceToolchain.ts index 250e6cf14f3b..eb299f9e29cd 100644 --- a/apps/server/src/device/DeviceToolchain.ts +++ b/apps/server/src/device/DeviceToolchain.ts @@ -209,6 +209,19 @@ export const isDeviceHubInstalled = (baseDir: string) => export const isAgentDeviceInstalled = (baseDir: string) => isToolInstalled(baseDir, AGENT_DEVICE_SPEC, (paths) => paths.agentDevice); +/** Entry of the first installed agent-device among `versions`; never installs. */ +export const installedAgentDeviceEntry = Effect.fn("DeviceToolchain.installedAgentDeviceEntry")( + function* (baseDir: string, versions: ReadonlyArray) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + for (const version of versions) { + const paths = toolPaths(path, baseDir, { ...AGENT_DEVICE_SPEC, version }); + if (yield* isInstalled(fs, paths, version)) return paths.entryPath; + } + return null; + }, +); + export const deviceToolVersions = Effect.fn("DeviceToolchain.versions")(function* ( baseDir: string, running: { hub?: string; agent?: string } = {}, diff --git a/apps/server/src/device/LocalDeviceHost.test.ts b/apps/server/src/device/LocalDeviceHost.test.ts index 6b86a4d03261..e133b4f9db36 100644 --- a/apps/server/src/device/LocalDeviceHost.test.ts +++ b/apps/server/src/device/LocalDeviceHost.test.ts @@ -40,6 +40,7 @@ const agentFixture = Effect.fn("agentFixture")(function* ( stateDir: string, ) => Effect.Effect, avdOutput: ProcessRunner.ProcessRunOutput = processOutput(0), + previousDaemon?: typeof LocalDeviceHost.__testing.AgentDeviceDaemonFile.Type, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -47,6 +48,7 @@ const agentFixture = Effect.fn("agentFixture")(function* ( const hub = { running: true, spawnFails: false }; const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata")); const daemonHealthy = yield* Ref.make(true); + const runs: Array = []; for (const [name, version, entry] of [ ["expo-device-hub", DEVICE_HUB_VERSION, "dist/server/cli.mjs"], ["agent-device", AGENT_DEVICE_VERSION, "bin/agent-device.mjs"], @@ -57,6 +59,10 @@ const agentFixture = Effect.fn("agentFixture")(function* ( yield* fs.writeFileString(entryPath, ""); yield* fs.writeFileString(path.join(installDir, ".install-complete"), version!); } + if (previousDaemon) { + yield* fs.makeDirectory(stateDir, { recursive: true }); + yield* fs.writeFileString(path.join(stateDir, "daemon.json"), JSON.stringify(previousDaemon)); + } const host = yield* LocalDeviceHost.make().pipe( Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)), Effect.provideService(HostProcess.Environment, { HOME: baseDir, PATH: "" }), @@ -92,10 +98,12 @@ const agentFixture = Effect.fn("agentFixture")(function* ( ), ), Effect.provideService(ProcessRunner.ProcessRunner, { - run: (input) => - input.args.includes("devices") + run: (input) => { + runs.push(input); + return input.args.includes("devices") ? startup(stateDir) - : Effect.succeed(input.args.includes("-list-avds") ? avdOutput : processOutput(0)), + : Effect.succeed(input.args.includes("-list-avds") ? avdOutput : processOutput(0)); + }, }), Effect.provideService( HttpClient.HttpClient, @@ -114,7 +122,7 @@ const agentFixture = Effect.fn("agentFixture")(function* ( ), ); yield* host.ensureReady(() => Effect.void); - return { host, fs, stateDir, hub, daemonHealthy }; + return { host, fs, baseDir, stateDir, hub, daemonHealthy, runs }; }); describe("AgentDevice startup", () => { @@ -276,6 +284,75 @@ describe("AgentDevice startup", () => { expect((yield* host.current)?.releaseAgentSession).toBeTypeOf("function"); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + + it.effect("stops a previous server's daemon with the agent-device version it recorded", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const { host, fs, baseDir, runs } = yield* agentFixture( + () => Effect.die("A session that never readies agent tools must not start the daemon"), + processOutput(0), + { httpPort: 12345, token: "previous-token", pid: process.pid, version: "0.0.1" }, + ); + const olderInstall = path.join(baseDir, "tools", "agent-device", "0.0.1"); + const olderEntry = path.join( + olderInstall, + "node_modules", + "agent-device", + "bin", + "agent-device.mjs", + ); + yield* fs.makeDirectory(path.dirname(olderEntry), { recursive: true }); + yield* fs.writeFileString(olderEntry, ""); + yield* fs.writeFileString(path.join(olderInstall, ".install-complete"), "0.0.1"); + yield* host.stop; + expect(runs.find((run) => run.args.includes("daemon"))?.args[0]).toBe(olderEntry); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + // regression: #33552 a daemon left by a previous server survived every later graceful quit + it.effect("stops a previous server's daemon with the current pin when its version is gone", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const { host, baseDir, stateDir, runs } = yield* agentFixture( + () => Effect.die("A session that never readies agent tools must not start the daemon"), + processOutput(0), + { httpPort: 12345, token: "previous-token", pid: process.pid, version: "0.0.1" }, + ); + yield* host.stop; + expect(runs.find((run) => run.args.includes("daemon"))?.args).toEqual([ + path.join( + baseDir, + "tools", + "agent-device", + AGENT_DEVICE_VERSION, + "node_modules", + "agent-device", + "bin", + "agent-device.mjs", + ), + "daemon", + "stop", + "--state-dir", + stateDir, + ]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("drops a dead daemon's record without running agent-device when the host stops", () => + Effect.gen(function* () { + // Above the Linux and macOS PID limits, so never a live process. + const deadPid = 4_194_305; + const path = yield* Path.Path; + const { host, fs, stateDir, runs } = yield* agentFixture( + () => Effect.die("A session that never readies agent tools must not start the daemon"), + processOutput(0), + { httpPort: 12345, token: "previous-token", pid: deadPid, version: AGENT_DEVICE_VERSION }, + ); + yield* host.stop; + expect(runs.filter((run) => run.args.includes("daemon"))).toEqual([]); + expect(yield* fs.exists(path.join(stateDir, "daemon.json"))).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); }); const diagnose = ( diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index afb408f5cc0f..c5097509dcad 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -47,7 +47,9 @@ import { isAgentDeviceInstalled, isDeviceHubInstalled, deviceToolVersions, + AGENT_DEVICE_VERSION, DEVICE_HUB_VERSION, + installedAgentDeviceEntry, } from "./DeviceToolchain.ts"; const HUB_READY_TIMEOUT_MS = 30_000; @@ -624,28 +626,44 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { } }); - const stopAgentDeviceDaemon = ( - agentTool: { readonly entryPath: string; readonly nodePath: string } | null, - ) => - agentTool - ? runner - .run({ - command: agentTool.nodePath, - args: [ - agentTool.entryPath, - "daemon", - "stop", - "--state-dir", - agentDeviceStateDir(path, config.stateDir), - ], - env: { ...hostEnvironment, AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1" }, - timeout: Duration.seconds(10), - timeoutBehavior: "timedOutResult", - }) - .pipe(Effect.ignore) - : Effect.void; - - let agentToolRef: { readonly entryPath: string; readonly nodePath: string } | null = null; + // The daemon may predate this process (an earlier server was killed, possibly on an + // older pin), so stop it with the CLI of its recorded version when that is installed. + const stopAgentDeviceDaemon = Effect.gen(function* () { + if (!(yield* fs.exists(daemonFilePath()))) return; + const recorded = yield* readDaemonFile().pipe(Effect.option); + if ( + Option.isSome(recorded) && + recorded.value.pid && + !(yield* isProcessAlive(recorded.value.pid)) + ) { + return yield* fs.remove(daemonFilePath(), { force: true }); + } + const entryPath = yield* installedAgentDeviceEntry(config.baseDir, [ + ...(Option.isSome(recorded) && recorded.value.version ? [recorded.value.version] : []), + AGENT_DEVICE_VERSION, + ]); + if (!entryPath) return; + const nodePath = yield* resolveNodeExecutable("Local device support", hostEnvironment).pipe( + Effect.provideService(HostProcess.Platform, hostPlatform), + ); + yield* runner.run({ + command: nodePath, + args: [ + entryPath, + "daemon", + "stop", + "--state-dir", + agentDeviceStateDir(path, config.stateDir), + ], + env: { ...hostEnvironment, AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1" }, + timeout: Duration.seconds(10), + timeoutBehavior: "timedOutResult", + }); + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.ignore, + ); const ensureHubReady = Effect.fn("LocalDeviceHost.ensureHubReady")(function* ( onPhase: (phase: "installing" | "starting", detail?: string) => Effect.Effect, @@ -760,7 +778,6 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { }), ), ); - agentToolRef = { entryPath: agentTool.entryPath, nodePath: running.hub.nodePath }; yield* onPhase("starting"); const agentDevice = yield* startAgentDeviceDaemon(agentTool, running.hub.nodePath); yield* pruneLocalDeviceTools(config.baseDir, running.hub.nodePath, "agent").pipe( @@ -843,7 +860,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { const stopAgent: DeviceHost.DeviceHost["Service"]["stopAgent"] = startLock.withPermits(1)( Effect.gen(function* () { - yield* stopAgentDeviceDaemon(agentToolRef); + yield* stopAgentDeviceDaemon; yield* Ref.update(runningRef, (running) => running ? { ...running, agentDevice: null } : running, ); @@ -855,7 +872,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { const running = yield* Ref.getAndSet(runningRef, null); yield* stopHub(running?.hub); yield* fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore); - yield* stopAgentDeviceDaemon(agentToolRef); + yield* stopAgentDeviceDaemon; }), ); From 3cb99ced5b79f74628065952098cc1cf2d829f0e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 14:28:00 -0800 Subject: [PATCH 043/170] fix(mobile): attaching larger images no longer crashes with a BigInt error (#34087) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/lib/attachmentUpload.test.ts | 15 +++++++++++++++ apps/mobile/src/lib/attachmentUpload.ts | 4 +++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/apps/mobile/src/lib/attachmentUpload.test.ts b/apps/mobile/src/lib/attachmentUpload.test.ts index 54dfa536ff36..0097ab7ed77c 100644 --- a/apps/mobile/src/lib/attachmentUpload.test.ts +++ b/apps/mobile/src/lib/attachmentUpload.test.ts @@ -321,12 +321,27 @@ describe("prepareTurnAttachments", () => { // regression: #9713 read file-backed image drafts before enabling them it("uploads a file-backed image from its owned copy without staging base64", async () => { + mocks.upload.mockImplementation( + async ( + _uri: string, + _url: string, + options: { onProgress?: (event: { bytesSent: unknown; totalBytes: unknown }) => void }, + ) => { + // expo-modules-jsi delivers native Int64 progress counts as BigInt. + options.onProgress?.({ bytesSent: BigInt(1), totalBytes: BigInt(4) }); + return { status: 204, body: "", headers: {} }; + }, + ); + const progress: Array = []; const prepared = await prepareTurnAttachments({ environmentId, attachments: [fileBackedImage], supportsImageUploads: true, + onUploadProgress: (_, value) => progress.push(value), }); + expect(progress).toEqual([0.25]); + expect(mocks.upload).toHaveBeenCalledWith( fileBackedImage.fileUri, "https://environment.example/api/attachments/upload/signed", diff --git a/apps/mobile/src/lib/attachmentUpload.ts b/apps/mobile/src/lib/attachmentUpload.ts index aef8dd444751..57699af22819 100644 --- a/apps/mobile/src/lib/attachmentUpload.ts +++ b/apps/mobile/src/lib/attachmentUpload.ts @@ -232,8 +232,10 @@ async function uploadFileBytes( signal, ...(onProgress ? { + // Native events carry Int64 counts, which expo-modules-jsi delivers as BigInt despite the `number` type. onProgress: ({ bytesSent, totalBytes }) => { - if (totalBytes > 0) onProgress(bytesSent / totalBytes); + const total = Number(totalBytes); + if (total > 0) onProgress(Number(bytesSent) / total); }, } : {}), From 17a6a01d84e3adf9f29df2639d6b6079a434e1b2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 14:35:41 -0800 Subject: [PATCH 044/170] feat(mobile): pick a voice environment once, then its method (#34073) Co-authored-by: Claude Opus 5.5 --- apps/mobile/src/components/ui/ListRow.tsx | 51 +- .../features/settings/CloudVoiceSection.tsx | 495 ++++++++++-------- .../settings/SettingsVoiceRouteScreen.tsx | 139 +++-- .../features/settings/VoiceModelSection.tsx | 71 +-- 4 files changed, 439 insertions(+), 317 deletions(-) diff --git a/apps/mobile/src/components/ui/ListRow.tsx b/apps/mobile/src/components/ui/ListRow.tsx index de8bba51beb3..8f2ce11259bc 100644 --- a/apps/mobile/src/components/ui/ListRow.tsx +++ b/apps/mobile/src/components/ui/ListRow.tsx @@ -1,17 +1,27 @@ -import { Platform } from "react-native"; +import { Platform, View } from "react-native"; import { useResolveClassNames } from "uniwind"; import { SymbolView } from "./AppSymbol"; import { ListRowLayout, type ListRowContentProps } from "./ListRowLayout"; +import { RadioIndicator } from "./RadioIndicator"; import { RowPressable } from "./RowPressable"; -export function ListRow(props: ListRowContentProps & { readonly onPress: () => void }) { +export function ListRow( + props: ListRowContentProps & { + readonly onPress: () => void; + /** Marks the row as the chosen option while it still navigates. */ + readonly selected?: boolean; + }, +) { const rippleStyle = useResolveClassNames("bg-subtle-strong"); return ( v + + {props.selected === undefined ? null : ( + + {Platform.OS === "android" ? ( + + ) : props.selected ? ( + + ) : null} + + )} + + } /> diff --git a/apps/mobile/src/features/settings/CloudVoiceSection.tsx b/apps/mobile/src/features/settings/CloudVoiceSection.tsx index 684f8dbc8376..6ca61ece7b90 100644 --- a/apps/mobile/src/features/settings/CloudVoiceSection.tsx +++ b/apps/mobile/src/features/settings/CloudVoiceSection.tsx @@ -21,7 +21,7 @@ import { import * as Schema from "effect/Schema"; import Constants from "expo-constants"; import { AsyncResult } from "effect/reactivity"; -import { useState } from "react"; +import { type ReactNode, useState } from "react"; import { ScrollView, TextInput, View } from "react-native"; import { Sheet } from "../../components/ui/Sheet"; import * as Dialog from "../../components/ui/Dialog"; @@ -30,6 +30,7 @@ import { AppText as Text } from "../../components/ui/AppText"; import { ListActionRow } from "../../components/ui/ListActionRow"; import { ListChoiceRow } from "../../components/ui/ListChoiceRow"; import { Chip } from "../../components/ui/Chip"; +import { ListSection } from "../../components/ui/ListSection"; import type { EnvironmentPresentation } from "../../state/environments"; import { useEnvironmentScope } from "../../state/session"; import { @@ -40,7 +41,6 @@ import { cloudVoiceModelsAtom, runSpeech, } from "../voice-input/voiceDestination"; -import { SettingsSection } from "./components/SettingsSection"; type CloudDestination = Extract; type Props = { environment: EnvironmentPresentation; active: CloudDestination | null }; @@ -48,23 +48,38 @@ const isApiKey = Schema.is(CloudSpeechApiKey); const isModelId = Schema.is(CloudSpeechModelId); const MODEL_ROWS = 6; -export function CloudVoiceSection({ environment, active }: Props) { - const [open, setOpen] = useState(false); +/** The cloud method row for one environment; opens the provider sheet. */ +export function CloudVoiceChoice({ + environment, + active, + open, + onOpenChange, +}: Props & { open: boolean; onOpenChange: (open: boolean) => void }) { + const usable = useAtomValue(cloudVoiceConnectionAtom(environment.environmentId)) !== null; return ( - - + setOpen(true)} + selected={active !== null} + disabled={!usable} + separated + onPress={() => onOpenChange(true)} /> {open && ( - setOpen(false)} /> + onOpenChange(false)} + /> )} - + ); } @@ -92,54 +107,70 @@ function ModelPicker({ const shown = showAll ? matches : matches.slice(0, MODEL_ROWS); const delisted = current !== undefined && !models.some((model) => model.id === current); return ( - <> - - {delisted ? ( - - OpenRouter no longer lists {current}. Dictation stays off until you choose another model. - - ) : null} + + + + {selected && !shown.some((model) => model.id === selected.id) ? ( {}} /> ) : null} - {shown.map((model, index) => ( + {shown.map((model) => ( 0} + separated disabled={disabled} onPress={() => onChange(model.id)} /> ))} {matches.length === 0 ? ( - No transcription model matches. + + + No transcription model matches. + + ) : matches.length > shown.length ? ( - setShowAll(true)} - /> + + setShowAll(true)} + /> + ) : null} - + ); } +/** A hairline above a row that has no `separated` prop of its own. */ +function Separated({ children }: { children: ReactNode }) { + return {children}; +} + function CloudChoices({ environment, active, onClose }: Props & { onClose: () => void }) { const id = environment.environmentId; const connection = useAtomValue(cloudVoiceConnectionAtom(id)); @@ -223,58 +254,35 @@ function CloudChoices({ environment, active, onClose }: Props & { onClose: () => onClose(); }; const catalog = AsyncResult.isSuccess(models) ? (models.value?.models ?? null) : null; - const content = - !AsyncResult.isSuccess(keys) || !keys.value || !connection ? ( - - ) : ( - CloudSpeechProvider.literals.map((provider) => { - if (editing && provider !== editing.provider) return null; - const label = CLOUD_SPEECH_LABELS[provider]; - const company = CLOUD_SPEECH_PROVIDER_NAMES[provider]; - const routed = provider === "openrouter"; - const disclosure = cloudSpeechDisclosure(provider, environment.label); - const saved = keys.value![provider]; - const isActive = active?.provider === provider; - const isEditing = editing?.provider === provider; - const modelChosen = - isModelId(model) && (catalog?.some((entry) => entry.id === model) ?? false); - const modelChanged = model !== (activeModel ?? ""); - const original = environment.serverConfig?.settings.cloudSpeechCredentials?.[provider]; - const keyChanged = - credential !== undefined && - !( - isSecretReference(credential) && - isSecretReference(original) && - original.provider === credential.provider && - original.reference === credential.reference - ); - const routedReady = - modelChosen && - (draft.trim() ? credential !== undefined : Boolean(saved)) && - (!isActive || modelChanged || keyChanged); - const saveRouted = () => { - if (!routedReady || !isModelId(model)) return; - const grantChanges = !isActive || modelChanged; - if (credential !== undefined && keyChanged) - return void changeKey(provider, credential, model); - // Model-only changes never write to the environment. - if (grantChanges) enable(() => chooseVoiceDestination(id, provider, model)); - onClose(); - }; - return ( - - {!isEditing && ( + const content = (() => { + if (!AsyncResult.isSuccess(keys) || !keys.value || !connection) + return ( + + + + ); + const saved = keys.value; + if (!editing) + return ( + + {CloudSpeechProvider.literals.map((provider, index) => { + const label = CLOUD_SPEECH_LABELS[provider]; + const routed = provider === "openrouter"; + const key = saved[provider]; + const isActive = active?.provider === provider; + return ( /> } selected={isActive} - disabled={saved === undefined || (!saved && !canManage) || saving} + separated={index > 0} + disabled={key === undefined || (!key && !canManage) || saving} description={ - saved === undefined + key === undefined ? "Update the environment to use this provider" : isActive && routed ? `${activeModel} · Tap to change model${canManage ? " or key" : ""}` - : isActive && saved && canManage + : isActive && key && canManage ? "Tap to manage key" - : saved + : key ? routed ? "API key saved · choose a model to use it" - : "API key saved on this environment" + : "API key saved" : canManage ? "Add an API key to use this provider" : "Ask an environment administrator to add an API key" } onPress={() => { if (routed) return edit(provider, !isActive); - if (!saved) return edit(provider, true); + if (!key) return edit(provider, true); if (isActive) { if (canManage) edit(provider, false); return; } Dialog.confirm({ title: `Use ${label} for dictation?`, - message: `${disclosure} Select This device to stop sharing.`, + message: `${cloudSpeechDisclosure(provider, environment.label)} Select This device to stop sharing.`, confirmText: `Use ${label}`, onConfirm: () => enable(pendingCloudVoiceChoice(id, provider)), }); }} /> - )} - {isEditing && routed && ( - <> - {disclosure} - {catalog ? ( - + ); + + const provider = editing.provider; + const label = CLOUD_SPEECH_LABELS[provider]; + const company = CLOUD_SPEECH_PROVIDER_NAMES[provider]; + const routed = provider === "openrouter"; + const disclosure = cloudSpeechDisclosure(provider, environment.label); + const key = saved[provider]; + const isActive = active?.provider === provider; + const modelChosen = isModelId(model) && (catalog?.some((entry) => entry.id === model) ?? false); + const modelChanged = model !== (activeModel ?? ""); + const original = environment.serverConfig?.settings.cloudSpeechCredentials?.[provider]; + const keyChanged = + credential !== undefined && + !( + isSecretReference(credential) && + isSecretReference(original) && + original.provider === credential.provider && + original.reference === credential.reference + ); + const routedReady = + modelChosen && + (draft.trim() ? credential !== undefined : Boolean(key)) && + (!isActive || modelChanged || keyChanged); + const saveRouted = () => { + if (!routedReady || !isModelId(model)) return; + const grantChanges = !isActive || modelChanged; + if (credential !== undefined && keyChanged) + return void changeKey(provider, credential, model); + // Model-only changes never write to the environment. + if (grantChanges) enable(() => chooseVoiceDestination(id, provider, model)); + onClose(); + }; + const submit = () => { + if (routed) saveRouted(); + else if (credential) void changeKey(provider, credential); + }; + const keyFooter = + draft && !credential + ? (source?.invalidReferenceMessage ?? "Enter a valid API key.") + : routed + ? key && !credential + ? "Uses the API key saved on this environment. The model choice applies only to this device." + : `Anyone with dictation access to ${environment.label} can bill this key.` + : editing.enable + ? `Anyone with dictation access to ${environment.label} can bill this key.` + : `Updates the ${company} key on ${environment.label}. Your dictation destination stays the same.`; + return ( + <> + {disclosure} + {routed ? ( + catalog ? ( + + ) : ( + + + + ) + ) : null} + {canManage ? ( + + + {sources.length > 0 && ( + + - ) : ( - { + setDraft(""); + setSourceId(null); + }} /> - )} - - )} - {isEditing && (canManage || routed) && ( - <> - {canManage && sources.length > 0 && ( - + {sources.map((candidate) => ( { setDraft(""); - setSourceId(null); + setSourceId(candidate.id); }} /> - {sources.map((candidate) => ( - { - setDraft(""); - setSourceId(candidate.id); - }} - /> - ))} - - )} - {canManage && ( - { - if (routed) saveRouted(); - else if (credential) void changeKey(provider, credential); - }} - value={draft} - onChangeText={setDraft} - className="mx-4 rounded-lg bg-background px-3 py-2 text-foreground" - /> - )} - {routed && !saved && !canManage ? ( - {}} - /> - ) : ( - { - if (routed) saveRouted(); - else if (credential) void changeKey(provider, credential); - }} - /> - )} - {saved && canManage && ( - - Dialog.confirm({ - title: `Remove the ${label} key from ${environment.label}?`, - message: "Everyone using it for dictation will lose access.", - confirmText: "Remove key", - destructive: true, - onConfirm: () => void changeKey(provider, null), - }) - } - /> - )} - - + ))} + + )} + + + + ) : null} + {canManage || routed ? ( + + {routed && !key && !canManage ? ( + {}} + /> + ) : ( + )} - - ); - }) + {key && canManage ? ( + + + Dialog.confirm({ + title: `Remove the ${label} key from ${environment.label}?`, + message: "Everyone using it for dictation will lose access.", + confirmText: "Remove key", + destructive: true, + onConfirm: () => void changeKey(provider, null), + }) + } + /> + + ) : null} + + ) : null} + + + + ); + })(); return ( {content} diff --git a/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx index 5f7328214cb1..4b0ca00e8866 100644 --- a/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx @@ -24,13 +24,14 @@ import * as Dialog from "../../components/ui/Dialog"; import { useEnvironments, type EnvironmentPresentation } from "../../state/environments"; import { chooseVoiceDestination, + cloudVoiceConnectionAtom, voiceConnectionAtom, voiceGrantAtom, - voiceSpeechStatusAtom, hasEnvironmentVoiceCapture, } from "../voice-input/voiceDestination"; -import { VoiceModelSection } from "./VoiceModelSection"; -import { CloudVoiceSection } from "./CloudVoiceSection"; +import { LocalModelChoice } from "./VoiceModelSection"; +import { CloudVoiceChoice } from "./CloudVoiceSection"; +import type { VoiceGrant } from "../voice-input/voiceGrantStorage"; import type { EnvironmentId } from "@t3tools/contracts"; import { ThreadSwipeable } from "../home/thread-swipe-actions"; import { ListActionRow as SettingsActionRow } from "../../components/ui/ListActionRow"; @@ -127,45 +128,81 @@ function saveDestination(id: EnvironmentId | null) { function EnvironmentChoice({ environment, selected, + onCloudOnly, }: { environment: EnvironmentPresentation; selected: boolean; + /** Called instead of a local grant when the environment only offers cloud transcription. */ + onCloudOnly: () => void; }) { - const usable = useAtomValue(voiceConnectionAtom(environment.environmentId)) !== null; - const status = AsyncResult.getOrElse( - useAtomValue(voiceSpeechStatusAtom(environment.environmentId)), - () => null, - ); + const local = useAtomValue(voiceConnectionAtom(environment.environmentId)) !== null; + const cloud = useAtomValue(cloudVoiceConnectionAtom(environment.environmentId)) !== null; + const usable = local || cloud; return ( { - if (!selected) - Dialog.confirm({ - title: `Send microphone audio to ${environment.label}?`, - message: `Finished recordings will be sent to ${environment.displayUrl ?? environment.label} for transcription. You can switch back to This device at any time.`, - confirmText: "Use environment", - onConfirm: () => saveDestination(environment.environmentId), - }); + if (selected) return; + if (!local) return onCloudOnly(); + Dialog.confirm({ + title: `Send microphone audio to ${environment.label}?`, + message: `Finished recordings will be sent to ${environment.displayUrl ?? environment.label} for transcription. You can switch back to This device at any time.`, + confirmText: "Use environment", + onConfirm: () => saveDestination(environment.environmentId), + }); }} /> ); } +/** How the selected environment transcribes: its own model or a cloud provider. */ +function EnvironmentMethodSection({ + environment, + grant, + cloudOpen, + onCloudOpenChange, +}: { + environment: EnvironmentPresentation; + grant: VoiceGrant | null; + cloudOpen: boolean; + onCloudOpenChange: (open: boolean) => void; +}) { + const id = environment.environmentId; + const destination = grant?.destination.environmentId === id ? grant.destination : null; + const cloudCapable = + environment.serverConfig?.environment.capabilities.cloudVoiceTranscription === true || + destination?.kind === "cloud"; + return ( + + saveDestination(id)} + /> + {cloudCapable ? ( + + ) : null} + + ); +} + export function SettingsVoiceRouteScreen() { const transcriber = useAtomValue(localVoiceTranscriberAtom); const grant = useAtomValue(voiceGrantAtom); @@ -175,6 +212,15 @@ export function SettingsVoiceRouteScreen() { (environment) => environment.environmentId === grant.destination.environmentId, ) : undefined; + // An environment whose cloud sheet is open; it may not hold the grant yet. + const [cloudSheet, setCloudSheet] = useState(null); + // A sheet whose environment lost cloud transcription is gone, so its pending choice is too. + const sheetEnvironment = environments.find( + (environment) => + environment.environmentId === cloudSheet && + environment.serverConfig?.environment.capabilities.cloudVoiceTranscription === true, + ); + const methodEnvironment = sheetEnvironment ?? grantEnvironment; const insets = useSafeAreaInsets(); const preferencesResult = useAtomValue(mobilePreferencesAtom); const savePreferences = useAtomSet(updateMobilePreferencesAtom); @@ -234,8 +280,11 @@ export function SettingsVoiceRouteScreen() { saveDestination(null)} + selected={!grant && !sheetEnvironment} + onPress={() => { + setCloudSheet(null); + saveDestination(null); + }} /> {hasEnvironmentVoiceCapture && environments.map((environment) => ( @@ -243,9 +292,11 @@ export function SettingsVoiceRouteScreen() { key={environment.environmentId} environment={environment} selected={ - grant?.destination.kind === "environment" && - grant.destination.environmentId === environment.environmentId + sheetEnvironment + ? sheetEnvironment.environmentId === environment.environmentId + : grant?.destination.environmentId === environment.environmentId } + onCloudOnly={() => setCloudSheet(environment.environmentId)} /> ))} {isReady && grant && !grantEnvironment ? ( @@ -259,30 +310,14 @@ export function SettingsVoiceRouteScreen() { /> ) : null} - {hasEnvironmentVoiceCapture && - environments - .filter( - (env) => - env.serverConfig?.environment.capabilities.cloudVoiceTranscription || - (grant?.destination.kind === "cloud" && - grant.destination.environmentId === env.environmentId), - ) - .map((environment) => ( - - ))} - {grantEnvironment && grant?.destination.kind === "environment" ? ( - + setCloudSheet(open ? methodEnvironment.environmentId : null) + } /> ) : null} {!grant && transcriber === null ? ( diff --git a/apps/mobile/src/features/settings/VoiceModelSection.tsx b/apps/mobile/src/features/settings/VoiceModelSection.tsx index 2403f113b2af..0bee9748b19c 100644 --- a/apps/mobile/src/features/settings/VoiceModelSection.tsx +++ b/apps/mobile/src/features/settings/VoiceModelSection.tsx @@ -29,7 +29,6 @@ import { voiceSpeechModelsAtom, voiceSpeechStatusAtom, } from "../voice-input/voiceDestination"; -import { SettingsSection } from "./components/SettingsSection"; const isDownloading = (model: EnvironmentSpeechModel) => model.state === "downloading" || model.state === "verifying"; @@ -272,51 +271,59 @@ export function VoiceModelRow(props: { ); } -export function VoiceModelSection(props: { +/** The environment's local-model method: chosen by its mark, opens the model list. */ +export function LocalModelChoice(props: { readonly environmentId: EnvironmentId; readonly label: string; + readonly selected: boolean; + readonly onSelect: () => void; }) { const navigation = useNavigation(); const voice = useVoiceModels(props.environmentId, props.label); const { status } = voice; - if (!voice.connection || !status) return null; - const title = `Transcription model on ${props.label}`; - if (!status.supported) { + const open = () => + navigation.navigate("SettingsVoiceModels", { environmentId: props.environmentId }); + if (!voice.connection || !status || !status.supported) return ( - - {null} - + {}} + /> ); - } const active = status.state === "missing-model" ? null : status; const pending = voice.models.find(isDownloading); const progress = pending?.downloaded === undefined ? undefined : pending.downloaded / pending.size; return ( - - - navigation.navigate("SettingsVoiceModels", { environmentId: props.environmentId }) - } - /> - + selected={props.selected} + onPress={() => { + if (!props.selected) props.onSelect(); + // Switching to an installed model needs no further step. + if (props.selected || !active) open(); + }} + /> ); } From d91915db9e36b03450aa7d6dbd35ff27cb027ffe Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 15:15:22 -0800 Subject: [PATCH 045/170] fix(server): a t3 thread send to a finished delegated child notifies its parent (#33446) --- .../src/orchestration-v2/DelegatedCompletionDelivery.test.ts | 3 ++- apps/server/src/orchestration-v2/Orchestrator.ts | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 5cabb1c36372..a5c123157bae 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -2575,7 +2575,8 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( creationSource: outcome === "failed" ? "web" : "mcp", commandId: CommandId.make(`command:followup-send-${outcome}`), threadId: child.childThreadId, - senderThreadId: parentThreadId, + // `t3 thread send` and unscoped MCP sessions carry no sender thread. + ...(outcome === "completed" ? {} : { senderThreadId: parentThreadId }), messageId, text: "Check the same work again.", attachments: [], diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index eab5cda62027..3157f55cacfa 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -8486,12 +8486,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (!startsAttempt) return; const child = yield* projectionStore.getThread(command.threadId); const parentThreadId = child.lineage.parentThreadId; + // A send with no sender thread comes from a client acting for the owner, like a user send. if ( child.lineage.relationshipToParent !== "subagent" || parentThreadId === null || (command.notification === undefined && command.createdBy !== "user" && command.usageLimitContinuationOfRunId === undefined && + command.senderThreadId !== undefined && command.senderThreadId !== parentThreadId) ) return; From 43915a4064b341cd040f24c1b906d87222e403de Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 15:28:07 -0800 Subject: [PATCH 046/170] fix(web): question panel header text sits centered in its row (#34095) Co-authored-by: Claude Opus 5.5 --- .../web/src/components/chat/ComposerPendingUserInputPanel.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx index a19e7f205cef..c25eacd50671 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx @@ -205,7 +205,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( isCollapsed ? "Show the question and its options" : "Hide the question and its options" } data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"} - className="px-4 pt-1.5" + className="px-4 py-1.5" > {/* Rows span the header row's width so the radios align with the question text and the shortcut column sits under the dismiss button. */}
    From ae142932d07c0596cf0497dd28cfee07ae7c0722 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 15:45:07 -0800 Subject: [PATCH 047/170] feat(scripts): scenarios prove a fix in the real app with e2e, on web and iOS (#34007) Co-authored-by: Claude Fable 5.2 --- .../workflows/mobile-showcase-screenshots.yml | 2 +- .gitignore | 1 + AGENTS.md | 2 +- apps/desktop/package.json | 2 +- apps/server/package.json | 2 +- apps/server/src/device/AgentDeviceShim.ts | 5 +- .../server/src/device/deviceToolVersions.json | 4 +- .../src/preview/ServerBrowserPage.test.ts | 1 - apps/web/package.json | 2 +- docs/README.md | 1 + docs/operations/scenarios.md | 161 ++++ evals/mcp-tool-use/agent-device-help.txt | 27 +- knip.jsonc | 6 +- package.json | 2 + pnpm-lock.yaml | 817 +++++++++++++++--- scripts/e2e.config.ts | 181 ++++ scripts/package.json | 8 +- scripts/prove-scenario.test.ts | 110 +++ scripts/prove-scenario.ts | 325 +++++++ .../add-project-tab-reaches-submit.e2e.ts | 22 + .../mobile-opens-a-seeded-thread.e2e.ts | 21 + scripts/scenarios/replay-turn-streams.e2e.ts | 26 + scripts/scenarios/shell.ts | 64 ++ scripts/scenarios/start-app.ts | 235 +++++ scripts/scenarios/t3-mobile.ts | 93 ++ scripts/scenarios/t3.ts | 140 +++ 26 files changed, 2112 insertions(+), 148 deletions(-) create mode 100644 docs/operations/scenarios.md create mode 100644 scripts/e2e.config.ts create mode 100644 scripts/prove-scenario.test.ts create mode 100644 scripts/prove-scenario.ts create mode 100644 scripts/scenarios/add-project-tab-reaches-submit.e2e.ts create mode 100644 scripts/scenarios/mobile-opens-a-seeded-thread.e2e.ts create mode 100644 scripts/scenarios/replay-turn-streams.e2e.ts create mode 100644 scripts/scenarios/shell.ts create mode 100644 scripts/scenarios/start-app.ts create mode 100644 scripts/scenarios/t3-mobile.ts create mode 100644 scripts/scenarios/t3.ts diff --git a/.github/workflows/mobile-showcase-screenshots.yml b/.github/workflows/mobile-showcase-screenshots.yml index c02be425c1ab..53b0a74a1f5a 100644 --- a/.github/workflows/mobile-showcase-screenshots.yml +++ b/.github/workflows/mobile-showcase-screenshots.yml @@ -88,7 +88,7 @@ jobs: axe --version - name: Install foldable simulator controls - run: npm install --global agent-device@0.21.25 + run: npm install --global agent-device@0.21.36 - name: Capture iOS showcase run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --theme "${{ inputs.theme }}" diff --git a/.gitignore b/.gitignore index b6b793e020ef..85b7c5b4bf02 100644 --- a/.gitignore +++ b/.gitignore @@ -38,6 +38,7 @@ apps/mobile/.android-cache/ artifacts/app-store/screenshots/ artifacts/mobile-e2e/ artifacts/mobile-behavior/ +scripts/.e2e/ .github/pr-assets/ native/**/target/ node_modules/ diff --git a/AGENTS.md b/AGENTS.md index 2effa629d25e..87f21a8a0a2f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -108,7 +108,7 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real - [Testing](docs/internals/testing.md) carries these same test rules, plus review guidance, for review bots. Change both together. - **Do not run repo-wide checks.** No `vp check`, no `vp run -r test`, no `vp run -r typecheck` unless I ask. CI owns the full suite. - Backend behavior changes ship with focused tests for that behavior. -- Proof for a bug fix depends on the bug. Logic, data, state, and protocol bugs get a failing test first (the fewest that fail on `main` for that reason, in an existing case of the module's test file where one fits), then the fix. Purely visual bugs (spacing, colour, alignment, a layout shift) get before/after captures as their proof and no test: do not add UI tests for nitpicks, and do not ask for one in review when a capture already shows it. A server-only fix with no visible surface ships the test plus a short runtime transcript. +- Proof for a bug fix depends on the bug. Logic, data, state, and protocol bugs get a failing test first (the fewest that fail on `main` for that reason, in an existing case of the module's test file where one fits), then the fix. Purely visual bugs (spacing, colour, alignment, a layout shift) get before/after captures as their proof and no test: do not add UI tests for nitpicks, and do not ask for one in review when a capture already shows it. A server-only fix with no visible surface ships the test plus a short runtime transcript. For a bug a user can reproduce in the web client, `vp run scenarios:prove` shows it failing on base and passing on the fix in the real app; see [Scenarios](docs/operations/scenarios.md). - The server is event-sourced, and side effects run after the command commits. In tests, drain the effect worker (`OrchestrationEffectWorkerV2.drain`) or await the specific persisted event or `Deferred` that marks the milestone. Never wait on sleeps or polling. A test that needs a timeout to pass is wrong. Concretely: - `it.effect` runs on a `TestClock`; `Effect.sleep` only advances through `TestClock.adjust`. `it.live` is wall-clock and only for subprocess or network fixtures. - No `yieldNow` or `sleep` polling loops. Await the `Deferred`, take from the `Queue`, or drain the worker. diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 4a4884ba73e2..ab4e1ed382da 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -27,7 +27,7 @@ "electron-updater": "^6.8.9", "electron-webauthn": "catalog:", "ffi-rs": "1.3.2", - "playwright-core": "1.60.0", + "playwright-core": "1.64.1", "react-grab": "^0.1.32", "tldts": "catalog:" }, diff --git a/apps/server/package.json b/apps/server/package.json index 284084065e61..d7e4d21f08b8 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -67,7 +67,7 @@ "effect": "catalog:", "ffi-rs": "1.3.2", "node-pty": "^1.2.0-beta.15", - "playwright-core": "1.60.0", + "playwright-core": "1.64.1", "proper-lockfile": "4.1.2", "saxes": "6.0.0", "stream-chain": "^4.2.5", diff --git a/apps/server/src/device/AgentDeviceShim.ts b/apps/server/src/device/AgentDeviceShim.ts index b50f4dfbf2a4..e5b42557a1e1 100644 --- a/apps/server/src/device/AgentDeviceShim.ts +++ b/apps/server/src/device/AgentDeviceShim.ts @@ -12,7 +12,7 @@ const STALE_RUNTIME = const quoteShell = (value: string) => "'" + value.replaceAll("'", "'\"'\"'") + "'"; -/** agent-device 0.21.31's flags that take a value, so the launcher can find the command past them. */ +/** agent-device 0.21.36's flags that take a value, so the launcher can find the command past them. */ const VALUE_FLAGS: ReadonlyArray = [ "--activity", "--all", @@ -53,6 +53,7 @@ const VALUE_FLAGS: ReadonlyArray = [ "--header", "--hold-ms", "--host", + "--image-tag", "--in-app", "--include", "--interval-ms", @@ -79,6 +80,7 @@ const VALUE_FLAGS: ReadonlyArray = [ "--metro-port", "--network-profile", "--on-error", + "--os", "--os-version", "--out", "--pattern", @@ -101,6 +103,7 @@ const VALUE_FLAGS: ReadonlyArray = [ "--provider-geo-location", "--provider-language", "--provider-locale", + "--provider-network-hosts", "--provider-network-profile", "--provider-os-version", "--provider-project", diff --git a/apps/server/src/device/deviceToolVersions.json b/apps/server/src/device/deviceToolVersions.json index e441cc55a9d3..ce61669b2657 100644 --- a/apps/server/src/device/deviceToolVersions.json +++ b/apps/server/src/device/deviceToolVersions.json @@ -1,4 +1,4 @@ { - "agent-device": "0.21.31", - "expo-device-hub": "0.19.1" + "agent-device": "0.21.36", + "expo-device-hub": "0.22.1" } diff --git a/apps/server/src/preview/ServerBrowserPage.test.ts b/apps/server/src/preview/ServerBrowserPage.test.ts index 78f03f1f91b7..855d30f80ee0 100644 --- a/apps/server/src/preview/ServerBrowserPage.test.ts +++ b/apps/server/src/preview/ServerBrowserPage.test.ts @@ -180,7 +180,6 @@ describe("server browser element refs", () => { ); expect(result.visibleText).not.toContain("editable-pass"); expect(result.visibleText).toContain("Order ••••••••-2"); - expect(tree).toMatch(/row "password: •+"/); expect(tree).toMatch(/textbox "Username" [^\n]*: maria$/m); const line = tree.split("\n").find((line) => line.includes('textbox "Password"')); expect(line).toMatch(/: •+$/); diff --git a/apps/web/package.json b/apps/web/package.json index e1dc0fbf90c1..6cb69713aec2 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -111,7 +111,7 @@ "compression": "^1.8.2", "micromark-util-types": "catalog:", "oxc-transform-react": "~0.152.0", - "playwright": "1.60.0", + "playwright": "1.64.1", "tailwindcss": "^4.0.0", "vite": "catalog:", "vite-plus": "catalog:" diff --git a/docs/README.md b/docs/README.md index 3c98c7223882..264d509d9764 100644 --- a/docs/README.md +++ b/docs/README.md @@ -65,6 +65,7 @@ source alone does not explain. Most code changes do not need an internal documen ### Runbooks - [Development and local builds](./operations/development.md) +- [Scenarios: real-app proof for a fix](./operations/scenarios.md) - [T3 Connect setup](./operations/connect-setup.md) - [Release](./operations/release.md) - [Observability](./operations/observability.md) diff --git a/docs/operations/scenarios.md b/docs/operations/scenarios.md new file mode 100644 index 000000000000..c7a753f8ae2b --- /dev/null +++ b/docs/operations/scenarios.md @@ -0,0 +1,161 @@ +# Scenarios + +A scenario is an [e2e](https://e2e.com/docs) test that shows one behavior in the real app: a real +server on its own T3 home, real HTTP and WebSocket, and a real browser on the web client or a +pooled iPhone simulator running the mobile app. The +dev replay agent stands in for the model, so a run is free and repeatable. Use one as the proof +for a bug fix: it fails on the base commit and passes on the fix. + +Scenarios live in [`scripts/scenarios`](../../scripts/scenarios) as `*.e2e.ts`. e2e is the +runner; its docs ship in `scripts/node_modules/e2e/docs` and `e2e guide` prints them. + +## Write one + +```ts +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Tab moves from the add-project Git URL field to its submit button", + WEB, + async ({ t3, app, screen, browser }) => { + await t3.project("demo"); + await t3.open(); + + await screen.getByRole("button", "Add project").tap(); + await screen.getByText("Git URL").tap(); + await screen.getByRole("combobox").fill("https://github.com/pingdotgg/t3code.git"); + const submit = screen.getByRole("button", "Continue (Enter)"); + await expect(submit).toBeEnabled(); + + await browser.keyboard.press("Tab"); + await app.screenshot("after-tab"); + await expect(submit).toBeFocused(); + }, +); +``` + +`screen`, `browser`, `app`, and `expect` are e2e's own. [`t3.ts`](../../scripts/scenarios/t3.ts) +adds one fixture for what e2e cannot know about T3 Code: + +- `t3.project(title, files)` creates a git repository and adds it as a project. +- `t3.thread({ project, title, messages })` starts a thread and plays one replayed turn per + message before returning, so the thread has real history. `model` picks the recording. +- `t3.open(path)` opens the app, already signed in. + +State is created through the app's own CLI, so it is real events and works on a base commit +whose schema differs. New threads default to the replay agent's `showcase` recording: type a +message and send it. To play something else, add a recording to the +[replay agent](development.md#replay-provider). + +Write one test per file: a proof runs the file and needs exactly one test in it. + +Take an `app.screenshot("label")` where the bug shows. The proof pairs base and head captures by +label. e2e adds a capture at the point of failure itself. + +Write only `expect` assertions for the thing the bug breaks. A proof counts a failed assertion as +the bug. A control that cannot be found, or an app that does not start, counts as a scenario that +could not run. + +Keep `agent.act` and `agent.assert` out of scenarios: they call a model, and no model is +configured. + +## Run + +```sh +vp run scenarios # all of them +cd scripts && pnpm exec e2e run scenarios/replay-turn-streams.e2e.ts --headed +``` + +e2e starts the dev stack through [`start-app.ts`](../../scripts/scenarios/start-app.ts) on a free +port, runs the tests, and stops it. Results land in `scripts/.e2e`: `report.json`, `summary.md`, +and per test a `trace.md`, its screenshots, and a video. The first run downloads e2e's browser. +`e2e run --help` lists the rest: `--grep`, `--watch`, `--last-failed`, `--changed-since`. + +Run one at a time per checkout: a run recreates the checkout's scenario T3 home and its `.e2e` +output. Use a second worktree for a second run. + +## Prove a fix + +```sh +vp run scenarios:prove scripts/scenarios/add-project-tab-reaches-submit.e2e.ts \ + --base e509db3a2f^ --head e509db3a2f --upload-command "ghdrop upload" +``` + +[`prove-scenario.ts`](../../scripts/prove-scenario.ts) runs `e2e run` for that scenario on both +commits and compares the two reports. It prints, and writes to `scripts/.e2e/prove/proof.json`, +`failsOnBase`, `passesOnHead`, `baseSha`, `headSha`, `verdict`, each side's `steps`, `captures`, +`videos`, and `markdown`: a table with base and head captures side by side, each labelled with +its commit, ready for a pull request description. `--upload-command` names a command that takes +the capture paths and prints one URL per line. `--head` defaults to `HEAD`. + +It exits 0 only when the scenario fails on base and passes on head, 1 when it ran and did not +prove the fix, and 2 when it could not run. A scenario that passes on base does not reproduce the +bug, and the verdict says so. + +The scenario and e2e always come from your checkout. Only the app comes from the commit under +test: a temporary worktree beside your checkout, installed with `vp i` and removed afterwards. A +commit that is your clean `HEAD` runs in place. So a new scenario can prove a fix against a base +that predates it. + +## iOS + +An iOS scenario imports from [`t3-mobile.ts`](../../scripts/scenarios/t3-mobile.ts) and passes +`IOS` where a web one passes `WEB`: + +```ts +import { expect } from "e2e"; + +import { IOS, test } from "./t3-mobile.ts"; + +test( + "The iOS app lists a seeded thread and opens its history", + IOS, + async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + await t3.thread({ project, title: "Earlier work", messages: ["first", "second"] }); + await t3.open(); + + const thread = screen.getByText("Earlier work", { exact: false }).first(); + await expect(thread).toBeVisible({ timeout: 120_000 }); + await thread.tap(); + await expect(screen.getByText("second fixture turn complete", { exact: false })).toBeVisible(); + }, +); +``` + +`t3.project` and `t3.thread` are the same. `t3.open()` installs the dev client for the checkout's +native fingerprint, loads it from Metro, and pairs it with the scenario's server. `device` is +e2e's [device fixture](https://e2e.com/docs/mobile#the-device-fixture) for system actions. + +The run leases an iPhone 18 Pro from the Simlock pool, so it needs `SIMLOCK_AGENT_DEVICE_URL` +and `AGENT_DEVICE_DAEMON_AUTH_TOKEN`, as `mobile:e2e` does, and a gateway on Simlock 0.7.0 or +later. A web-only run leases nothing. The device reaches this machine over the tailnet on ports +13990 (server) and 8190 (Metro); set `T3_SCENARIO_SERVER_PORT` and `T3_SCENARIO_METRO_PORT` when +another run on the machine holds them. An iOS run takes two to three minutes, most of it the +device and the first bundle. `e2e run --target web` or `--target ios` runs one side. + +`scenarios:prove` works the same for an iOS scenario. Each commit gets the dev client built for +its own native code. + +## Other tiers + +- **Android.** Add a target with `mobile({ platform: "android", device: simlock("Pixel 9") })` + and open the dev client with the Android form of the Expo link. Not built. +- **Live provider.** Point the default model in `start-app.ts` at a real provider's cheapest + model. Assertions on exact reply text would not hold. + +## In CI + +No job runs scenarios, and none should run all of them on every pull request. e2e can select the +ones a branch touches with `e2e run --changed-since origin/main` once +[test filters](https://e2e.com/docs/filters) are configured, and `@e2e-dev/github` posts the +result as a pull request comment. + +## What a scenario cannot cover + +- Desktop shell behavior (menus, windows, IPC), and Android. +- Provider-specific behavior. The replay agent speaks generic ACP. +- State no command can create, such as a run stopped by a usage limit. +- Timing. Replay streaming is simulated, so a scenario cannot show a performance regression. diff --git a/evals/mcp-tool-use/agent-device-help.txt b/evals/mcp-tool-use/agent-device-help.txt index a45698bfb2f0..058f29b5bf6a 100644 --- a/evals/mcp-tool-use/agent-device-help.txt +++ b/evals/mcp-tool-use/agent-device-help.txt @@ -1,4 +1,4 @@ -agent-device 0.21.31 prints this help; apps/server/src/device/deviceToolVersions.json pins that version. Regenerate from +agent-device 0.21.36 prints this help; apps/server/src/device/deviceToolVersions.json pins that version. Regenerate from the repo root with: node scripts/node_modules/agent-device/bin/agent-device.mjs help [commands|record|screenshot|open|settings|fill] $ agent-device help @@ -54,9 +54,8 @@ Guides (agent-device help ): physical-device / ios-system-ui / maestro foldable iPhone Duo panels, the fold command, and why refs die on a pose change - $ agent-device help commands -agent-device 0.21.31 — commands +agent-device 0.21.36 — commands Full command catalog. Use agent-device help for exact flags and behavior. @@ -88,7 +87,7 @@ Commands: doctor Diagnose device, app, dev-server, and RN/Expo readiness events Read session event timeline fill [text] Replace text in a UI input - find [value] Find an element and act + find [action] [value] Find an element and act focus Focus input at screen coordinates fold [pose] Fold or unfold a foldable iPhone simulator or Android emulator gesture ... Run pan, fling, swipe, pinch, rotate, transform, tap, or drag gestures @@ -181,7 +180,6 @@ Related: agent-device help command-specific flags agent-device help manual-qa routine QA loop agent-device help workflow full automation reference - $ agent-device help record Usage: agent-device record start [path] [--scope ] [--fps ] [--quality ] [--hide-touches] | record stop | record contact-sheet [--out ] @@ -194,12 +192,11 @@ Command flags: --hide-touches Record: skip touch-overlay post-processing for faster raw benchmark videos --scope Record: app requires an active app session; device/system records the whole screen --out Output path - $ agent-device help screenshot Usage: agent-device screenshot [path] [--out ] [--overlay-refs] [--crop-on ] [--pixel-density ] [--fullscreen, --full, -f] [--scale <0.01-1>] [--no-stabilize] [--normalize-status-bar] -Capture a screenshot of the active app or web session. Choose the capture scope, density, size, or annotations through the corresponding input fields when needed. Web defaults to the viewport; use --fullscreen, --full, or -f for the entire page. iOS simulators default to 1x logical-point output; use --pixel-density to request a different screenshot density. macOS app sessions default to the app window; use --fullscreen for full desktop, --scale to downscale, --crop-on to crop the capture to the frame the selector resolves on the same screen (currently iOS simulators, Android emulators, and CoreDevice physical iPhones), --overlay-refs to annotate current refs, --normalize-status-bar for deterministic iOS simulator or Android chrome. Physical iPhone crop verification covers portrait CoreDevice/devicectl captures only. XCTest, runner fallback, and physical iPad crops are refused; landscape iPhone crop is unverified. Android captures immediately by default; --normalize-status-bar also waits for transient UI to fade, and --no-stabilize keeps capture immediate. With the native macOS backend, the front window is the app's frontmost visible, nonempty normal-level (layer-0) window on the current Space: floating palettes and app-modal alerts at window level 8 are skipped, and a sheet is captured as its own window. On macOS, any --surface other than app (desktop, menubar, frontmost-app) always captures the main display and refuses an explicit --fullscreen. On single-display iOS simulators and Android devices, the result reports displayRotation, the rotation the display rendered the capture in, when the device returns a reading in time; otherwise the field is absent. +Capture a screenshot of the active app or web session. Choose the capture scope, density, size, or annotations through the corresponding input fields when needed. Web defaults to the viewport; use --fullscreen, --full, or -f for the entire page. iOS simulators default to 1x logical-point output; use --pixel-density to request a different screenshot density. macOS app sessions default to the app window; use --fullscreen for full desktop, --scale to downscale, --crop-on to crop the capture to the frame the selector resolves on the same screen (currently iOS simulators, Android emulators, and CoreDevice physical iPhones), --overlay-refs to annotate current refs, --normalize-status-bar for deterministic iOS simulator or Android chrome. Physical iPhone crop verification covers portrait CoreDevice/devicectl captures only. XCTest, runner fallback, and physical iPad crops are refused; landscape iPhone crop is unverified. Android captures immediately by default; --normalize-status-bar also waits for transient UI to fade, and --no-stabilize keeps capture immediate. With the native macOS backend, the front window is the app's frontmost visible, nonempty normal-level (layer-0) window on the current Space: floating palettes and app-modal alerts at window level 8 are skipped, and a sheet is captured as its own window. On macOS, any --surface other than app (desktop, menubar, frontmost-app) always captures the main display and refuses an explicit --fullscreen. On single-display iOS simulators and Android devices, the result reports displayRotation, the rotation the display rendered the capture in, when the device returns a reading in time; otherwise the field is absent. On iOS simulators a screenshot waits for that simulator's status bar to be free, and a request its caller cancelled while it waits reports the cancellation instead of capturing. Command flags: --out Output path @@ -210,15 +207,17 @@ Command flags: --scale <0.01-1> Screenshot: resize both dimensions by this factor (or use AGENT_DEVICE_SCREENSHOT_SCALE) --no-stabilize Screenshot: capture immediately without Android status-bar stabilization (the default) --normalize-status-bar Screenshot: temporarily normalize iOS simulator or ADB-backed Android status-bar chrome for deterministic screenshot diffs; ADB-backed Android waits for transient UI to fade - $ agent-device help open Usage: - agent-device open [appOrUrl] [url] [--activity ] [--launch-console ] [--launch-args ] [--test-ime] [--no-test-ime] [--save-script [path]] [--force, --overwrite] [--no-record] [--relaunch] [--foreground] [--timeout ] [--wait ] [--surface app|frontmost-app|desktop|menubar] [--metro-host ] [--metro-port ] [--bundle-url ] [--launch-url ] + agent-device open [appOrUrl] [url] [--activity ] [--launch-console ] [--launch-args ] [--test-ime] [--no-test-ime] [--save-script [path]] [--force, --overwrite] [--no-record] [--relaunch] [--foreground] [--timeout ] [--wait ] [--surface app|frontmost-app|desktop|menubar] [--metro-host ] [--metro-port ] [--bundle-url ] [--launch-url ] [--os ] [--image-tag ] [--physical] -Boot the selected device when needed, then open an app, deep link, or URL in a session. Use the app or URL inputs to choose what becomes the foreground automation target. Use --platform to bind URL/deep-link opens to the target platform. For iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app's Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app's launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; in both cases inspect the warning and answer with alert get then alert accept; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app's target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. A recognized prompt still visible after a failed accept also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. Only the English prompt title with Cancel and Open buttons is recognized, so on a Simulator set to another language the prompt stays on screen. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session. +Boot the selected device when needed, then open an app, deep link, or URL in a session. Use the app or URL inputs to choose what becomes the foreground automation target. Use --platform to bind URL/deep-link opens to the target platform. For local iOS simulator initial stdout/stderr, put --launch-console on this open command, for example agent-device open "Agent Device Tester" --platform ios --launch-console artifacts/launch-console.log. Expo Go/dev-client shells accept host + URL, for example agent-device open "Expo Go" exp://127.0.0.1:8081 --platform ios. macOS also supports --surface app|frontmost-app|desktop|menubar. --metro-host/--metro-port/--bundle-url choose the app's Metro server and save that address for later metro reload calls in the same session. A fresh open without Metro hints clears an older same-name binding; close also clears it. --launch-url supplies the app's launch URL; it does not select the reload server. On an iOS simulator without --launch-url, open connects a detected Expo development client through its expo-development-client URL. The app must declare a single exp+ scheme that no other installed app owns. If detection is inconclusive, the app opens normally. Bare React Native apps receive their server settings before launch. On an iOS simulator, when --launch-url raises an "Open in ?" prompt that keeps open from seeing the app, open accepts it if the URL scheme belongs to the session app (data.launchConfirmation: "accepted"); if the scheme belongs to another installed app, the prompt stays on screen and open fails with details.reason launch_confirmation_foreign_app; if the scheme owner cannot be resolved because no single installed app owns it or the lookup failed, the prompt stays on screen and open returns with data.launchConfirmation: "unanswered", launchConfirmationReason url-owner-unresolved, and a warning; a prompt that is seen but not recognized is reported the same way with launchConfirmationReason alert-unrecognized and its own warning; for url-owner-unresolved, answer the prompt with alert accept; for alert-unrecognized, read the alert with alert get first, because it can be the app's own alert (such as a permission prompt) rather than the launch confirmation, and answer with alert accept only when it is the launch confirmation; when agent-device cannot read whether a prompt is up at all (the alert read, the accept, or the runner itself failed, including after a re-hand of the URL), open stays green, reports no launchConfirmation plus data.launchConfirmationProbeFailure naming the failed step (alert-read, alert-accept, or runner), and appends a warning that says to check with alert get. The prompt is read whenever open cannot see the app afterwards, including on a slow host where the app's target discovery fails on its own deadline. When an accept leaves the app provably not running, open hands the same URL over once more and reads again; still not running, it fails with details.reason launch_confirmation_unanswered. When the runner reports its main-thread timeout for the accept and the prompt is still up, open presses Open again, but only when the time the open request has left covers a whole press and the read that checks it. A recognized prompt still visible after a failed accept, or once that time is gone, also fails with this reason, even if the app is running behind it; answer it with alert accept or alert dismiss. A simulator openurl that CoreSimulator never answers fails within 20s with details.reason ios-simulator-openurl-timeout. The prompt is recognized by the OS's own wording of its title and buttons in the Simulator's preferred languages; when the runner cannot read that wording, the prompt stays on screen as alert-unrecognized. A prompt that appears after open has already seen the app is not answered; use alert accept. A device another session is holding refuses at once; add --wait to block up to that budget for it and only then fail with DEVICE_IN_USE naming the owning session. Command flags: --force, --overwrite Force replacement of existing state (connect: replace an active connection; --save-script: overwrite an existing target instead of refusing) + --os Proxy lease: OS version or range the backend picks the device by (Android: API level); refused without such a backend + --image-tag Proxy lease: Android system image tag the backend picks the device by; refused without such a backend + --physical Proxy lease: ask the backend for a physical device instead of a simulator or emulator; refused without such a backend --surface app|frontmost-app|desktop|menubar macOS session surface for open (defaults to app) --metro-host Session-scoped Metro/debug host hint --metro-port Session-scoped Metro/debug port hint; on an emulator/simulator the host defaults to the loopback alias, physical devices still need --metro-host @@ -227,7 +226,7 @@ Command flags: --test-ime open/test/replay: activate the headless Android test IME for deterministic Unicode text entry (default on for emulators; opt-in on real devices; on test/replay it applies to the sessions the flow opens) --no-test-ime open/test/replay: keep the real Android keyboard even on emulators (opt out of the headless test IME; on test/replay it applies to the sessions the flow opens) --activity Android launch activity (package/Class, .Class, or Class) or HarmonyOS ability name; not for URL opens - --launch-console open: capture the initial iOS simulator launch console window to a file + --launch-console open: capture the initial local iOS simulator launch console window to a file --launch-args open: repeatable launch argument forwarded verbatim to the platform launch command (iOS app process args; Android adb shell am start args). Linux and macOS reject the flag. --save-script [path] Arm evidence capture on open, publish the armed recording on close; close --save-script alone (without an armed open) is rejected — start with open --save-script, or use session save-script mid-session. Optional custom output path. --relaunch open: terminate app process before launching it @@ -235,13 +234,14 @@ Command flags: --no-record Do not record this action --timeout Boot/Open/Prepare: startup budget covering the device boot (and runner preparation for prepare). Replay/Snapshot/Test: maximum wall-clock time for the command or attempt. With --settle: the settle-wait deadline (default 10s) --wait Open: wait up to n ms for a device another session is holding before failing with DEVICE_IN_USE - $ agent-device help settings Usage: agent-device settings | settings location set | settings appearance | settings text-size [extra-small|small|medium|large|extra-large|extra-extra-large|extra-extra-extra-large|accessibility-medium|accessibility-large|accessibility-extra-large|accessibility-extra-extra-large|accessibility-extra-extra-extra-large] | settings | settings fingerprint | settings clear-app-state [app-id] | settings reset-keychain clear | settings permission [full|limited] | settings permission [--app ] Read or change supported operating-system settings, animation scales, appearance, or app permissions on the selected target. Platform support varies by setting and action. A bare readable setting reads the value the target holds. A target that does not serve a setting refuses it with UNSUPPORTED_OPERATION before anything changes. +On an iOS simulator, settings wifi and settings airplane wait for screenshots and other status bar writes. The request timeout includes this wait (90 seconds for a standalone CLI request). Once the write starts, its status bar command has a separate 10-second timeout. A request or write that times out may already have changed the bar; check the bar before relying on it. Cancelling while still queued guarantees nothing was written. + Settings: wifi: Android switches Wi-Fi with svc wifi; an Apple simulator overrides only its status bar. bluetooth: Android over adb turns its Bluetooth adapter on or off with svc bluetooth, from Android 8.1. It reports the bluetooth state the device holds afterwards, or fails with bluetooth-not-applied or bluetooth-unreadable. A device without an adapter refuses with android_bluetooth_adapter_missing, and an adapter on a build older than 8.1 with android_bluetooth_command_unavailable, before anything changes. --app is refused. @@ -260,12 +260,11 @@ Settings: Command flags: --app Target an app without opening it: doctor verifies an installed app by id or name; settings applies an app-scoped change (permission, iOS location) to a bundle id or package - $ agent-device help fill Usage: agent-device fill | fill <@ref|selector> | fill --text-stdin -Replace text in a UI input selected by snapshot ref, selector, or coordinates. Pass an empty text to clear the field. Inspect unconfirmed evidence and assert the expected value or resulting screen before continuing. Prefer refs or selectors after snapshot; use recordAs to keep sensitive text out of a recorded replay while sending it to the live app. Every positional after an @ref is the replacement text, so fill @e57 good morning enters "good morning"; quote the text when the shell must preserve exact whitespace. Clear a field with an empty text argument: fill @e57 "" (the argument must be present — fill @e57 alone is a missing argument, not a clear). When visible label text also matches a non-input element, constrain the target with editable=true, for example fill 'label="Email" editable=true' "qa@example.com". To keep a secret out of argv, omit the text and pipe it in: printf %s "$PASSWORD" | fill @e57 --text-stdin (max 64 KiB, one trailing newline removed). +Replace text in a UI input selected by snapshot ref, selector, or coordinates. Pass an empty text to clear the field. Inspect unconfirmed evidence and assert the expected value or resulting screen before continuing. Prefer refs or selectors after snapshot; use recordAs to keep sensitive text out of a recorded replay while sending it to the live app. Every positional after an @ref is the replacement text, so fill @e57 good morning enters "good morning"; quote the text when the shell must preserve exact whitespace. Clear a field with an empty text argument: fill @e57 "" (the argument must be present — fill @e57 alone is a missing argument, not a clear). When visible label text also matches a non-input element, constrain the target with editable=true, for example fill 'label="Email" editable=true' "qa@example.com". To keep a secret out of argv, omit the text and pipe it in: printf %s "$PASSWORD" | fill @e57 --text-stdin (max 64 KiB, one trailing newline removed). On web, a coordinate fill selects the clicked field in the page and refuses with COMMAND_FAILED and details.reason text_entry_focus_not_observed, before it sends any text or key, when the click did not reach an editable text field it can reach: a read-only, disabled, date, checkbox, or select control, a field in a cross-origin frame, a sandboxed frame without allow-same-origin, or a closed shadow root, or a click that missed. The click has already landed, so run snapshot -i again and fill the field it reports by ref (fill @e2 text); a selector fill reaches the same coordinate path and hits the same limits. Command flags: --delay-ms Delay between typed characters diff --git a/knip.jsonc b/knip.jsonc index ed4bf1912964..068c8cf84ab6 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -31,13 +31,17 @@ "linux-after-pack.ts", "mobile-behavior/run.ts", "mobile-native-client.ts", + // e2e loads its config and the scenarios by path, and starts the app script. + "e2e.config.ts", + "prove-scenario.ts", + "scenarios/*.ts", "setup-worktree.ts", "sign-macos.ts", "prepare-server-compile-cache.cjs", "smoke-desktop-app.ts", "verify-windows-desktop-artifact.ts", ], - "ignoreDependencies": ["agent-device", "esbuild"], + "ignoreDependencies": ["esbuild"], // The `t3` npm package's files: copied into the package, never imported. // knip-schemas.test.ts writes a throwaway project to .knip-test-*, which a // knip run beside it in check:changed must not report. diff --git a/package.json b/package.json index c43ef19c7b85..9017f1117394 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,8 @@ "mobile:install": "node scripts/mobile-native-client.ts ensure", "mobile:behavior": "node scripts/mobile-behavior.ts", "mobile:e2e": "node scripts/mobile-e2e.ts", + "scenarios": "vp run --filter @t3tools/scripts scenarios", + "scenarios:prove": "node scripts/prove-scenario.ts", "test": "vp run -r test", "test:cached": "node scripts/test-cached.ts", "test:perf:v2-wire": "vp test run apps/server/src/orchestration-v2/WireProjection.test.ts apps/server/src/orchestration-v2/threadHistoryPaging.test.ts apps/server/src/orchestration-v2/ThreadStream.test.ts apps/server/src/orchestration-v2/ThreadTransportPerformance.test.ts apps/server/src/orchestration-v2/ShellStream.test.ts apps/server/src/orchestration-v2/CommandPolicy.test.ts apps/server/src/orchestration-v2/runtimeLayer.test.ts apps/server/src/ws.test.ts packages/contracts/src/orchestrationV2.test.ts packages/client-runtime/src/operations/commands.test.ts packages/client-runtime/src/operations/commands.performance.test.ts packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts packages/client-runtime/src/state/threadHistoryController.test.ts packages/client-runtime/src/state/threadHistoryMerge.test.ts packages/client-runtime/src/state/threads-sync.test.ts packages/client-runtime/src/state/shellReducer.test.ts", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ff6392397431..e7265664f0a4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -409,7 +409,7 @@ importers: version: 6.34.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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) apps/desktop: dependencies: @@ -465,8 +465,8 @@ importers: specifier: 1.3.2 version: 1.3.2 playwright-core: - specifier: 1.60.0 - version: 1.60.0 + specifier: 1.64.1 + version: 1.64.1 react-grab: specifier: ^0.1.32 version: 0.1.44(react@19.3.0) @@ -476,7 +476,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -494,7 +494,7 @@ importers: version: 4.3.3 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) apps/marketing: dependencies: @@ -787,7 +787,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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) @@ -912,8 +912,8 @@ importers: specifier: 1.2.0-beta.15 version: 1.2.0-beta.15(patch_hash=f1e680afec85f650699ea756f91f469844ec4c976f4f168492a45c6b3f67d651) playwright-core: - specifier: 1.60.0 - version: 1.60.0 + specifier: 1.64.1 + version: 1.64.1 proper-lockfile: specifier: 4.1.2 version: 4.1.2 @@ -947,7 +947,7 @@ importers: version: 4.1.2(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.2) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -1004,7 +1004,7 @@ importers: version: 16.14.1 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) apps/web: dependencies: @@ -1248,7 +1248,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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)) @@ -1290,7 +1290,7 @@ importers: version: 6.1.2(@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))(babel-plugin-react-compiler@1.0.0)(oxc-transform-react@0.152.0) '@vitest/browser-playwright': specifier: 5.0.5 - version: 5.0.5(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(playwright@1.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(vitest@5.0.5)(yaml@2.9.0) + version: 5.0.5(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(vitest@5.0.5)(yaml@2.9.0) compression: specifier: ^1.8.2 version: 1.8.2(supports-color@8.1.1) @@ -1301,8 +1301,8 @@ importers: specifier: ~0.152.0 version: 0.152.0 playwright: - specifier: 1.60.0 - version: 1.60.0 + specifier: 1.64.1 + version: 1.64.1 tailwindcss: specifier: 4.3.3 version: 4.3.3 @@ -1311,7 +1311,7 @@ importers: 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)' 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) evals: dependencies: @@ -1333,13 +1333,13 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) infra/relay: dependencies: @@ -1394,7 +1394,7 @@ importers: devDependencies: '@alchemy.run/test': specifier: 'catalog:' - version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(be874ca08ab53e444d5d72e167a81f3f) + version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(93775fed45909d71c0b8bba962f026cf) '@cloudflare/workers-types': specifier: ^4.20260601.1 version: 4.20260604.1 @@ -1403,7 +1403,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -1418,7 +1418,7 @@ importers: 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)' 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) infra/task-cache: dependencies: @@ -1446,13 +1446,13 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) oxlint-plugin-t3code: dependencies: @@ -1468,10 +1468,10 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/client-runtime: dependencies: @@ -1535,13 +1535,13 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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/three': specifier: 0.180.0 version: 0.180.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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/contracts: dependencies: @@ -1551,10 +1551,10 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/effect-acp: dependencies: @@ -1570,13 +1570,13 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/effect-codex-app-server: dependencies: @@ -1592,13 +1592,13 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/provider-acp: dependencies: @@ -1623,7 +1623,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -1632,7 +1632,7 @@ importers: version: link:../effect-acp 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/provider-acp-registry: dependencies: @@ -1660,7 +1660,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -1672,7 +1672,7 @@ importers: version: link:../effect-acp 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/provider-core: dependencies: @@ -1691,13 +1691,13 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/provider-cursor: dependencies: @@ -1725,7 +1725,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -1734,7 +1734,7 @@ importers: version: 24.12.4 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/provider-fx: dependencies: @@ -1759,7 +1759,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -1768,7 +1768,7 @@ importers: version: link:../effect-acp 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/provider-grok: dependencies: @@ -1793,7 +1793,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -1805,7 +1805,7 @@ importers: version: link:../effect-acp 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/provider-kiro: dependencies: @@ -1827,7 +1827,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -1836,7 +1836,7 @@ importers: version: link:../effect-acp 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/provider-muse: dependencies: @@ -1861,7 +1861,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -1870,7 +1870,7 @@ importers: version: 24.12.4 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/provider-opencode: dependencies: @@ -1904,7 +1904,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -1913,7 +1913,7 @@ importers: version: 24.12.4 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/provider-pi: dependencies: @@ -1935,7 +1935,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -1944,7 +1944,7 @@ importers: version: 24.12.4 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/provider-testing: dependencies: @@ -1982,13 +1982,13 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/secret-provider-definitions: dependencies: @@ -2022,13 +2022,13 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/shared: dependencies: @@ -2095,7 +2095,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -2107,7 +2107,7 @@ importers: version: 2.0.2 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/source-control-azure-devops: dependencies: @@ -2132,7 +2132,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -2141,7 +2141,7 @@ importers: version: 24.12.4 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/source-control-bitbucket: dependencies: @@ -2166,7 +2166,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -2175,7 +2175,7 @@ importers: version: 24.12.4 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/source-control-core: dependencies: @@ -2191,13 +2191,13 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/source-control-cursor-origin: dependencies: @@ -2222,13 +2222,13 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/source-control-definitions: dependencies: @@ -2280,7 +2280,7 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -2289,7 +2289,7 @@ importers: version: 24.12.4 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/source-control-gitcafe: dependencies: @@ -2311,7 +2311,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -2320,7 +2320,7 @@ importers: version: 24.12.4 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/source-control-github: dependencies: @@ -2348,7 +2348,7 @@ importers: version: 4.1.2(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.2) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -2357,7 +2357,7 @@ importers: version: 24.12.4 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/source-control-gitlab: dependencies: @@ -2376,7 +2376,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -2385,7 +2385,7 @@ importers: version: 24.12.4 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/source-control-testing: dependencies: @@ -2426,13 +2426,13 @@ importers: version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages/tailscale: dependencies: @@ -2445,16 +2445,22 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) scripts: dependencies: + '@e2e-dev/mobile': + specifier: 0.12.6 + version: 0.12.6(e2e@0.23.0) + '@e2e-dev/web': + specifier: 0.15.5 + version: 0.15.5(e2e@0.23.0) '@effect/platform-node': specifier: 4.1.2 version: 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(redis@6.2.1)(utf-8-validate@6.0.6) @@ -2474,14 +2480,17 @@ importers: specifier: workspace:* version: link:../packages/tailscale agent-device: - specifier: 0.21.32 - version: 0.21.32 + specifier: 0.21.36 + version: 0.21.36 + e2e: + specifier: 0.23.0 + version: 0.23.0 effect: specifier: 4.1.2 version: 4.1.2 playwright-core: - specifier: 1.60.0 - version: 1.60.0 + specifier: 1.64.1 + version: 1.64.1 plist: specifier: 'catalog:' version: 3.1.1 @@ -2494,7 +2503,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.2 - version: 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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 @@ -2512,7 +2521,7 @@ importers: version: typescript@6.0.3 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.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) packages: @@ -2535,6 +2544,10 @@ packages: resolution: {integrity: sha512-IpefF5ssZVOZCD4Wu7zxt6PwZoGT2HLVjxpJ10Bjx6EAmRfLYJPjyrfxb0RYDlwvXnDb9nkQ7Do/oJVDuRFzew==} engines: {node: '>=18'} + '@ai-sdk/provider@4.0.36': + resolution: {integrity: sha512-GqvWZSZdBelCGughlBdOoupT258rgM3YMbaLAS9WSZJ0vlt8c9vm3My+ZT31mYhiReMCMCF2qF2axnGbILpk1A==} + engines: {node: '>=22'} + '@alchemy.run/acme@2.0.0-beta.85': resolution: {integrity: sha512-hOV18VHG6ivrbPnk35hoqlCQPc6bR8b9soGmHlSkbnPIgVZUg7jpliF9AztSSJbJK4GHcBFc9hWetwCRHzGYAg==} peerDependencies: @@ -3712,6 +3725,23 @@ packages: peerDependencies: react: '>=16.8.0' + '@e2e-dev/mobile@0.12.6': + resolution: {integrity: sha512-V56hOt5cJsoC9M8kMIjsCKOY2pEPHb4awYMLP699yMO4aNUUnpALYK/R2ik6C64CLEq4N1aibLmD7ErPZVc97w==} + engines: {node: ^22.22.3 || >=24.8.0} + peerDependencies: + ai: ^7.0.0 + e2e: '>=0.22.1 <1' + peerDependenciesMeta: + ai: + optional: true + + '@e2e-dev/web@0.15.5': + resolution: {integrity: sha512-fUXrSgfii6w/q7OyX9/kEIDLpIMHpEkTH81hrR8WLnqk8li3bRyXJQBGWqtq9NoWpS2UANnhMI45n6Fv1ErCnw==} + engines: {node: ^22.22.3 || >=24.8.0} + hasBin: true + peerDependencies: + e2e: '>=0.22.1 <1' + '@effect/atom-react@4.1.2': resolution: {integrity: sha512-XRAm4lks2kzNFQIz9QTGKR02CaDTR9VJNRXDjDAR8OzM15ybrK4YkB7OlFZ9U+hxXe3DXJZx7RU1/xI2Em2PGQ==} peerDependencies: @@ -4817,6 +4847,10 @@ packages: '@material/material-color-utilities@0.3.0': resolution: {integrity: sha512-ztmtTd6xwnuh2/xu+Vb01btgV8SQWYCaK56CkRK8gEkWe5TuDyBcYJ0wgkMRn+2VcE9KUmhvkz+N9GHrqw/C0g==} + '@modelcontextprotocol/core@2.4.0': + resolution: {integrity: sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==} + engines: {node: '>=20'} + '@modelcontextprotocol/sdk@1.32.2': resolution: {integrity: sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw==} engines: {node: '>=18'} @@ -4827,6 +4861,10 @@ packages: '@cfworker/json-schema': optional: true + '@modelcontextprotocol/server@2.4.0': + resolution: {integrity: sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==} + engines: {node: '>=20'} + '@muse-code/sdk@1.4.6': resolution: {integrity: sha512-pUENCnmn9q4e2xMXicdRbzbSMdH1fiyTIh5fVBXuxNdNP2ZKA0kwQz5fWMxIB8wzxS2ZyH0v27dvfbZuGuoUjg==} engines: {node: '>=20'} @@ -5131,6 +5169,12 @@ packages: cpu: [arm] os: [android] + '@oxc-parser/binding-android-arm-eabi@0.157.0': + resolution: {integrity: sha512-zFtSEal1K/17LATxVs0VcT/Itt+fxUQ9Ni8HtG+pPcEqy/TenRO74XffkY2dBiy3Pd+w0FuebwCZ6PJx1z7scQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + '@oxc-parser/binding-android-arm64@0.147.0': resolution: {integrity: sha512-emjQHOYJaomo4ykaXQ1EItunr/I94Nk01oqBmU4dSkKSTupIDx6OysVDf2e8Eytm77rb+4ZxzgElyWP7rcEX7A==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5143,6 +5187,12 @@ packages: cpu: [arm64] os: [android] + '@oxc-parser/binding-android-arm64@0.157.0': + resolution: {integrity: sha512-WSlkFUnjamuv+2+TXW5F1rp2I24KVEXj4S+H7J7Y8T/KLR2xXbHj8lgxbZZtjSKi3Z/aGGrlFEOy7EmCWpIUlg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + '@oxc-parser/binding-darwin-arm64@0.147.0': resolution: {integrity: sha512-kXvBPJL7RmDPJ2mze/vXPPVQimCDtFr9OFLjf7dyhV5Dx64cgcXh9KKrA1sMWvCObvJll9CZZUO0FBlFwD0l6A==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5155,6 +5205,12 @@ packages: cpu: [arm64] os: [darwin] + '@oxc-parser/binding-darwin-arm64@0.157.0': + resolution: {integrity: sha512-Usk8UoURmtG2qBLwrO+il+kf6CahEJJriRQACuAwF2CqcWqGsvl9xj9JIMDxP9VTinOt/BZUuDZxcpn68QKsAA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + '@oxc-parser/binding-darwin-x64@0.147.0': resolution: {integrity: sha512-mgFF8pLU6R64LbT27lSrtVRspVC/3IcZ0qyIikzmi78Y3Ik2OPnlAHHI0UEBRcC3qmNgtjaef7zkFt7/uPxIcw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5167,6 +5223,12 @@ packages: cpu: [x64] os: [darwin] + '@oxc-parser/binding-darwin-x64@0.157.0': + resolution: {integrity: sha512-yOvjPixSD2sYJxtQXOzprXdV1xbr2RZyEnbkwFnnxz332Q4+gwkQgCGXZkFlQpc95Fk4XFITACfbFzze4XXktA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + '@oxc-parser/binding-freebsd-x64@0.147.0': resolution: {integrity: sha512-v38aiF11qufOTBcCAKL4skgQf0zJ4NEvRlivq7B5kHrlyvjCLjvNrMtNWDTz1SDUL6/xVsJRmLDxv2e+Cp4oWw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5179,6 +5241,12 @@ packages: cpu: [x64] os: [freebsd] + '@oxc-parser/binding-freebsd-x64@0.157.0': + resolution: {integrity: sha512-BLTsP8TWvmV53jgGBynwv2DR3hKtjpdpL6fXnQs2Fg5P6HsFTShFjrgQrHMSM1cA4lGmlcj7tdTx96RoJfYuuA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + '@oxc-parser/binding-linux-arm-gnueabihf@0.147.0': resolution: {integrity: sha512-AeIiBbwUaP0H1+4/qGW9l5qHecS/+XA5iMuieVcGb1T+tyc2dVGspFW13BWk/XrLsiGP/CiDJTJqAPLLCzZHkw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5191,6 +5259,12 @@ packages: cpu: [arm] os: [linux] + '@oxc-parser/binding-linux-arm-gnueabihf@0.157.0': + resolution: {integrity: sha512-wGMDInIrhayQpNxwpXIWqa2QiKk+/6RxOi4GxPVoqmwrCdn2xj3xXyDUm3RujxQaraZjeWfh0+h9nedoivnL1w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + '@oxc-parser/binding-linux-arm-musleabihf@0.147.0': resolution: {integrity: sha512-/41MKPW4RgPY4DJco0NCF0RYX3IMZaVlRNMNzvhaxRavc7tN3Txm+qllZbh0aMRs0VHdgUlbI8TcAOiTai4TKg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5203,6 +5277,12 @@ packages: cpu: [arm] os: [linux] + '@oxc-parser/binding-linux-arm-musleabihf@0.157.0': + resolution: {integrity: sha512-N6OLfOnku4otlU6eF+HLU+1fH2XAaItc+c7dE+S09SzRZHvkaltU9aGTlMhmAIee95hOqkOCVFHNzQYJ1KS+gQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + '@oxc-parser/binding-linux-arm64-gnu@0.147.0': resolution: {integrity: sha512-bmpw/RPhVXgZbtb3xBDuwW5s8+LvZYdqcDSX/sP2ltL77aTio3DP/B5ZTwwgoJ6Mr9vJs4RrmgEKW9XkLNUU1g==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5217,6 +5297,13 @@ packages: os: [linux] libc: [glibc] + '@oxc-parser/binding-linux-arm64-gnu@0.157.0': + resolution: {integrity: sha512-YfY+qZ8d9tHJEvIq+zXyCcSve/jWgTNDiDtr1W4WVMh5+4fsOjYtH2JDIXIXUkILZzPKgJYbQ08Y/mwhr1gQLQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + '@oxc-parser/binding-linux-arm64-musl@0.147.0': resolution: {integrity: sha512-gd7VX/FDVOw6mjQcu45iIcp4QkgybgJwh3a0OFG2NxmPCj628mQWD96QGu1kK8+mZF9qK4b/gIEyC63vQoB7+Q==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5231,6 +5318,13 @@ packages: os: [linux] libc: [musl] + '@oxc-parser/binding-linux-arm64-musl@0.157.0': + resolution: {integrity: sha512-ytZeO8BKkezwkLoWH3hK0R9Jd+S1BQhcQaWiSAWhXE7Dncq1XiJKb4w5hCe4lwl2ytgoSBgB0XEABhwD2/IhJg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + '@oxc-parser/binding-linux-ppc64-gnu@0.147.0': resolution: {integrity: sha512-HnAzcfki7dSUNHf510Q2NmbJlz8Ys7rn8l9l588Pkx0tYe1BHLZnmELIgqizJ4WPhHGSwN8Ce+B/menVxS3odA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5245,6 +5339,13 @@ packages: os: [linux] libc: [glibc] + '@oxc-parser/binding-linux-ppc64-gnu@0.157.0': + resolution: {integrity: sha512-54w3SexApRhsw3DOAXBZ85rEMR2y29NDOUr18t69fcsnemS/N1YU+zQddHCol/HDhBPyLHg5fpxChRCSzxHwqw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + '@oxc-parser/binding-linux-riscv64-gnu@0.147.0': resolution: {integrity: sha512-qlkOL6wT44U+fT5s/+sR6Shx0OdwvQF83JyIPZUxG/ovqZF5/7atOtjH+JPZ5/7ATQLbFBBSmghcy/+2NVB/ew==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5259,6 +5360,13 @@ packages: os: [linux] libc: [glibc] + '@oxc-parser/binding-linux-riscv64-gnu@0.157.0': + resolution: {integrity: sha512-byg0y1OHdjjhll0qWJQyowKdCxM/zCKysIIOqkWgCid/cR+RU5nTz/63OeAZvIb1z/VB1CyypDRdLn2Ov3r+HQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + '@oxc-parser/binding-linux-riscv64-musl@0.147.0': resolution: {integrity: sha512-DlefD7L7sMXs/3hIBH23Egk0phj8kG0SA81dVGOQ3S1ekjOlmTLH2E+F2Thwfh1slKx6aH+lNc5fQYAw0GU7/g==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5273,6 +5381,13 @@ packages: os: [linux] libc: [musl] + '@oxc-parser/binding-linux-riscv64-musl@0.157.0': + resolution: {integrity: sha512-CiQrt8esQTeL17kscbsfpdx5cywItx3y95YejsihET68oYnxHjbEgj8JaqlIWmhpL2h98piqPBLhWmZbp67nQQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + '@oxc-parser/binding-linux-s390x-gnu@0.147.0': resolution: {integrity: sha512-Xqpagk/031IvZ4svrk2FF01YEqM/iN3MJV3SVZadKg/CsGlDCGoREqKHXYnoV5+8SfGe/m6RM1szXFLusTu/Uw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5287,6 +5402,13 @@ packages: os: [linux] libc: [glibc] + '@oxc-parser/binding-linux-s390x-gnu@0.157.0': + resolution: {integrity: sha512-wSzuUshJVxcrx0c9UJYUOuUf0XHThC1+f8CEfeFbosg7FzTkjCdt89JKKU7BH8C9eTPrnJ5ir4QM0pWpVSmHnA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + '@oxc-parser/binding-linux-x64-gnu@0.147.0': resolution: {integrity: sha512-QioQOeUbI4ATUr0S2z88uA3Cds2R3Mm5Ge7U8XNYtlTb2GJF3rWlcj70z0AJhhOlbdm0YgVjqPBldUNbFylDIg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5301,6 +5423,13 @@ packages: os: [linux] libc: [glibc] + '@oxc-parser/binding-linux-x64-gnu@0.157.0': + resolution: {integrity: sha512-C4BY4QSVzN6R03Ner3r6EtIvLNR4VW4RAb63m+L0tiF/zD7grkBHMn1svyrOBFR4i32+GWJHu05xC4gGQYBhtA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + '@oxc-parser/binding-linux-x64-musl@0.147.0': resolution: {integrity: sha512-NXy1tv/OdC+pPTwf9RiCZWPK53V/Xq/2cjSnjOSyKopajdaDqMIkgtDY+jXZemp2e8px5FeWfY2L2LwhKZQovg==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5315,6 +5444,13 @@ packages: os: [linux] libc: [musl] + '@oxc-parser/binding-linux-x64-musl@0.157.0': + resolution: {integrity: sha512-kN3LdZ2xp9z+TLuzYUWPR/mz/HrKd20vMCGWyby1d8T8K5t5NPemcqfSv3y0oMwXK8OF3lW7MNJnc3uWphvwvw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + '@oxc-parser/binding-openharmony-arm64@0.147.0': resolution: {integrity: sha512-GpGWZ6oKz4bjCWW9Mz5pCaGPyk2Aaze6zEoaslIQqpSLtpx5pXj/ap5gUNb5Jn2LIbqWyjkGLX9yv3NMuNcBVQ==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5327,6 +5463,12 @@ packages: cpu: [arm64] os: [openharmony] + '@oxc-parser/binding-openharmony-arm64@0.157.0': + resolution: {integrity: sha512-cQKUrgBAFUaGcqp9Umb3GToFkvow92YeJxJuzbk8YPnButv9aY5HLyKUpxxh4WqJvP6POiNR5fUDDB5wI8Wiaw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + '@oxc-parser/binding-win32-arm64-msvc@0.147.0': resolution: {integrity: sha512-a8mlt7CC8z7LUdCfaxhff4kCd+vSjE+NEFL0cxA8ukfuSnvAto/pWTjytW4BuVLnQGcCVdHJwcRKOfs++H+tjw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5339,6 +5481,12 @@ packages: cpu: [arm64] os: [win32] + '@oxc-parser/binding-win32-arm64-msvc@0.157.0': + resolution: {integrity: sha512-qZsymd8L67o5bpzZ7gVO7qJUIF9Uf0/mXcoG0MDchBvdL7Q2tAF4aZBZFqc/YRd0WP3jTvqjs3CxlFhHgi48dA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + '@oxc-parser/binding-win32-ia32-msvc@0.147.0': resolution: {integrity: sha512-M5ViVDBcFLnl2632AuuWuP35zEL5oikK1jTx8r3+902VEDeSNHxFZAB6RZyfZ7MU6Oi5QTOG8MmMkIeHsudSaw==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5351,6 +5499,12 @@ packages: cpu: [ia32] os: [win32] + '@oxc-parser/binding-win32-ia32-msvc@0.157.0': + resolution: {integrity: sha512-Ro9PcgwvRglGKI9fEYkbTKvIgh/hzWjv+yPyCTNuxp173i79YbTkkYeOvAEC9SFQPZXYr4+SuIrpCIaWN6sbUA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + '@oxc-parser/binding-win32-x64-msvc@0.147.0': resolution: {integrity: sha512-DUaE13OwnUSlHpLZNcC/nuT10ivlWqc5EZgsfgXuAmWYw0r3nDxGeLD1zlGwYwIgVk1/ZMAxoXpV+05stvbHaA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -5363,10 +5517,20 @@ packages: cpu: [x64] os: [win32] + '@oxc-parser/binding-win32-x64-msvc@0.157.0': + resolution: {integrity: sha512-Ea0fqR+HLzzCt9tYhKbb6aJlM6wBXKWfuDwLhcG519B8HGtxthDzLGfbqMQdlX2Ii5gAZt/Hgxig/iApdxZSzQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + '@oxc-project/runtime@0.155.0': resolution: {integrity: sha512-VbW9raczGS5ZZ1FMunUBYHe4uV/R684qlQCoMdE3n5JT1PcqQsvmFpMYkF8AD+W04fBLGAq6Tr7YsTk0jjvDBA==} engines: {node: ^20.19.0 || >=22.12.0} + '@oxc-project/runtime@0.157.0': + resolution: {integrity: sha512-srnUknwVoji5JdmU664pA4XyjBJXmgxP8rWlnZhFovzw6XQxaICGWAuScZdlLmIHI+ZRc7WgeiC2CURF4tAszQ==} + engines: {node: ^20.19.0 || >=22.12.0} + '@oxc-project/types@0.127.0': resolution: {integrity: sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ==} @@ -5385,6 +5549,9 @@ packages: '@oxc-project/types@0.155.0': resolution: {integrity: sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==} + '@oxc-project/types@0.157.0': + resolution: {integrity: sha512-95iTox1qdt6WGWce3xwNOVayByOfLaYAq+qGPpub6NWbBh9sv0GG3+zyfh9ZBCO/jVu5A0EWI+qQI7g6fevjxg==} + '@oxc-resolver/binding-android-arm-eabi@11.24.2': resolution: {integrity: sha512-y09e0L0SRI2OA2tUIrjBgoV3eH5hvUKXNkJqXmNo5V2WxIjyC7I7aJfRLMEVpA8yi95f90gFDvO0VMgrDw+vwA==} cpu: [arm] @@ -5610,6 +5777,128 @@ packages: cpu: [x64] os: [win32] + '@oxc-transform/binding-android-arm-eabi@0.157.0': + resolution: {integrity: sha512-uRHbSeooFBkwRx9DkedM9YPMAvnwPd9ds6iu+ki9yerAGgTe7dhQAgvrbxrbnhQF3L43QR2LMEkV1zobNpI2cQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxc-transform/binding-android-arm64@0.157.0': + resolution: {integrity: sha512-sZAV2CvG3hqJPG6O3OYF5hXfbWkb+kJQvYdfa0lC788dpQQI+zBR7RpFDpAY+3u4WpV2+v1H8SfSOdsw7aJ1ug==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxc-transform/binding-darwin-arm64@0.157.0': + resolution: {integrity: sha512-/vxwVl483evp5RmWHoz999TL3RW3ghgOlgyd8VNGkBeFgxm2lJRKa0MKzbP7l0v6uIF6789yNe8b7B8BgaTWwA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@oxc-transform/binding-darwin-x64@0.157.0': + resolution: {integrity: sha512-Uoqdq4CaoMh2hyeOl5L2f8cnXOW36KZR2/MzY4E4zAkO2xKYaWHa/XWNPkFeTfnaOi9lmMIvZAYZ8R7ELxRhPg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@oxc-transform/binding-freebsd-x64@0.157.0': + resolution: {integrity: sha512-QFjfMWa/oPK40lyWBCQR8/PlnpgVdPN6yOZqU5HJIzWyo0FwPd7tLpig7rtQgiBEhj+XoyxexXHUVFlwA9Oa/A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@oxc-transform/binding-linux-arm-gnueabihf@0.157.0': + resolution: {integrity: sha512-aQHBtkX/75l8/hvBTggNLpfzPzHZ1vN/qxK9h+r0Gas5XaI4yeW9Qd/VPxGskBgtjmN3BfHXQvAFaj+R9vyBGA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxc-transform/binding-linux-arm-musleabihf@0.157.0': + resolution: {integrity: sha512-dJVOATtEl0LxQuYXTsSAWRay19J5uq7bs1PBHBktEwoCdbXUa8Tm2lPZaX2QuEqC98xk7yAWMOlesv40x6m1rA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxc-transform/binding-linux-arm64-gnu@0.157.0': + resolution: {integrity: sha512-Jdt0PpTwGWEqFkDqkRrR6yJNMevQebaQFnFZIxxnNXPVDze6mNxpEaPvJEmH0Dxzk1vQQm/I/SM08PAAb2qjpg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxc-transform/binding-linux-arm64-musl@0.157.0': + resolution: {integrity: sha512-qCLNQRA3KLaiCG9uXQmFbhjoetlCyfFwFdSXqbVVPCUPi1VFhuBGFltb2ZOMrxE2zMyh9RD27xzVULm+SRB1/A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxc-transform/binding-linux-ppc64-gnu@0.157.0': + resolution: {integrity: sha512-B5bEXT0mG88o2tIoKK/x2KOoXhbab5SjjBm5WfWlcpKLfr8ioYeZPPNT2gZN6FMq+pYuJA3f+i9dFIVlaqFz6w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxc-transform/binding-linux-riscv64-gnu@0.157.0': + resolution: {integrity: sha512-dDYzPGj3/SrcCwWK78FDXg5UXjJRxhVXADxIHvxiCFAeOAUGBFqBS1ykxw/VcsMueDr2QVgsYySPp+VB6fUNSg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxc-transform/binding-linux-riscv64-musl@0.157.0': + resolution: {integrity: sha512-zfplsQ80jaRXnD/l9d1w4awRanMkEiR+rlTJbxOkB+FnuypwHU3JYVJlrQLr/dph3XIrQSkvxsitY2XpyHdLpw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxc-transform/binding-linux-s390x-gnu@0.157.0': + resolution: {integrity: sha512-X7rmxwvgEQrg2qs0goelrFU5X1m5yaTNdnNBT94bK0cQB5q+E7HCxV8eX9wK3qMP8p2bae6N8+ck4gW9XGKBBQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxc-transform/binding-linux-x64-gnu@0.157.0': + resolution: {integrity: sha512-wi5EV43pRIiodHVttWD/785k78IMEyKUaSN1o9JN3Yu1GFBCXJEy9wU4J2V6//4iCeEFywdzQiMbHizG4cl0eQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxc-transform/binding-linux-x64-musl@0.157.0': + resolution: {integrity: sha512-ZK6gmsC1rGiqov3mRltKCwJiRxAhEv7l72TdfClGlLy1kH97GiPsnhLnIiCfqRwahN3W9DX98xMoijhtI/taTg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxc-transform/binding-openharmony-arm64@0.157.0': + resolution: {integrity: sha512-gz2syX2odmf8qzbiEVy+y+giea43tXnTavzy44/JsopYvUodDWOx4aZzu+ZrQZsbfmae1ntDv3NZWyTkbip2yQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxc-transform/binding-win32-arm64-msvc@0.157.0': + resolution: {integrity: sha512-44/lSyHppcduYVtPpWURyUTB8IINPqmwwDFbZKxClGARBhDcPgcvcgI6X4niSUWYJTBHf7vT+OcxmWygRc17dQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxc-transform/binding-win32-ia32-msvc@0.157.0': + resolution: {integrity: sha512-S7a7wqrwQAMTUCocS4weusiQLNY2WP9kJCGCOD1in6PRq1vQFkPt52mh1GLQCzCH+HMBEMx+wK9XotVZBRIVuA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxc-transform/binding-win32-x64-msvc@0.157.0': + resolution: {integrity: sha512-lADvsdq/qHDlkdgzaaJbcwQZOEdNcjrLFW/MdJDG3AhUQSIINibJly2U9Q/yMsoUx/tAnR31gRvWWkLjHq5lxA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + '@oxfmt/binding-android-arm-eabi@0.74.0': resolution: {integrity: sha512-xxQwrf5EPI5zxvuCTW8r6tzCTjPQ+h6+HqJ0iRKRy2zS1yBllt/xLVjoIyUc+FnR7g0a5g1SZv2yyDYhTItLbA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -7017,6 +7306,9 @@ packages: peerDependencies: vitest: 5.0.5 + '@vitest/expect@5.1.0': + resolution: {integrity: sha512-Okx71SHCjnfax7YLaxcJzZINi71BF2S5FezzQipheEQsiBAB0dhRBwuQ7uCJUH0/eGAT6HgAtmVVzrEZo6Qmcw==} + '@vitest/mocker@5.0.5': resolution: {integrity: sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==} peerDependencies: @@ -7028,12 +7320,18 @@ packages: '@vitest/pretty-format@5.0.5': resolution: {integrity: sha512-24sSdIlMA9DVPXnYiB9siwU0bTd887Y9jX3+vabztCSsvHwo7ipvJ/a2L3Rljw8+2rK1f5fCj3h5U9I/Jsqgbw==} + '@vitest/pretty-format@5.1.0': + resolution: {integrity: sha512-IRx5mc30CrFzyMNni6SZKQ1r53kv049Mcvvk0WbWcD6PUz/bFjG4zYv0KosQAeonPpGp5WxqYBMqdSOfJfvVWw==} + '@vitest/snapshot@5.0.5': resolution: {integrity: sha512-dHyFElWMQy0wFBGrIaPPeUWfJFh+jAUrv46ImIJGd8CADdKV3mlrAu3FyD0wesdxELFCs9M807e040Kba/XKtA==} '@vitest/spy@5.0.5': resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + '@vitest/spy@5.1.0': + resolution: {integrity: sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==} + '@vitest/ui@5.0.5': resolution: {integrity: sha512-dCoGUOdgmCaSB2g+WQ/spPCBkytAWdNUkFSXY4z+eYp2d8JEOY8v0uDRaJTG9qf/kTlTVZ4CuYMYMz/f1HS/qQ==} peerDependencies: @@ -7042,6 +7340,9 @@ packages: '@vitest/utils@5.0.5': resolution: {integrity: sha512-/rBu7gzLDQI/SC79Tn98b5DwOgaHU/Gt4I9OVeP3YofzNaYtbImRCOJQmT1S6vOJg9gEIlWC+r3QxKkjuSa1nQ==} + '@vitest/utils@5.1.0': + resolution: {integrity: sha512-V+qgCwkvVw+s1t1S5TaoBHsLi5Sz/YmohCMoOu0mZ8ZQst2bKhRYARAQucWpVg8D0mv0x5MHcWXY5QdOsoiGBQ==} + '@voidzero-dev/vite-plus-core@1.4.0': resolution: {integrity: sha512-LTGXCdZ58qJKfuCOmf0hnZOVA64eOgzDQOqYpI+71tPxk/0cGqPQhYDGQQZoEvNLAn1G2Lo4gKadsQdWxb99WQ==} engines: {node: ^20.19.0 || ^22.18.0 || >=24.11.0} @@ -7390,8 +7691,8 @@ packages: engines: {node: '>=18.18'} hasBin: true - agent-device@0.21.32: - resolution: {integrity: sha512-gfpNs+qeCHKKLY3mqD/NpC7Et7wh5qxNvM9A2cPOhOpzX21e9UHSkO7zOMBpUK7NGtOOkbtz67jco5SVmZOPog==} + agent-device@0.21.36: + resolution: {integrity: sha512-aG88WlEHjFc/OEBQC7AJg+2LfNoVT/ogxnnzIUYUEgafdiTvBaA+X6uQ2wNmpp2ZrHLy8QIXoEOyc3NEZgJCpQ==} engines: {node: '>=22.12'} hasBin: true peerDependencies: @@ -7931,6 +8232,10 @@ packages: resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} engines: {node: '>=20'} + commander@15.0.0: + resolution: {integrity: sha512-z67u4ZhzCL/Tydu1lJARtEZYWbWaN7oYLHbsuzocr6y4N6WZAagG3RQ4FW61V1/0+jImpj293XfrcYnd1qxtPg==} + engines: {node: '>=22.12.0'} + commander@15.1.0: resolution: {integrity: sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==} engines: {node: '>=22.12.0'} @@ -8420,6 +8725,31 @@ packages: duplexer@0.1.2: resolution: {integrity: sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==} + e2e@0.23.0: + resolution: {integrity: sha512-x4wbcLDbwtmB9avyruqQX2j77i8HynAGG74vxA2SVSCJwnD7CaioyfBOxKU3L7J7K7cWIDU0LNz3yR5j29UjNQ==} + engines: {node: ^22.22.3 || >=24.8.0} + hasBin: true + peerDependencies: + '@ai-sdk/anthropic': ^4.0.0 + '@ai-sdk/google': ^4.0.0 + '@ai-sdk/openai': ^4.0.0 + '@ai-sdk/openai-compatible': ^3.0.0 + '@ai-sdk/xai': ^5.0.0 + ai: ^7.0.0 + peerDependenciesMeta: + '@ai-sdk/anthropic': + optional: true + '@ai-sdk/google': + optional: true + '@ai-sdk/openai': + optional: true + '@ai-sdk/openai-compatible': + optional: true + '@ai-sdk/xai': + optional: true + ai: + optional: true + ee-first@1.1.1: resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} @@ -8980,6 +9310,9 @@ packages: fast-json-stable-stringify@2.1.0: resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + fast-png@8.0.0: + resolution: {integrity: sha512-gCysNasJ8KEMgfdYIKd/wTDo6ENK1PWT0RJO7O+0pgmuHPw2O6tA1WvdxFRJoLf9V8yFYpG0FA1YgI8X97OhJA==} + fast-safe-stringify@2.1.1: resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==} @@ -9145,11 +9478,6 @@ packages: fs.realpath@1.0.0: resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} - fsevents@2.3.2: - resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} - engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} - os: [darwin] - fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -10393,6 +10721,10 @@ packages: resolution: {integrity: sha512-syxUKHeUll89RIABQADcI7sikYrwyssvA6gj4phSSIPezKVM8yMaLAiLLSc7fmzVvrwybfFGFbW5zme9sX87rg==} engines: {node: ^20.19.0 || >=22.12.0} + oxc-parser@0.157.0: + resolution: {integrity: sha512-2MJ9tZGXUbEIhQT/O2OPLlYCgur75ES26t2Pb1sYrvDQcRjrE7GmubkALgPEB6LzOY6sM81AAHKfl5M/FgnjJg==} + engines: {node: ^20.19.0 || >=22.12.0} + oxc-resolver@11.24.2: resolution: {integrity: sha512-FY91FiDBj7ls5MsFS9jN3tjz2o0/zsdSsymlakySaBwVJZorHhkWyICLZMKxlu1R9vYo+sd3z1jwb4J8x7bNDw==} @@ -10400,6 +10732,10 @@ packages: resolution: {integrity: sha512-CAx+SKDU4uSOmQnyn7daMj/v/h8tF3fnaUMi4yImKAARPnXV0BieHe/qw1LTcK4KlnIuAhpfUJfSfNKIBh8HqQ==} engines: {node: ^20.19.0 || >=22.12.0} + oxc-transform@0.157.0: + resolution: {integrity: sha512-2H8XPFEbZQv/uoJ863a8YHdNrWWfETcKJ/fVutW7X1ryA5UhhNqaJsV1ib9y2pHOoHfofBIMzfIBCQmzLOVnTA==} + engines: {node: ^20.19.0 || >=22.12.0} + oxfmt@0.74.0: resolution: {integrity: sha512-G4OP7FgwGYZR5ttRpCOOfJdyRsSyvtn34vSXnjDq6Oqed5Dufg5mB44mank+51nAdHOKuTJ0lj0mksY7L+N61A==} engines: {node: ^20.19.0 || >=22.12.0} @@ -10592,6 +10928,10 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + pixelmatch@8.0.0: + resolution: {integrity: sha512-cIqOLfh5k52us715qf3B3+kTOxZv+WDv77HN7xokLScYQGYQHi4m/ynoDIPpvF2LvCyUJGyvzY64i0QCXtzu1g==} + hasBin: true + pkce-challenge@5.0.1: resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} engines: {node: '>=16.20.0'} @@ -10604,14 +10944,14 @@ packages: resolution: {integrity: sha512-emEcLuomt2j03vxD54giVB4SxTjnsqkU692xZOZXHDVoYyypEm+b3jpiTcc+Cf+myooc+/Ly0z01jqeNHVgJGw==} engines: {node: '>=16.0.0'} - playwright-core@1.60.0: - resolution: {integrity: sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==} - engines: {node: '>=18'} + playwright-core@1.64.1: + resolution: {integrity: sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==} + engines: {node: '>=20'} hasBin: true - playwright@1.60.0: - resolution: {integrity: sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==} - engines: {node: '>=18'} + playwright@1.64.1: + resolution: {integrity: sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==} + engines: {node: '>=20'} hasBin: true plist@3.1.0: @@ -12346,6 +12686,10 @@ snapshots: dependencies: json-schema: 0.4.0 + '@ai-sdk/provider@4.0.36': + 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.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(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.2)(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.2)': dependencies: '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.2) @@ -12471,12 +12815,12 @@ snapshots: '@effect/sql-pg': 4.1.2(effect@4.1.2) pg: 8.23.0 - '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(be874ca08ab53e444d5d72e167a81f3f)': + '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(93775fed45909d71c0b8bba962f026cf)': dependencies: '@effect/platform-bun': 4.1.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6) effect: 4.1.2 optionalDependencies: - '@effect/vitest': 4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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.2(bufferutil@4.1.0)(effect@4.1.2)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.2(bufferutil@4.1.0)(effect@4.1.2)(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.2)(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: @@ -13513,6 +13857,18 @@ snapshots: react: 19.3.0 tslib: 2.8.1 + '@e2e-dev/mobile@0.12.6(e2e@0.23.0)': + dependencies: + agent-device: 0.21.36 + e2e: 0.23.0 + pngjs: 7.0.0 + zod: 4.6.7 + + '@e2e-dev/web@0.15.5(e2e@0.23.0)': + dependencies: + e2e: 0.23.0 + playwright-core: 1.64.1 + '@effect/atom-react@4.1.2(effect@4.1.2)(react@19.3.0)(scheduler@0.28.0)': dependencies: effect: 4.1.2 @@ -13603,10 +13959,10 @@ snapshots: '@effect/tsgo-win32-arm64': 0.67.1 '@effect/tsgo-win32-x64': 0.67.1 - '@effect/vitest@4.1.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.60.0)(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.2(patch_hash=299510b71c36537a832a67e9d160a5f112a5f326a29e95c41cb45fc8234e47c7)(@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.2)(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.2 - 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + 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' - '@astrojs/compiler-rs' @@ -14742,6 +15098,10 @@ snapshots: '@material/material-color-utilities@0.3.0': {} + '@modelcontextprotocol/core@2.4.0': + dependencies: + zod: 4.6.7 + '@modelcontextprotocol/sdk@1.32.2(supports-color@8.1.1)(zod@4.6.7)': dependencies: '@hono/node-server': 2.1.6(hono@4.13.17) @@ -14764,6 +15124,11 @@ snapshots: transitivePeerDependencies: - supports-color + '@modelcontextprotocol/server@2.4.0': + dependencies: + '@modelcontextprotocol/core': 2.4.0 + zod: 4.6.7 + '@muse-code/sdk@1.4.6(patch_hash=7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101)(@types/node@24.12.4)': optionalDependencies: '@types/node': 24.12.4 @@ -14994,116 +15359,175 @@ snapshots: '@oxc-parser/binding-android-arm-eabi@0.148.0': optional: true + '@oxc-parser/binding-android-arm-eabi@0.157.0': + optional: true + '@oxc-parser/binding-android-arm64@0.147.0': optional: true '@oxc-parser/binding-android-arm64@0.148.0': optional: true + '@oxc-parser/binding-android-arm64@0.157.0': + optional: true + '@oxc-parser/binding-darwin-arm64@0.147.0': optional: true '@oxc-parser/binding-darwin-arm64@0.148.0': optional: true + '@oxc-parser/binding-darwin-arm64@0.157.0': + optional: true + '@oxc-parser/binding-darwin-x64@0.147.0': optional: true '@oxc-parser/binding-darwin-x64@0.148.0': optional: true + '@oxc-parser/binding-darwin-x64@0.157.0': + optional: true + '@oxc-parser/binding-freebsd-x64@0.147.0': optional: true '@oxc-parser/binding-freebsd-x64@0.148.0': optional: true + '@oxc-parser/binding-freebsd-x64@0.157.0': + optional: true + '@oxc-parser/binding-linux-arm-gnueabihf@0.147.0': optional: true '@oxc-parser/binding-linux-arm-gnueabihf@0.148.0': optional: true + '@oxc-parser/binding-linux-arm-gnueabihf@0.157.0': + optional: true + '@oxc-parser/binding-linux-arm-musleabihf@0.147.0': optional: true '@oxc-parser/binding-linux-arm-musleabihf@0.148.0': optional: true + '@oxc-parser/binding-linux-arm-musleabihf@0.157.0': + optional: true + '@oxc-parser/binding-linux-arm64-gnu@0.147.0': optional: true '@oxc-parser/binding-linux-arm64-gnu@0.148.0': optional: true + '@oxc-parser/binding-linux-arm64-gnu@0.157.0': + optional: true + '@oxc-parser/binding-linux-arm64-musl@0.147.0': optional: true '@oxc-parser/binding-linux-arm64-musl@0.148.0': optional: true + '@oxc-parser/binding-linux-arm64-musl@0.157.0': + optional: true + '@oxc-parser/binding-linux-ppc64-gnu@0.147.0': optional: true '@oxc-parser/binding-linux-ppc64-gnu@0.148.0': optional: true + '@oxc-parser/binding-linux-ppc64-gnu@0.157.0': + optional: true + '@oxc-parser/binding-linux-riscv64-gnu@0.147.0': optional: true '@oxc-parser/binding-linux-riscv64-gnu@0.148.0': optional: true + '@oxc-parser/binding-linux-riscv64-gnu@0.157.0': + optional: true + '@oxc-parser/binding-linux-riscv64-musl@0.147.0': optional: true '@oxc-parser/binding-linux-riscv64-musl@0.148.0': optional: true + '@oxc-parser/binding-linux-riscv64-musl@0.157.0': + optional: true + '@oxc-parser/binding-linux-s390x-gnu@0.147.0': optional: true '@oxc-parser/binding-linux-s390x-gnu@0.148.0': optional: true + '@oxc-parser/binding-linux-s390x-gnu@0.157.0': + optional: true + '@oxc-parser/binding-linux-x64-gnu@0.147.0': optional: true '@oxc-parser/binding-linux-x64-gnu@0.148.0': optional: true + '@oxc-parser/binding-linux-x64-gnu@0.157.0': + optional: true + '@oxc-parser/binding-linux-x64-musl@0.147.0': optional: true '@oxc-parser/binding-linux-x64-musl@0.148.0': optional: true + '@oxc-parser/binding-linux-x64-musl@0.157.0': + optional: true + '@oxc-parser/binding-openharmony-arm64@0.147.0': optional: true '@oxc-parser/binding-openharmony-arm64@0.148.0': optional: true + '@oxc-parser/binding-openharmony-arm64@0.157.0': + optional: true + '@oxc-parser/binding-win32-arm64-msvc@0.147.0': optional: true '@oxc-parser/binding-win32-arm64-msvc@0.148.0': optional: true + '@oxc-parser/binding-win32-arm64-msvc@0.157.0': + optional: true + '@oxc-parser/binding-win32-ia32-msvc@0.147.0': optional: true '@oxc-parser/binding-win32-ia32-msvc@0.148.0': optional: true + '@oxc-parser/binding-win32-ia32-msvc@0.157.0': + optional: true + '@oxc-parser/binding-win32-x64-msvc@0.147.0': optional: true '@oxc-parser/binding-win32-x64-msvc@0.148.0': optional: true + '@oxc-parser/binding-win32-x64-msvc@0.157.0': + optional: true + '@oxc-project/runtime@0.155.0': {} + '@oxc-project/runtime@0.157.0': {} + '@oxc-project/types@0.127.0': optional: true @@ -15118,6 +15542,8 @@ snapshots: '@oxc-project/types@0.155.0': {} + '@oxc-project/types@0.157.0': {} + '@oxc-resolver/binding-android-arm-eabi@11.24.2': optional: true @@ -15236,6 +15662,63 @@ snapshots: '@oxc-transform-react/binding-win32-x64-msvc@0.152.0': optional: true + '@oxc-transform/binding-android-arm-eabi@0.157.0': + optional: true + + '@oxc-transform/binding-android-arm64@0.157.0': + optional: true + + '@oxc-transform/binding-darwin-arm64@0.157.0': + optional: true + + '@oxc-transform/binding-darwin-x64@0.157.0': + optional: true + + '@oxc-transform/binding-freebsd-x64@0.157.0': + optional: true + + '@oxc-transform/binding-linux-arm-gnueabihf@0.157.0': + optional: true + + '@oxc-transform/binding-linux-arm-musleabihf@0.157.0': + optional: true + + '@oxc-transform/binding-linux-arm64-gnu@0.157.0': + optional: true + + '@oxc-transform/binding-linux-arm64-musl@0.157.0': + optional: true + + '@oxc-transform/binding-linux-ppc64-gnu@0.157.0': + optional: true + + '@oxc-transform/binding-linux-riscv64-gnu@0.157.0': + optional: true + + '@oxc-transform/binding-linux-riscv64-musl@0.157.0': + optional: true + + '@oxc-transform/binding-linux-s390x-gnu@0.157.0': + optional: true + + '@oxc-transform/binding-linux-x64-gnu@0.157.0': + optional: true + + '@oxc-transform/binding-linux-x64-musl@0.157.0': + optional: true + + '@oxc-transform/binding-openharmony-arm64@0.157.0': + optional: true + + '@oxc-transform/binding-win32-arm64-msvc@0.157.0': + optional: true + + '@oxc-transform/binding-win32-ia32-msvc@0.157.0': + optional: true + + '@oxc-transform/binding-win32-x64-msvc@0.157.0': + optional: true + '@oxfmt/binding-android-arm-eabi@0.74.0': optional: true @@ -16477,11 +16960,11 @@ snapshots: babel-plugin-react-compiler: 1.0.0 oxc-transform-react: 0.152.0 - '@vitest/browser-playwright@5.0.5(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(playwright@1.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(vitest@5.0.5)(yaml@2.9.0)': + '@vitest/browser-playwright@5.0.5(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(vitest@5.0.5)(yaml@2.9.0)': dependencies: '@vitest/browser': 5.0.5(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(vitest@5.0.5)(yaml@2.9.0) '@vitest/mocker': 5.0.5(@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) - playwright: 1.60.0 + playwright: 1.64.1 tinyrainbow: 3.2.0 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: @@ -16580,6 +17063,15 @@ snapshots: - vue-tsc - yaml + '@vitest/expect@5.1.0': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 5.1.0 + '@vitest/utils': 5.1.0 + chai: 6.3.0 + tinyrainbow: 3.2.0 + '@vitest/mocker@5.0.5(@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)': dependencies: '@jridgewell/trace-mapping': 0.3.31 @@ -16614,6 +17106,10 @@ snapshots: dependencies: tinyrainbow: 3.2.0 + '@vitest/pretty-format@5.1.0': + dependencies: + tinyrainbow: 3.2.0 + '@vitest/snapshot@5.0.5': dependencies: '@vitest/pretty-format': 5.0.5 @@ -16623,6 +17119,8 @@ snapshots: '@vitest/spy@5.0.5': {} + '@vitest/spy@5.1.0': {} + '@vitest/ui@5.0.5(vitest@5.0.5)': dependencies: '@vitest/utils': 5.0.5 @@ -16639,6 +17137,12 @@ snapshots: convert-source-map: 2.0.0 tinyrainbow: 3.2.0 + '@vitest/utils@5.1.0': + dependencies: + '@vitest/pretty-format': 5.1.0 + convert-source-map: 2.0.0 + tinyrainbow: 3.2.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)': dependencies: '@oxc-project/runtime': 0.155.0 @@ -16850,7 +17354,7 @@ snapshots: agent-cli-detector@0.1.7: {} - agent-device@0.21.32: {} + agent-device@0.21.36: {} agent-install@0.0.5: dependencies: @@ -17537,6 +18041,8 @@ snapshots: commander@14.0.3: {} + commander@15.0.0: {} + commander@15.1.0: {} commander@2.20.3: {} @@ -17879,6 +18385,23 @@ snapshots: duplexer@0.1.2: {} + e2e@0.23.0: + dependencies: + '@ai-sdk/provider': 4.0.36 + '@clack/prompts': 1.8.1 + '@jridgewell/remapping': 2.3.5 + '@modelcontextprotocol/server': 2.4.0 + '@oxc-project/runtime': 0.157.0 + '@vitest/expect': 5.1.0 + commander: 15.0.0 + fast-png: 8.0.0 + get-tsconfig: 4.14.3 + oxc-parser: 0.157.0 + oxc-transform: 0.157.0 + picocolors: 1.1.1 + pixelmatch: 8.0.0 + zod: 4.6.7 + ee-first@1.1.1: {} effect@4.1.2: {} @@ -18585,6 +19108,11 @@ snapshots: fast-json-stable-stringify@2.1.0: optional: true + fast-png@8.0.0: + dependencies: + fflate: 0.8.3 + iobuffer: 6.0.1 + fast-safe-stringify@2.1.1: {} fast-sha256@1.3.0: {} @@ -18770,9 +19298,6 @@ snapshots: fs.realpath@1.0.0: {} - fsevents@2.3.2: - optional: true - fsevents@2.3.3: optional: true @@ -20454,6 +20979,30 @@ snapshots: '@oxc-parser/binding-win32-x64-msvc': 0.148.0 optional: true + oxc-parser@0.157.0: + dependencies: + '@oxc-project/types': 0.157.0 + optionalDependencies: + '@oxc-parser/binding-android-arm-eabi': 0.157.0 + '@oxc-parser/binding-android-arm64': 0.157.0 + '@oxc-parser/binding-darwin-arm64': 0.157.0 + '@oxc-parser/binding-darwin-x64': 0.157.0 + '@oxc-parser/binding-freebsd-x64': 0.157.0 + '@oxc-parser/binding-linux-arm-gnueabihf': 0.157.0 + '@oxc-parser/binding-linux-arm-musleabihf': 0.157.0 + '@oxc-parser/binding-linux-arm64-gnu': 0.157.0 + '@oxc-parser/binding-linux-arm64-musl': 0.157.0 + '@oxc-parser/binding-linux-ppc64-gnu': 0.157.0 + '@oxc-parser/binding-linux-riscv64-gnu': 0.157.0 + '@oxc-parser/binding-linux-riscv64-musl': 0.157.0 + '@oxc-parser/binding-linux-s390x-gnu': 0.157.0 + '@oxc-parser/binding-linux-x64-gnu': 0.157.0 + '@oxc-parser/binding-linux-x64-musl': 0.157.0 + '@oxc-parser/binding-openharmony-arm64': 0.157.0 + '@oxc-parser/binding-win32-arm64-msvc': 0.157.0 + '@oxc-parser/binding-win32-ia32-msvc': 0.157.0 + '@oxc-parser/binding-win32-x64-msvc': 0.157.0 + oxc-resolver@11.24.2: optionalDependencies: '@oxc-resolver/binding-android-arm-eabi': 11.24.2 @@ -20498,7 +21047,29 @@ snapshots: '@oxc-transform-react/binding-win32-ia32-msvc': 0.152.0 '@oxc-transform-react/binding-win32-x64-msvc': 0.152.0 - oxfmt@0.74.0(@astrojs/compiler-rs@0.5.1)(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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)): + oxc-transform@0.157.0: + optionalDependencies: + '@oxc-transform/binding-android-arm-eabi': 0.157.0 + '@oxc-transform/binding-android-arm64': 0.157.0 + '@oxc-transform/binding-darwin-arm64': 0.157.0 + '@oxc-transform/binding-darwin-x64': 0.157.0 + '@oxc-transform/binding-freebsd-x64': 0.157.0 + '@oxc-transform/binding-linux-arm-gnueabihf': 0.157.0 + '@oxc-transform/binding-linux-arm-musleabihf': 0.157.0 + '@oxc-transform/binding-linux-arm64-gnu': 0.157.0 + '@oxc-transform/binding-linux-arm64-musl': 0.157.0 + '@oxc-transform/binding-linux-ppc64-gnu': 0.157.0 + '@oxc-transform/binding-linux-riscv64-gnu': 0.157.0 + '@oxc-transform/binding-linux-riscv64-musl': 0.157.0 + '@oxc-transform/binding-linux-s390x-gnu': 0.157.0 + '@oxc-transform/binding-linux-x64-gnu': 0.157.0 + '@oxc-transform/binding-linux-x64-musl': 0.157.0 + '@oxc-transform/binding-openharmony-arm64': 0.157.0 + '@oxc-transform/binding-win32-arm64-msvc': 0.157.0 + '@oxc-transform/binding-win32-ia32-msvc': 0.157.0 + '@oxc-transform/binding-win32-x64-msvc': 0.157.0 + + oxfmt@0.74.0(@astrojs/compiler-rs@0.5.1)(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)): dependencies: tinypool: 2.2.0 optionalDependencies: @@ -20522,7 +21093,7 @@ snapshots: '@oxfmt/binding-win32-arm64-msvc': 0.74.0 '@oxfmt/binding-win32-ia32-msvc': 0.74.0 '@oxfmt/binding-win32-x64-msvc': 0.74.0 - 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + 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) oxlint-tsgolint@7.0.2004: optionalDependencies: @@ -20533,7 +21104,7 @@ snapshots: '@oxlint-tsgolint/win32-arm64': 7.0.2004 '@oxlint-tsgolint/win32-x64': 7.0.2004 - oxlint@1.89.0(oxlint-tsgolint@7.0.2004)(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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)): + oxlint@1.89.0(oxlint-tsgolint@7.0.2004)(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)): optionalDependencies: '@oxlint/binding-android-arm-eabi': 1.89.0 '@oxlint/binding-android-arm64': 1.89.0 @@ -20555,7 +21126,7 @@ snapshots: '@oxlint/binding-win32-ia32-msvc': 1.89.0 '@oxlint/binding-win32-x64-msvc': 1.89.0 oxlint-tsgolint: 7.0.2004 - 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + 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) p-cancelable@2.1.1: {} @@ -20701,6 +21272,10 @@ snapshots: picomatch@4.0.7: {} + pixelmatch@8.0.0: + dependencies: + pngjs: 7.0.0 + pkce-challenge@5.0.1: {} pkg-up@3.1.0: @@ -20716,13 +21291,11 @@ snapshots: pvutils: 1.1.5 tslib: 2.8.1 - playwright-core@1.60.0: {} + playwright-core@1.64.1: {} - playwright@1.60.0: + playwright@1.64.1: dependencies: - playwright-core: 1.60.0 - optionalDependencies: - fsevents: 2.3.2 + playwright-core: 1.64.1 plist@3.1.0: dependencies: @@ -22183,7 +22756,7 @@ snapshots: '@types/unist': 3.0.3 vfile-message: 4.0.3 - 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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0): + 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): dependencies: '@oxc-project/runtime': 0.155.0 '@oxc-project/types': 0.155.0 @@ -22195,13 +22768,13 @@ snapshots: '@vitest/snapshot': 5.0.5 '@vitest/spy': 5.0.5 '@vitest/utils': 5.0.5 - oxfmt: 0.74.0(@astrojs/compiler-rs@0.5.1)(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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)) - oxlint: 1.89.0(oxlint-tsgolint@7.0.2004)(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.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)) + oxfmt: 0.74.0(@astrojs/compiler-rs@0.5.1)(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)) + oxlint: 1.89.0(oxlint-tsgolint@7.0.2004)(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)) oxlint-tsgolint: 7.0.2004 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)' 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) optionalDependencies: - '@vitest/browser-playwright': 5.0.5(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(playwright@1.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(vitest@5.0.5)(yaml@2.9.0) + '@vitest/browser-playwright': 5.0.5(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(vitest@5.0.5)(yaml@2.9.0) '@voidzero-dev/vite-plus-darwin-arm64': 1.4.0 '@voidzero-dev/vite-plus-darwin-x64': 1.4.0 '@voidzero-dev/vite-plus-linux-arm64-gnu': 1.4.0 @@ -22210,7 +22783,7 @@ snapshots: '@voidzero-dev/vite-plus-linux-x64-musl': 1.4.0 '@voidzero-dev/vite-plus-win32-arm64-msvc': 1.4.0 '@voidzero-dev/vite-plus-win32-x64-msvc': 1.4.0 - playwright: 1.60.0 + playwright: 1.64.1 transitivePeerDependencies: - '@arethetypeswrong/core' - '@astrojs/compiler-rs' @@ -22290,7 +22863,7 @@ snapshots: why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 24.12.4 - '@vitest/browser-playwright': 5.0.5(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(playwright@1.60.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(vitest@5.0.5)(yaml@2.9.0) + '@vitest/browser-playwright': 5.0.5(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(vitest@5.0.5)(yaml@2.9.0) '@vitest/browser-preview': 5.0.5(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(vitest@5.0.5)(yaml@2.9.0) '@vitest/ui': 5.0.5(vitest@5.0.5) jsdom: 30.1.0(@noble/hashes@1.8.0) diff --git a/scripts/e2e.config.ts b/scripts/e2e.config.ts new file mode 100644 index 000000000000..6db320e4aa72 --- /dev/null +++ b/scripts/e2e.config.ts @@ -0,0 +1,181 @@ +// Scenarios: e2e tests that run against the real dev stack. See docs/operations/scenarios.md. +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { mobile, type DeviceProvider } from "@e2e-dev/mobile"; +import { web } from "@e2e-dev/web"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { createAgentDeviceClient } from "agent-device"; +import type { E2EConfig } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Path from "effect/Path"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Schedule from "effect/Schedule"; + +import { run, ScenarioError } from "./scenarios/shell.ts"; + +// e2e loads this module for its values, so the paths and the host are resolved once, here. +const resolved = await Effect.gen(function* () { + const path = yield* Path.Path; + const env = yield* HostProcess.Environment; + const scripts = yield* path.fromFileUrl(new URL(".", import.meta.url)); + const home = path.resolve(scripts, "../.t3/scenarios"); + // A pooled device reaches this machine over the tailnet, not localhost. + const host = yield* run("tailscale", ["ip", "-4"]).pipe( + Effect.map((result) => result.stdout.trim().split("\n")[0] ?? ""), + Effect.orElseSucceed(() => ""), + ); + return { + node: yield* HostProcess.ExecutablePath, + scripts, + /** The checkout whose app runs. `prove-scenario.ts` points it at a base or head worktree. */ + appDir: path.resolve(scripts, env.T3_SCENARIO_APP_DIR ?? ".."), + home, + startApp: path.join(scripts, "scenarios/start-app.ts"), + mobile: { + host: host || "127.0.0.1", + // A mobile target has no `app.url`, so e2e cannot pick these ports. + serverPort: Number(env.T3_SCENARIO_SERVER_PORT ?? 13_990), + metroPort: Number(env.T3_SCENARIO_METRO_PORT ?? 8_190), + }, + }; +}).pipe(Effect.provide(NodeServices.layer), Effect.runPromise); + +export const APP_DIR = resolved.appDir; +/** T3 homes only scenarios use, recreated on every run. `.t3` is gitignored. */ +export const T3_HOME = resolved.home; +export const MOBILE_T3_HOME = `${T3_HOME}-mobile`; +export const MOBILE = resolved.mobile; +const startApp = resolved.startApp; + +/** + * Leases a device from the Simlock pool, whose gateway speaks agent-device's lease protocol. + * `retainOnClose` keeps the device when the engine closes its session between attempts. + */ +const simlock = (device: string): DeviceProvider => { + const connect = Effect.fn("simlock.connect")(function* ( + env: Readonly>, + ) { + const daemonBaseUrl = env.SIMLOCK_AGENT_DEVICE_URL; + const daemonAuthToken = env.AGENT_DEVICE_DAEMON_AUTH_TOKEN; + if (daemonBaseUrl === undefined || daemonAuthToken === undefined) { + return yield* new ScenarioError({ + message: "SIMLOCK_AGENT_DEVICE_URL and AGENT_DEVICE_DAEMON_AUTH_TOKEN are not set.", + }); + } + return { daemonBaseUrl, daemonAuthToken }; + }); + const call = (description: string, request: () => Promise) => + Effect.tryPromise({ + try: request, + catch: (cause) => new ScenarioError({ message: `${description}: ${String(cause)}` }), + }); + const acquire = Effect.fn("simlock.acquire")(function* ( + request: Parameters[0], + ) { + const daemon = yield* connect(request.env); + const client = createAgentDeviceClient(daemon); + const platform = request.platform === "android" ? "android" : "ios"; + const scope = { tenant: "t3-scenarios", runId: `${request.runId}-${request.slot}` }; + // Simlock takes the lease id from the caller: 32 hex characters. + const leaseId = (yield* (yield* SecureRandom.SecureRandom).uuidV4()).replaceAll("-", ""); + const lease = yield* call(`The pool leased no ${device}`, () => + client.leases.allocate({ ...scope, platform, device, retainOnClose: true, leaseId }), + ).pipe( + // A busy gateway answers its health probe late, which the client reports as unavailable. + Effect.tapError(() => Effect.sync(() => request.log("the pool is busy; asking again"))), + Effect.retry({ schedule: Schedule.spaced("10 seconds"), times: 12 }), + ); + const leaseScope = { ...scope, leaseId: lease.leaseId, leaseBackend: lease.backend }; + // The pool answers `boot` with the leased device; a worker hosts several, so name ours. + const leased = yield* call("The pool did not name the leased device", () => + createAgentDeviceClient({ ...daemon, ...leaseScope }).devices.boot({ platform }), + ).pipe( + // e2e releases only the leases `acquire` returned. + Effect.tapError(() => + call("release", () => client.leases.release({ leaseId: lease.leaseId })).pipe( + Effect.ignore, + ), + ), + ); + return { + id: lease.leaseId, + daemon: { baseUrl: daemon.daemonBaseUrl, authToken: daemon.daemonAuthToken }, + deviceId: leased.id, + client: { + ...leaseScope, + ...(lease.leaseProvider === undefined ? {} : { leaseProvider: lease.leaseProvider }), + }, + }; + }); + return { + name: "simlock", + acquire: (request) => + acquire(request).pipe(Effect.provide(NodeCrypto.layer), Effect.runPromise), + release: (lease, context) => + connect(context.env).pipe( + Effect.flatMap((daemon) => + call("release", () => + createAgentDeviceClient(daemon).leases.release({ leaseId: lease.id }), + ), + ), + Effect.asVoid, + Effect.runPromise, + ), + }; +}; + +export default { + tests: "scenarios/**/*.e2e.ts", + targets: [ + { + name: "web", + engine: web({ viewport: { width: 1280, height: 800 } }), + app: { + url: "http://127.0.0.1:0", + // Vite answers before the server does; this path is proxied to the server. + readyUrl: "http://127.0.0.1:{port}/.well-known/t3/environment", + command: { + executable: resolved.node, + args: [startApp, "web", T3_HOME, "{port}"], + cwd: APP_DIR, + startupTimeout: 300_000, + log: ".e2e/app.log", + }, + }, + }, + { + name: "ios", + engine: mobile({ + platform: "ios", + device: simlock("iPhone 18 Pro"), + session: "t3-scenarios", + }), + app: { + bundleId: "com.t3tools.t3code.dev", + // Metro starts after the server listens, so it answering means both are up. + readyUrl: `http://127.0.0.1:${MOBILE.metroPort}/status`, + command: { + executable: resolved.node, + args: [ + startApp, + "mobile", + MOBILE_T3_HOME, + String(MOBILE.serverPort), + String(MOBILE.metroPort), + MOBILE.host, + ], + cwd: APP_DIR, + startupTimeout: 300_000, + log: ".e2e/mobile-app.log", + }, + }, + }, + ], + // One server holds every test's state, and a dev stack is heavy. + workers: 1, + timeout: 300_000, + assertionTimeout: 15_000, + video: "on", + trace: "on", + reporters: ["list", "markdown"], +} satisfies E2EConfig; diff --git a/scripts/package.json b/scripts/package.json index 02c0caad7f93..716a2edb3762 100644 --- a/scripts/package.json +++ b/scripts/package.json @@ -4,18 +4,22 @@ "type": "module", "scripts": { "typecheck": "effect-tsgo tsrs --noEmit", + "scenarios": "E2E_TELEMETRY_DISABLED=1 e2e run", "test": "vp test run --config ../vite.config.ts --dir ." }, "dependencies": { + "@e2e-dev/mobile": "0.12.6", + "@e2e-dev/web": "0.15.5", "@effect/platform-node": "catalog:", "@electron/asar": "^4.3.0", "@electron/osx-sign": "2.7.0", "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", "@t3tools/tailscale": "workspace:*", - "agent-device": "0.21.32", + "agent-device": "0.21.36", + "e2e": "0.23.0", "effect": "catalog:", - "playwright-core": "1.60.0", + "playwright-core": "1.64.1", "plist": "catalog:", "pngjs": "7.0.0", "sharp": "0.35.5" diff --git a/scripts/prove-scenario.test.ts b/scripts/prove-scenario.test.ts new file mode 100644 index 000000000000..51fc2f3ece7d --- /dev/null +++ b/scripts/prove-scenario.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { buildProof, readSide } from "./prove-scenario.ts"; + +const report = ( + exitCode: number, + error?: { code: string; message: string }, + status = error ? "failed" : "passed", +) => ({ + run: { + results: [ + { titlePath: ["Another scenario the run did not select"], attempts: [] }, + { + titlePath: ["Tab reaches the submit button"], + attempts: [ + { + status, + steps: [ + { api: "app.open", label: "/pair#token=secret", status: "passed" }, + { api: "expect.toBeFocused", label: "Continue", status: error ? "failed" : "passed" }, + ], + ...(error === undefined ? {} : { error }), + artifacts: [ + { kind: "screenshot", path: "tab/attempt-1/screenshots/001-after-tab.png" }, + { kind: "video", path: "tab/attempt-1/video/video.webm" }, + ], + }, + ], + }, + ], + }, +}); + +const passed = report(0); +const failed = report(1, { code: "ASSERTION_FAILED", message: "expected: focused" }); +// The control the scenario clicks is missing: the scenario is broken, the bug is not shown. +const brokenScenario = report(1, { code: "LOCATOR_NOT_FOUND", message: "no node" }); +// A file with two tests: the first passes, so reading only it would hide the second. +const twoTests = { run: { results: [...passed.run.results, ...failed.run.results] } }; +// e2e exits 0 when the test skips itself at runtime. +const skipped = report(0, undefined, "skipped"); + +describe("prove-scenario", () => { + it.each([ + { base: failed, head: passed, failsOnBase: true, passesOnHead: true, verdict: /^Proven/ }, + // A "fix" for behavior that never happens: the scenario must fail before it can prove. + { + base: passed, + head: passed, + failsOnBase: false, + passesOnHead: true, + verdict: /passes on base/, + }, + { base: failed, head: failed, failsOnBase: true, passesOnHead: false, verdict: /still fails/ }, + { + base: brokenScenario, + head: passed, + failsOnBase: false, + passesOnHead: true, + verdict: /could not run on base/, + }, + { + base: failed, + head: skipped, + failsOnBase: true, + passesOnHead: false, + verdict: /could not run on head/, + }, + { + base: failed, + head: twoTests, + failsOnBase: true, + passesOnHead: false, + verdict: /could not run on head .*exactly one/, + }, + // e2e writes no report when the app does not start. + { + base: undefined, + head: passed, + failsOnBase: false, + passesOnHead: true, + verdict: /could not run on base/, + }, + ])("reports $verdict", (row) => { + const proof = buildProof( + readSide("aaaaaaaaaaaa", "/out/base/results", row.base), + readSide("bbbbbbbbbbbb", "/out/head/results", row.head), + (path) => path, + ); + expect(proof).toMatchObject({ failsOnBase: row.failsOnBase, passesOnHead: row.passesOnHead }); + expect(proof.verdict).toMatch(row.verdict); + }); + + it("labels captures with their side and commit and keeps the pairing token out", () => { + const proof = buildProof( + readSide("aaaaaaaaaaaa", "/out/base/results", failed), + readSide("bbbbbbbbbbbb", "/out/head/results", passed), + (path) => `https://files.example${path}`, + ); + expect(proof.markdown).toContain("| | Base `aaaaaaaaaa` | Head `bbbbbbbbbb` |"); + expect(proof.markdown).toContain( + "![Base aaaaaaaaaa: after tab](https://files.example/out/base/results/tab/attempt-1/screenshots/001-after-tab.png)", + ); + expect(proof.videos).toEqual([ + "/out/base/results/tab/attempt-1/video/video.webm", + "/out/head/results/tab/attempt-1/video/video.webm", + ]); + expect(JSON.stringify(proof)).not.toContain("secret"); + }); +}); diff --git a/scripts/prove-scenario.ts b/scripts/prove-scenario.ts new file mode 100644 index 000000000000..6b0bb9c1a44f --- /dev/null +++ b/scripts/prove-scenario.ts @@ -0,0 +1,325 @@ +#!/usr/bin/env node +// Runs one scenario with `e2e run` on a base and a head commit and says whether it fails on +// base and passes on head. See docs/operations/scenarios.md. +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson"; +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import { Argument, Command, Flag } from "effect/cli"; + +import { run, ScenarioError } from "./scenarios/shell.ts"; + +/** The parts of e2e's report.json (schema/report-v1.schema.json) a proof reads. */ +const E2EReport = Schema.Struct({ + run: Schema.Struct({ + results: Schema.Array( + Schema.Struct({ + titlePath: Schema.Array(Schema.String), + attempts: Schema.Array( + Schema.Struct({ + status: Schema.optional(Schema.String), + steps: Schema.Array( + Schema.Struct({ + api: Schema.String, + label: Schema.optional(Schema.String), + status: Schema.String, + }), + ), + error: Schema.optional(Schema.Struct({ code: Schema.String, message: Schema.String })), + artifacts: Schema.optional( + Schema.Array( + Schema.Struct({ kind: Schema.String, path: Schema.optional(Schema.String) }), + ), + ), + }), + ), + }), + ), + }), +}); +type E2EReport = typeof E2EReport.Type; +const decodeReport = Schema.decodeUnknownEffect(Schema.fromJsonString(E2EReport)); +const encodeProof = Schema.encodeEffect(fromJsonStringPretty(Schema.Unknown)); + +export interface SideResult { + readonly sha: string; + /** `error`: the scenario could not run, which says nothing about the behavior. */ + readonly status: "passed" | "failed" | "error"; + readonly title: string; + readonly message?: string; + readonly steps: ReadonlyArray<{ readonly step: string; readonly status: string }>; + /** Capture paths under the run's results directory, in the order the scenario took them. */ + readonly captures: ReadonlyArray; + readonly videos: ReadonlyArray; +} + +/** Only a failed expectation shows the bug. A missing control or a dead app shows nothing. */ +export function readSide( + sha: string, + resultsDir: string, + report: E2EReport | undefined, +): SideResult { + // The report also lists the tests the run did not select, with no attempts. + const executed = report?.run.results.filter((candidate) => candidate.attempts.length > 0) ?? []; + // One scenario is one test: with several, a pass in the first could hide a failure in another. + const result = executed.length === 1 ? executed[0] : undefined; + const attempt = result?.attempts.at(-1); + if (result === undefined || attempt === undefined) { + const message = + executed.length > 1 + ? `the scenario file ran ${executed.length} tests; a proof needs exactly one` + : "e2e wrote no report: the app did not start, or no test was selected"; + return { sha, status: "error", title: "", message, steps: [], captures: [], videos: [] }; + } + const files = (kind: string) => + (attempt.artifacts ?? []).flatMap((artifact) => + artifact.kind === kind && artifact.path !== undefined + ? [`${resultsDir}/${artifact.path}`] + : [], + ); + const error = attempt.error; + return { + sha, + // e2e exits 0 for a skipped test too, and a test that did not run proves nothing. + status: + attempt.status === "passed" + ? "passed" + : error?.code === "ASSERTION_FAILED" + ? "failed" + : "error", + title: result.titlePath.join(" > "), + ...(error === undefined + ? attempt.status === "passed" + ? {} + : { message: `the test ended ${attempt.status ?? "without a status"}` } + : { message: `${error.code}: ${error.message}` }), + steps: attempt.steps.map((step) => ({ + // The sign-in step's label holds the run's pairing token. + step: `${step.api} ${step.label?.includes("token=") ? "" : (step.label ?? "")}`, + status: step.status, + })), + captures: files("screenshot"), + videos: files("video"), + }; +} + +const short = (sha: string) => sha.slice(0, 10); +const captureLabel = (path: string) => + (path.split("/").at(-1) ?? "") + .replace(/\.png$/, "") + .replace(/^\d+-/, "") + .replaceAll("-", " "); + +/** `link` maps a capture path to what the Markdown should point at, such as an uploaded URL. */ +export function buildProof(base: SideResult, head: SideResult, link: (path: string) => string) { + const baseSha = `\`${short(base.sha)}\``; + const headSha = `\`${short(head.sha)}\``; + const broken = base.status === "error" ? base : head.status === "error" ? head : undefined; + const verdict = + broken !== undefined + ? `Not proven: the scenario could not run on ${broken === base ? `base ${baseSha}` : `head ${headSha}`} (${broken.message ?? "unknown error"}).` + : base.status === "passed" + ? head.status === "passed" + ? `Not proven: the scenario passes on base ${baseSha} too, so it does not reproduce the bug.` + : `Not proven: the scenario passes on base ${baseSha} and fails on head ${headSha}, so head breaks it.` + : head.status === "passed" + ? `Proven: the scenario fails on base ${baseSha} and passes on head ${headSha}.` + : `Not proven: the scenario fails on base ${baseSha} and still fails on head ${headSha}.`; + + const labels = [...new Set([...base.captures, ...head.captures].map(captureLabel))]; + const cell = (side: string, result: SideResult, label: string) => { + const capture = result.captures.find((path) => captureLabel(path) === label); + return capture === undefined + ? "" + : `![${side} ${short(result.sha)}: ${label}](${link(capture)})`; + }; + const outcome = (result: SideResult) => + result.status === "passed" + ? "✅ passed" + : `${result.status === "failed" ? "❌ failed" : "⚠️ could not run"}
    ${(result.message ?? "").replaceAll("\n", "
    ").replaceAll("|", "\\|").replaceAll("

    ", "
    ")}`; + const markdown = [ + `### Scenario: ${head.title || base.title}`, + "", + `**${verdict}**`, + "", + `| | Base ${baseSha} | Head ${headSha} |`, + "| --- | --- | --- |", + `| Result | ${outcome(base)} | ${outcome(head)} |`, + ...labels.map( + (label) => `| ${label} | ${cell("Base", base, label)} | ${cell("Head", head, label)} |`, + ), + "", + ].join("\n"); + return { + scenario: head.title || base.title, + failsOnBase: base.status === "failed", + passesOnHead: head.status === "passed", + baseSha: base.sha, + headSha: head.sha, + verdict, + steps: { base: base.steps, head: head.steps }, + captures: [...base.captures, ...head.captures], + videos: [...base.videos, ...head.videos], + markdown, + base, + head, + }; +} + +const roots = Effect.gen(function* () { + const path = yield* Path.Path; + const scripts = yield* path.fromFileUrl(new URL(".", import.meta.url)); + return { scripts, repo: path.dirname(path.resolve(scripts)) }; +}); + +const git = Effect.fn("prove.git")(function* (args: ReadonlyArray) { + return (yield* run("git", args, { cwd: (yield* roots).repo })).stdout.trim(); +}); + +/** Runs `use` with a checkout of `sha`: this one when it already is that commit, else a worktree. */ +const withCheckout = Effect.fn("prove.withCheckout")(function* ( + sha: string, + use: (appDir: string) => Effect.Effect, +) { + const { repo } = yield* roots; + const clean = (yield* git(["status", "--porcelain", "--untracked-files=no"])).length === 0; + if (clean && (yield* git(["rev-parse", "HEAD"])) === sha) return yield* use(repo); + // Beside this checkout, not in the temp directory, so tooling resolves as it does here. + const worktree = `${repo}-scenario-${short(sha)}`; + return yield* Effect.acquireUseRelease( + git(["worktree", "add", "--quiet", "--detach", "--force", worktree, sha]), + () => run("vp", ["i"], { cwd: worktree, echo: true }).pipe(Effect.andThen(use(worktree))), + () => git(["worktree", "remove", "--force", worktree]).pipe(Effect.ignore), + ); +}); + +/** Runs the scenario with `e2e run` against the app at `sha` and reads the report it wrote. */ +const runSide = Effect.fn("prove.runSide")(function* ( + side: "base" | "head", + rev: string, + scenarioPath: string, +) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { scripts } = yield* roots; + const sha = yield* git(["rev-parse", "--verify", `${rev}^{commit}`]); + const outDir = path.join(scripts, ".e2e/prove", side); + yield* fs.remove(outDir, { recursive: true, force: true }); + const environment = yield* HostProcess.Environment; + yield* withCheckout(sha, (appDir) => + // The scenario and e2e come from this checkout; only the app comes from `appDir`. + run( + path.join(scripts, "node_modules/.bin/e2e"), + ["run", scenarioPath, "--output", path.relative(scripts, outDir)], + { + cwd: scripts, + env: { ...environment, T3_SCENARIO_APP_DIR: appDir, E2E_TELEMETRY_DISABLED: "1" }, + // The report says how the run went; e2e's exit code only repeats it. + allowExit: [0, 1, 2, 3, 4], + echo: true, + }, + ), + ); + const report = yield* fs.readFileString(path.join(outDir, "report.json")).pipe( + Effect.flatMap(decodeReport), + Effect.orElseSucceed(() => undefined), + ); + return readSide(sha, path.join(outDir, "results"), report); +}); + +/** Uploads the captures and maps each to its URL; a failed upload leaves the map empty. */ +const upload = Effect.fn("prove.upload")(function* ( + uploadCommand: string, + captures: ReadonlyArray, +) { + const [command = "", ...args] = uploadCommand.split(/\s+/).filter(Boolean); + if (captures.length === 0) return new Map(); + return yield* run(command, [...args, ...captures]).pipe( + Effect.map((result) => result.stdout.trim().split("\n")), + // Lines pair with captures by position, so a different count would mislabel every image. + Effect.filterOrFail( + (urls) => urls.length === captures.length, + () => new ScenarioError({ message: "The upload command printed an unexpected line count." }), + ), + Effect.map((urls) => new Map(captures.map((capture, index) => [capture, urls[index] ?? ""]))), + // Two finished runs are worth more than their links: the proof then names local files. + Effect.catch((error) => + Console.error(`Upload failed, linking local captures: ${error.message}`).pipe( + Effect.as(new Map()), + ), + ), + ); +}); + +const prove = Effect.fn("prove")(function* (input: { + readonly scenario: string; + readonly base: string; + readonly head: string; + readonly uploadCommand: Option.Option; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { scripts } = yield* roots; + const proveDir = path.join(scripts, ".e2e/prove"); + const scenarioPath = path.resolve(yield* HostProcess.WorkingDirectory, input.scenario); + // A proof left by an earlier run must not be read as this one's. + yield* fs.remove(proveDir, { recursive: true, force: true }); + yield* fs.makeDirectory(proveDir, { recursive: true }); + const base = yield* runSide("base", input.base, scenarioPath); + const head = yield* runSide("head", input.head, scenarioPath); + const links = Option.isSome(input.uploadCommand) + ? yield* upload(input.uploadCommand.value, [...base.captures, ...head.captures]) + : new Map(); + const proof = buildProof( + base, + head, + (capture) => links.get(capture) ?? path.relative(proveDir, capture), + ); + const json = yield* encodeProof(proof); + yield* fs.writeFileString(path.join(proveDir, "proof.md"), proof.markdown); + yield* fs.writeFileString(path.join(proveDir, "proof.json"), `${json}\n`); + yield* Console.log(json); + const couldNotRun = base.status === "error" || head.status === "error"; + return proof.failsOnBase && proof.passesOnHead ? 0 : couldNotRun ? 2 : 1; +}); + +const command = Command.make( + "prove-scenario", + { + scenario: Argument.String("scenario").pipe( + Argument.withDescription("Scenario file, such as scripts/scenarios/name.e2e.ts."), + ), + base: Flag.String("base").pipe(Flag.withDescription("Commit the bug shows on.")), + head: Flag.String("head").pipe( + Flag.withDescription("Commit with the fix."), + Flag.withDefault("HEAD"), + ), + uploadCommand: Flag.String("upload-command").pipe( + Flag.withDescription("Command that takes capture paths and prints one URL per line."), + Flag.optional, + ), + }, + (input) => + prove(input).pipe( + // A bad revision or a failed install is "could not run" (2), not "did not prove" (1). + Effect.catch((error) => Console.error(String(error)).pipe(Effect.as(2))), + Effect.flatMap((exitCode) => + Effect.sync(() => { + process.exitCode = exitCode; + }), + ), + ), +); + +if (import.meta.main) { + Command.run(command, { version: "0.0.0" }).pipe( + Effect.provide(NodeServices.layer), + NodeRuntime.runMain, + ); +} diff --git a/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts b/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts new file mode 100644 index 000000000000..b6afb9358cd2 --- /dev/null +++ b/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts @@ -0,0 +1,22 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "Tab moves from the add-project Git URL field to its submit button", + WEB, + async ({ t3, app, screen, browser }) => { + await t3.project("demo"); + await t3.open(); + + await screen.getByRole("button", "Add project").tap(); + await screen.getByText("Git URL").tap(); + await screen.getByRole("combobox").fill("https://github.com/pingdotgg/t3code.git"); + const submit = screen.getByRole("button", "Continue (Enter)"); + await expect(submit).toBeEnabled(); + + await browser.keyboard.press("Tab"); + await app.screenshot("after-tab"); + await expect(submit).toBeFocused(); + }, +); diff --git a/scripts/scenarios/mobile-opens-a-seeded-thread.e2e.ts b/scripts/scenarios/mobile-opens-a-seeded-thread.e2e.ts new file mode 100644 index 000000000000..b5f2218df881 --- /dev/null +++ b/scripts/scenarios/mobile-opens-a-seeded-thread.e2e.ts @@ -0,0 +1,21 @@ +import { expect } from "e2e"; + +import { IOS, test } from "./t3-mobile.ts"; + +test( + "The iOS app lists a seeded thread and opens its history", + IOS, + async ({ t3, app, screen }) => { + const project = await t3.project("demo"); + await t3.thread({ project, title: "Earlier work", messages: ["first", "second"] }); + await t3.open(); + + const thread = screen.getByText("Earlier work", { exact: false }).first(); + await expect(thread).toBeVisible({ timeout: 120_000 }); + await app.screenshot("home"); + + await thread.tap(); + await expect(screen.getByText("second fixture turn complete", { exact: false })).toBeVisible(); + await app.screenshot("thread"); + }, +); diff --git a/scripts/scenarios/replay-turn-streams.e2e.ts b/scripts/scenarios/replay-turn-streams.e2e.ts new file mode 100644 index 000000000000..b6756a278179 --- /dev/null +++ b/scripts/scenarios/replay-turn-streams.e2e.ts @@ -0,0 +1,26 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A replayed turn streams a reply, shows its tool calls, and finishes", + WEB, + async ({ t3, app, screen }) => { + await t3.project("demo", { "src/math.ts": "export const sum = 1 + 1;\n" }); + await t3.open(); + + await screen.getByRole("textbox").fill("Give me a short tour"); + await screen.getByRole("textbox").press("Enter"); + const stop = screen.getByRole("button", "Stop generation"); + await expect( + screen.getByText("The project has a single math module", { exact: false }), + ).toBeVisible(); + await expect(stop).toBeVisible(); + await app.screenshot("streaming"); + + await expect(screen.getByText("This turn is a replay.", { exact: false })).toBeVisible(); + await expect(stop).toBeHidden(); + await expect(screen.getByText("Give me a short tour").first()).toBeVisible(); + await app.screenshot("finished"); + }, +); diff --git a/scripts/scenarios/shell.ts b/scripts/scenarios/shell.ts new file mode 100644 index 000000000000..40e3b224fa69 --- /dev/null +++ b/scripts/scenarios/shell.ts @@ -0,0 +1,64 @@ +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +export class ScenarioError extends Schema.TaggedError()("ScenarioError", { + message: Schema.String, +}) {} + +interface RunOptions { + readonly cwd?: string; + /** Replaces the inherited environment when given. */ + readonly env?: NodeJS.ProcessEnv; + /** Exit codes that are answers, not failures. Defaults to 0 only. */ + readonly allowExit?: ReadonlyArray; + /** Prints the command's output to stderr as it arrives, keeping stdout for results. */ + readonly echo?: boolean; +} + +const collect = (stream: Stream.Stream, echo: boolean) => + echo + ? stream.pipe( + Stream.decodeText(), + Stream.splitLines, + Stream.tap((line) => Console.error(line)), + Stream.runCollect, + Effect.map((lines) => [...lines].join("\n")), + ) + : Stream.mkString(Stream.decodeText(stream)); + +/** Runs a command to its end and returns what it printed. */ +export const run = Effect.fn("scenario.run")( + function* (program: string, args: ReadonlyArray, options: RunOptions = {}) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* spawner.spawn( + ChildProcess.make(program, [...args], { + ...(options.cwd === undefined ? {} : { cwd: options.cwd }), + ...(options.env === undefined ? {} : { env: options.env, extendEnv: false }), + stdin: "ignore", + stdout: "pipe", + stderr: "pipe", + }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collect(child.stdout, options.echo === true), + collect(child.stderr, options.echo === true), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + if (!(options.allowExit ?? [0]).includes(exitCode)) { + return yield* new ScenarioError({ + message: `${program} ${args.slice(0, 3).join(" ")} exited with ${exitCode}: ${stderr.trim().slice(-600)}`, + }); + } + return { stdout, stderr, exitCode: Number(exitCode) }; + }, + Effect.scoped, + Effect.mapError((error) => + error._tag === "ScenarioError" ? error : new ScenarioError({ message: String(error) }), + ), +); diff --git a/scripts/scenarios/start-app.ts b/scripts/scenarios/start-app.ts new file mode 100644 index 000000000000..5eabe224b977 --- /dev/null +++ b/scripts/scenarios/start-app.ts @@ -0,0 +1,235 @@ +#!/usr/bin/env node +// The app command of e2e.config.ts: starts the dev stack of the checkout it runs in on a fresh +// T3 home. e2e stops it with a signal, which ends the scope and the processes it started. +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NetService from "@t3tools/shared/Net"; +import * as Console from "effect/Console"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import { Argument, Command } from "effect/cli"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +import { ScenarioError } from "./shell.ts"; + +// The dev runner's web port is 5733 plus an offset. Mirror of BASE_WEB_PORT in dev-runner.ts. +const BASE_WEB_PORT = 5733; +// The replay agent `vp run dev` registers: free, recorded turns through the real adapter. +const REPLAY = { instanceId: "devReplay", model: "showcase" }; +// Generated text (titles) cannot go to the replay agent: the server swaps an ACP agent for the +// first enabled real provider, else its default, Codex. So every provider it could fall back to +// is off and Codex is a command that only fails: no run reaches a paid model. +// Mirror of TEXT_GENERATION_FALLBACK_DRIVERS in shared/serverSettings. +const REAL_PROVIDERS = [ + "codex", + "claudeAgent", + "cursor", + "grok", + "muse", + "pi", + "opencode", + "antigravity", +]; + +// The server labels its environment with the host's name, probed through these commands. +// Captures must not depend on, or show, the machine that made them. +const HOST_LABEL_SHIM = `#!/bin/sh +case "$*" in + "--pretty" | "--get ComputerName") echo "Scenario" ;; + *) for real in /usr/bin /usr/sbin /bin; do + [ -x "$real/$(basename "$0")" ] && exec "$real/$(basename "$0")" "$@" + done + exit 127 ;; +esac +`; + +const encodeSettings = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); + +const prepareHome = Effect.fn("startApp.prepareHome")(function* (home: string) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fs.remove(home, { recursive: true, force: true }); + yield* fs.makeDirectory(path.join(home, "userdata"), { recursive: true }); + yield* fs.makeDirectory(path.join(home, "bin")); + for (const command of ["hostnamectl", "scutil"]) { + const shim = path.join(home, "bin", command); + yield* fs.writeFileString(shim, HOST_LABEL_SHIM); + yield* fs.chmod(shim, 0o755); + } + const noModel = path.join(home, "bin/no-model"); + yield* fs.writeFileString(noModel, "#!/bin/sh\necho 'scenarios run no model' >&2\nexit 1\n"); + yield* fs.chmod(noModel, 0o755); + yield* fs.writeFileString( + path.join(home, "userdata/settings.json"), + yield* encodeSettings({ + defaultModelSelection: REPLAY, + providerInstances: Object.fromEntries( + REAL_PROVIDERS.map((driver) => [ + driver, + { + driver, + enabled: false, + ...(driver === "codex" ? { config: { binaryPath: noModel } } : {}), + }, + ]), + ), + }), + ); +}); + +/** Starts a process in the caller's scope and hands each line it prints to `onLine`. */ +const start = Effect.fn("startApp.start")(function* (input: { + readonly cwd: string; + readonly command: string; + readonly args: ReadonlyArray; + readonly env: NodeJS.ProcessEnv; + readonly onLine: (line: string) => Effect.Effect; +}) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const child = yield* spawner.spawn( + ChildProcess.make(input.command, [...input.args], { + cwd: input.cwd, + env: input.env, + extendEnv: false, + stdin: "ignore", + stdout: "pipe", + stderr: "inherit", + forceKillAfter: "5 seconds", + }), + ); + yield* child.stdout.pipe( + Stream.decodeText(), + Stream.splitLines, + Stream.runForEach(input.onLine), + Effect.ignore, + Effect.forkScoped, + ); + return child; +}); + +const startApp = Effect.fn("startApp")(function* (input: { + readonly surface: "web" | "mobile"; + readonly home: string; + readonly ports: ReadonlyArray; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const net = yield* NetService.NetService; + const node = yield* HostProcess.ExecutablePath; + const checkout = yield* HostProcess.WorkingDirectory; + const hostEnvironment = yield* HostProcess.Environment; + yield* prepareHome(input.home); + const env = { + ...hostEnvironment, + PATH: `${path.join(input.home, "bin")}:${hostEnvironment.PATH ?? ""}`, + T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "0", + }; + const devRunner = (mode: string, args: ReadonlyArray) => [ + "scripts/dev-runner.ts", + mode, + "--home-dir", + input.home, + "--no-seed", + ...args, + ]; + + if (input.surface === "web") { + const [webPort = ""] = input.ports; + const serverPort = yield* net.reserveLoopbackPort(); + const token = yield* (yield* SecureRandom.SecureRandom).uuidV4(); + const runner = yield* start({ + cwd: checkout, + command: node, + args: devRunner("dev", ["--port", String(serverPort)]), + env: { + ...env, + T3CODE_PORT_OFFSET: String(Number(webPort) - BASE_WEB_PORT), + T3CODE_DEV_ALLOWED_ORIGINS: `http://127.0.0.1:${webPort}`, + // Makes the startup pairing link reusable, so every test can sign in with it. + T3CODE_DEV_AUTH_TOKEN: `${token}${token}`.replaceAll("-", ""), + }, + onLine: (line) => { + const url = /pairingUrl:\s*(\S+)/.exec(line)?.[1]; + if (url === undefined) return Console.log(line); + // The link is a credential: it goes to a file the tests read, never to the log. + const { pathname, search, hash } = new URL(url); + return fs + .writeFileString(path.join(input.home, "pairing-path"), `${pathname}${search}${hash}`) + .pipe(Effect.ignore); + }, + }); + return yield* runner.exitCode; + } + + // The device is another machine: the server listens on every interface, and Metro serves the + // dev client its JavaScript. Tests mint their own pairing links, so the startup one is dropped. + const [serverPort = "", metroPort = "", host = ""] = input.ports; + const server = yield* start({ + cwd: checkout, + command: node, + args: devRunner("dev:server", ["--host", "0.0.0.0", "--port", serverPort]), + env, + onLine: (line) => (line.includes("pairingUrl:") ? Effect.void : Console.log(line)), + }); + yield* net.hasListenerOnHost(Number(serverPort), "127.0.0.1").pipe( + Effect.filterOrFail( + (listening) => listening, + () => new ScenarioError({ message: "The server is not listening yet." }), + ), + Effect.retry({ schedule: Schedule.spaced("500 millis"), times: 600 }), + ); + const metro = yield* start({ + cwd: path.join(checkout, "apps/mobile"), + command: "npx", + args: ["expo", "start", "--dev-client", "--scheme", "t3code-dev", "--lan", "--port", metroPort], + env: { + ...env, + APP_VARIANT: "development", + CI: "1", + // Lazily fetched chunks sometimes arrive broken on pool devices. + EXPO_NO_METRO_LAZY: "1", + REACT_NATIVE_PACKAGER_HOSTNAME: host, + }, + onLine: Console.log, + }); + return yield* Effect.raceFirst(server.exitCode, metro.exitCode); +}); + +const command = Command.make( + "start-app", + { + surface: Argument.Literals("surface", ["web", "mobile"]).pipe( + Argument.withDescription( + "web: server and Vite. mobile: server on every interface and Metro.", + ), + ), + home: Argument.String("t3-home").pipe(Argument.withDescription("T3 home to recreate.")), + ports: Argument.String("port").pipe( + Argument.withDescription("web: . mobile: ."), + Argument.variadic(), + ), + }, + (input) => + startApp(input).pipe( + Effect.flatMap((exitCode) => + Effect.sync(() => { + process.exitCode = Number(exitCode) || 1; + }), + ), + ), +); + +if (import.meta.main) { + Command.run(command, { version: "0.0.0" }).pipe( + Effect.scoped, + Effect.provide([NodeServices.layer, NodeCrypto.layer, NetService.layer]), + NodeRuntime.runMain, + ); +} diff --git a/scripts/scenarios/t3-mobile.ts b/scripts/scenarios/t3-mobile.ts new file mode 100644 index 000000000000..154030dd7abe --- /dev/null +++ b/scripts/scenarios/t3-mobile.ts @@ -0,0 +1,93 @@ +// `test` for iOS scenarios: e2e's mobile test plus `t3`, which seeds state like the web one and +// opens the dev client paired with the scenario's server. +import { test as base } from "@e2e-dev/mobile"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { APP_DIR, MOBILE, MOBILE_T3_HOME } from "../e2e.config.ts"; +import { run, ScenarioError } from "./shell.ts"; +import { makeState, runPromise, type T3State } from "./t3.ts"; + +const APP_ID = "com.t3tools.t3code.dev"; +const SCHEME = "t3code-dev"; + +export interface MobileT3 extends T3State { + /** Installs the dev client if the device lacks it, loads it from Metro, and pairs it. */ + readonly open: () => Promise; +} + +const decodePrepared = Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Struct({ fingerprint: Schema.String })), +); + +/** The dev client built for this checkout's native code, from the shared cache. */ +const devClientPath = Effect.gen(function* () { + const path = yield* Path.Path; + const prepared = yield* run( + yield* HostProcess.ExecutablePath, + ["scripts/mobile-native-client.ts", "ensure", "ios", "--prepare"], + { cwd: APP_DIR }, + ); + const { fingerprint } = yield* decodePrepared(prepared.stdout.trim().split("\n").at(-1) ?? ""); + return path.join( + yield* HostProcess.HomeDirectory, + ".cache/t3code/native-clients/artifacts/ios/development", + fingerprint, + "T3CodeDev.app", + ); +}); + +// A leased device is wiped when it returns to the pool, so one install and pairing last the run. +let installed = false; +let paired = false; + +export const test = base.extend<{ t3: MobileT3 }>({ + t3: async ({ device, screen }, use) => { + const { state, cli, cleanup } = makeState(MOBILE_T3_HOME, { + T3CODE_PORT: String(MOBILE.serverPort), + }); + const pairingUrl = Effect.gen(function* () { + const origin = `http://${MOBILE.host}:${MOBILE.serverPort}`; + const pairing = ["auth", "pairing", "create", "--ttl", "15m", "--label", "scenario"]; + const created = yield* cli([...pairing, "--base-url", origin]); + const url = /Pair URL:\s*(\S+)/.exec(`${created.stdout}\n${created.stderr}`)?.[1]; + return url ?? (yield* new ScenarioError({ message: "The server printed no pairing URL." })); + }); + await use({ + ...state, + open: async () => { + if (!installed) { + await device.installApp(await runPromise(devClientPath)); + installed = true; + } + // iOS asks before a link opens another app. + const openLink = async (url: string) => { + await device.openLink(url, { app: APP_ID }); + await device.alert("accept").catch(() => {}); + }; + const metro = encodeURIComponent(`http://${MOBILE.host}:${MOBILE.metroPort}`); + await openLink( + `${SCHEME}://expo-development-client/?url=${metro}&disableOnboarding=1&disableFab=1&disableAutoLaunch=1`, + ); + // The first load bundles the app; the pairing link only works once it is on screen. + if (paired) return; + await expect(screen.getByRole("button", "Add environment")).toBeVisible({ + timeout: 240_000, + }); + const query = new URLSearchParams({ + pairingUrl: await runPromise(pairingUrl), + autoConnect: "1", + }); + await openLink(`${SCHEME}://connections/new?${query.toString()}`); + paired = true; + }, + }); + await runPromise(cleanup); + }, +}); + +/** Test option for an iOS scenario: the web target skips it, and no device is leased for it. */ +export const IOS = { platforms: ["ios"] } as const; diff --git a/scripts/scenarios/t3.ts b/scripts/scenarios/t3.ts new file mode 100644 index 000000000000..4df481ace8cf --- /dev/null +++ b/scripts/scenarios/t3.ts @@ -0,0 +1,140 @@ +// `test` for web scenarios: e2e's web test plus `t3`, which seeds state and opens the signed-in +// app. `t3-mobile.ts` is the same for the iOS app. +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { test as base } from "@e2e-dev/web"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { APP_DIR, T3_HOME } from "../e2e.config.ts"; +import { run } from "./shell.ts"; + +export interface T3State { + /** Creates a git repository holding `files` and adds it as a project. Returns its path. */ + readonly project: (title: string, files?: Readonly>) => Promise; + /** + * Starts a thread in a project and plays one replayed turn per message before returning. + * `model` is a dev replay recording: showcase, todo-list, approval, question, multi-turn. + */ + readonly thread: (input: { + readonly project: string; + readonly title: string; + readonly messages: ReadonlyArray; + readonly model?: string; + }) => Promise; +} + +export interface T3 extends T3State { + /** Opens the app, signed in, at `path`. */ + readonly open: (path?: string) => Promise; +} + +/** e2e's fixtures are promise functions; this is the one place an Effect becomes a promise. */ +export const runPromise = (effect: Effect.Effect) => + Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer))); + +const decodeLaunched = Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Struct({ threadId: Schema.String })), +); + +/** State for the server on `home`, made through the app's own CLI: real events, not inserted rows. */ +export function makeState(home: string, env: NodeJS.ProcessEnv = {}) { + const cli = Effect.fn("scenario.cli")(function* ( + args: ReadonlyArray, + allowExit: ReadonlyArray = [0], + ) { + const hostEnvironment = yield* HostProcess.Environment; + return yield* run( + yield* HostProcess.ExecutablePath, + ["apps/server/src/bin.ts", ...args, "--base-dir", home], + { + cwd: APP_DIR, + env: { PATH: hostEnvironment.PATH, HOME: hostEnvironment.HOME, ...env }, + allowExit, + }, + ); + }); + const projects: Array = []; + + const project = Effect.fn("scenario.project")(function* ( + title: string, + files: Readonly>, + ) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + // Its own folder per test: the server and this home outlive one test. + yield* fs.makeDirectory(path.join(home, "workspaces"), { recursive: true }); + const parent = yield* fs.makeTempDirectory({ + directory: path.join(home, "workspaces"), + prefix: "w-", + }); + const workspace = path.join(parent, title); + for (const [file, content] of Object.entries({ "README.md": "", ...files })) { + yield* fs.makeDirectory(path.dirname(path.join(workspace, file)), { recursive: true }); + yield* fs.writeFileString(path.join(workspace, file), content); + } + const git = (args: ReadonlyArray) => run("git", args, { cwd: workspace }); + const author = ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid"]; + yield* git(["init", "--quiet", "--initial-branch=main"]); + yield* git(["add", "--all"]); + yield* git([...author, "commit", "--quiet", "--message", "Initial commit"]); + yield* cli(["project", "add", workspace, "--title", title]); + projects.push(workspace); + return workspace; + }); + + const thread = Effect.fn("scenario.thread")(function* (input: { + readonly project: string; + readonly title: string; + readonly messages: ReadonlyArray; + readonly model?: string; + }) { + // Exit code 2 means the turn waits for an answer, which a scenario may want to start from. + const turn = (args: ReadonlyArray) => + cli(["thread", ...args, "--wait", "--json"], [0, 2]); + const [first = "Start", ...rest] = input.messages; + const replay = ["--provider", "devReplay", "--model", input.model ?? "multi-turn"]; + const started = yield* turn(["start", input.project, first, "--title", input.title, ...replay]); + const { threadId } = yield* decodeLaunched(started.stdout); + for (const message of rest) yield* turn(["send", threadId, message]); + }); + + return { + cli, + state: { + project: (title, files = {}) => runPromise(project(title, files)), + thread: (input) => runPromise(thread(input)), + } satisfies T3State, + // The server outlives the test, so the next one must not see this one's projects. + cleanup: Effect.forEach( + projects, + (workspace) => cli(["project", "remove", workspace, "--force"]), + { discard: true }, + ), + }; +} + +const readPairingPath = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + return yield* fs.readFileString(path.join(T3_HOME, "pairing-path")); +}); + +export const test = base.extend<{ t3: T3 }>({ + t3: async ({ app }, use) => { + const { state, cleanup } = makeState(T3_HOME); + await use({ + ...state, + open: async (path = "/") => { + await app.open(await runPromise(readPairingPath)); + if (path !== "/") await app.open(path); + }, + }); + await runPromise(cleanup); + }, +}); + +/** Test option for a web scenario: the iOS target skips it. */ +export const WEB = { platforms: ["web"] } as const; From 9e1f81c78894270c7e281c78402a69a1a97c4474 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 15:47:22 -0800 Subject: [PATCH 048/170] feat(claude): Fable resets are offered and redeemed apart from weekly resets (#34106) Co-authored-by: Claude Opus 5.5 --- .../src/features/usage/UsageLimitsSection.tsx | 85 +++++++++---------- .../src/provider/Drivers/ClaudeDriver.ts | 10 ++- .../provider/ProviderInstanceRegistry.test.ts | 2 +- .../src/provider/claudeResetCredits.test.ts | 44 +++++++++- .../server/src/provider/claudeResetCredits.ts | 62 +++++++++++++- apps/server/src/ws.ts | 2 +- apps/web/src/components/usage/UsageLimits.tsx | 82 ++++++++---------- .../components/usage/UsageLimitsPooled.tsx | 58 +++++++------ packages/contracts/src/providerUsageLimits.ts | 17 +++- packages/provider-core/src/server/driver.ts | 7 +- packages/shared/src/usageLimits.ts | 51 +++++++++++ 11 files changed, 285 insertions(+), 135 deletions(-) diff --git a/apps/mobile/src/features/usage/UsageLimitsSection.tsx b/apps/mobile/src/features/usage/UsageLimitsSection.tsx index 214e64fab628..be4bf0c929d1 100644 --- a/apps/mobile/src/features/usage/UsageLimitsSection.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsSection.tsx @@ -11,7 +11,8 @@ import { type ServerProviderUsageWindow, } from "@t3tools/contracts"; import { - formatDuration, + type ResetCreditChoice, + resetCreditChoices, formatResetsIn, limitsNotice, paceOf, @@ -243,21 +244,11 @@ export function ResetCredits(props: { const [status, setStatus] = useState(null); if (dense && credits.availableCount === 0 && status === null) return null; - const expiresIn = credits.nextExpiresAt - ? formatDuration(Date.parse(credits.nextExpiresAt) - now) - : null; - const summary = - credits.availableCount === 0 - ? "No reset credits banked" - : `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${ - expiresIn ? ` · next expires in ${expiresIn}` : "" - }`; - - const redeem = async () => { + const redeem = async (choice: ResetCreditChoice) => { if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return; setBusy(true); setStatus(null); - const result = await consume({ environmentId, input }); + const result = await consume({ environmentId, input: choice.input }); setBusy(false); if (result._tag === "Success") { setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]); @@ -270,44 +261,44 @@ export function ResetCredits(props: { ); }; - const confirm = () => { + const confirm = (choice: ResetCreditChoice) => { if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return; - Dialog.alert( - "Use a reset credit?", - "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.", - [ - { text: "Cancel", style: "cancel" }, - { text: "Use credit", onPress: () => void redeem() }, - ], - ); + Dialog.alert("Use a reset credit?", choice.confirmDescription, [ + { text: "Cancel", style: "cancel" }, + { text: "Use credit", onPress: () => void redeem(choice) }, + ]); }; return ( - - {summary} - {credits.availableCount > 0 ? ( - - - {busy ? "Using…" : "Use reset"} - - - ) : null} + + {resetCreditChoices(credits, input, now).map((choice) => ( + + {choice.summary} + {choice.availableCount > 0 ? ( + confirm(choice)} + className={ + dense + ? "rounded-full bg-subtle-strong px-2.5 py-1 disabled:opacity-[0.45]" + : "min-h-[44px] justify-center rounded-full bg-subtle-strong px-3 py-1.5 disabled:opacity-[0.45]" + } + > + + {busy ? "Using…" : choice.actionLabel} + + + ) : null} + + ))} {!canManageProviders ? ( This connection cannot manage provider accounts. diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index c2d4b6386107..3ada12297649 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -309,9 +309,15 @@ export const ClaudeDriver: ProviderDriver = Effect.fn( "ClaudeDriver.consumeResetCredit", )( - function* () { + function* (creditId) { const current = yield* snapshot.getSnapshot; - const grantId = current.usageLimits?.resetCredits?.nextCreditId; + const credits = current.usageLimits?.resetCredits; + const grantId = + creditId === undefined + ? credits?.nextCreditId + : credits?.options?.some((option) => option.creditId === creditId) + ? creditId + : undefined; if (!grantId || !current.version) return "noCredit" as const; const version = current.version; return yield* resetCreditCoordinator.redeem( diff --git a/apps/server/src/provider/ProviderInstanceRegistry.test.ts b/apps/server/src/provider/ProviderInstanceRegistry.test.ts index e998332d3e92..95866780189a 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.test.ts @@ -664,7 +664,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { const before = yield* instance!.snapshot.refresh; expect(before.usageLimits?.windows[0]?.usedPercent).toBe(100); expect(before.usageLimits?.resetCredits?.nextCreditId).toBe("grant_a"); - const outcome = yield* instance!.consumeResetCredit!().pipe(Effect.result); + const outcome = yield* instance!.consumeResetCredit!(undefined).pipe(Effect.result); return { outcome, after: yield* instance!.snapshot.getSnapshot }; }).pipe( // macOS logins live in the Keychain, where resets are never read. diff --git a/apps/server/src/provider/claudeResetCredits.test.ts b/apps/server/src/provider/claudeResetCredits.test.ts index 8db751657454..a3a1110d87d3 100644 --- a/apps/server/src/provider/claudeResetCredits.test.ts +++ b/apps/server/src/provider/claudeResetCredits.test.ts @@ -62,9 +62,51 @@ describe("claudeResetCreditsToContract", () => { availableCount: 2, nextCreditId: "grant_a", nextExpiresAt: "2026-10-01T00:00:00.000Z", + options: [ + expect.objectContaining({ + creditId: "grant_a", + label: "Full reset", + availableCount: 2, + expiresAt: "2026-10-01T00:00:00.000Z", + }), + ], }); }); + it("offers each kind of reset by its own grant", () => { + const credits = ClaudeResetCredits.claudeResetCreditsToContract( + { + eligible: true, + next_grant_id: "weekly_a", + grants: [ + grant({ id: "weekly_a", clears: ["seven_day"], ends_at: "2026-12-10T22:00:00Z" }), + grant({ + id: "fable_a", + clears: ["seven_day_overage_included"], + gives_back_weekly: true, + ends_at: "2027-03-09T07:59:00Z", + }), + grant({ id: "fable_b", gives_back_weekly: true, type: "weekly" }), + grant({ id: "session_a", type: "session" }), + grant({ id: "spent", clears: ["seven_day"], resets_left: 0 }), + ], + }, + NOW, + ); + expect( + credits?.options?.map(({ creditId, label, availableCount }) => [ + creditId, + label, + availableCount, + ]), + ).toEqual([ + ["session_a", "5-hour reset", 1], + ["weekly_a", "Weekly reset", 1], + ["fable_a", "Fable reset", 2], + ]); + expect(credits).toMatchObject({ availableCount: 4, nextCreditId: "weekly_a" }); + }); + it("offers nothing to redeem without a usable next grant or an eligible account", () => { expect( ClaudeResetCredits.claudeResetCreditsToContract( @@ -111,7 +153,7 @@ effectIt.layer(NodeServices.layer)("readClaudeResetCredits", (it) => { Effect.provideService(HostProcess.Platform, "linux"), Effect.provideService(HttpClient.HttpClient, client), ); - expect(credits).toEqual({ availableCount: 1, nextCreditId: "grant_a" }); + expect(credits).toMatchObject({ availableCount: 1, nextCreditId: "grant_a" }); }), ); diff --git a/apps/server/src/provider/claudeResetCredits.ts b/apps/server/src/provider/claudeResetCredits.ts index 35973378edad..e1dbacc34ba7 100644 --- a/apps/server/src/provider/claudeResetCredits.ts +++ b/apps/server/src/provider/claudeResetCredits.ts @@ -1,5 +1,6 @@ import type { ProviderConsumeResetCreditOutcome, + ServerProviderResetCreditOption, ServerProviderResetCredits, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -31,6 +32,9 @@ const Grant = Schema.Struct({ ends_at: Schema.optional(Schema.NullOr(Schema.String)), paused: Schema.optional(Schema.Boolean), usable_now: Schema.optional(Schema.Boolean), + clears: Schema.optional(Schema.Array(Schema.Unknown)), + type: Schema.optional(Schema.Unknown), + gives_back_weekly: Schema.optional(Schema.Boolean), }); const decodeGrant = Schema.decodeUnknownOption(Grant); const CedarEmber = Schema.Struct({ @@ -95,6 +99,31 @@ const isFutureTimestamp = (value: string, nowMs: number) => { ); }; +// Claude Code's own grouping: a grant that gives back weekly usage is a Fable reset, else its +// declared type, else what it clears. +const RESET_KINDS = { + session: { label: "5-hour reset", description: "Refills your 5-hour limit." }, + weekly: { label: "Weekly reset", description: "Refills your weekly limit." }, + fable: { + label: "Fable reset", + description: + "Refills your Fable allowance and gives back what Fable used on your weekly limit. It doesn't reset your whole week.", + }, + full: { label: "Full reset", description: "Refills your 5-hour and weekly limits." }, +} as const; +type ResetKind = keyof typeof RESET_KINDS; + +const grantKind = (grant: typeof Grant.Type): ResetKind => { + if (grant.gives_back_weekly) return "fable"; + if (grant.type === "session" || grant.type === "weekly" || grant.type === "full") { + return grant.type; + } + const clears = grant.clears ?? []; + const session = clears.includes("five_hour"); + const other = clears.some((limit) => limit !== "five_hour"); + return session && !other ? "session" : other && !session ? "weekly" : "full"; +}; + export function claudeResetCreditsToContract( block: unknown, nowMs: number, @@ -110,13 +139,38 @@ export function claudeResetCreditsToContract( (grant.ends_at == null || isFutureTimestamp(grant.ends_at, nowMs)), ); const next = live.find((grant) => grant.id === parsed.value.next_grant_id); - const nextExpiresAt = next?.ends_at ? DateTime.make(next.ends_at) : Option.none(); + const expiresAt = (grant: typeof Grant.Type | undefined) => { + const at = grant?.ends_at ? DateTime.make(grant.ends_at) : Option.none(); + return Option.isSome(at) ? DateTime.formatIso(at.value) : undefined; + }; + const byKind = new Map>(); + for (const grant of live) { + if (grant.resets_left === 0) continue; + const kind = grantKind(grant); + byKind.set(kind, [...(byKind.get(kind) ?? []), grant]); + } + const options = (Object.keys(RESET_KINDS) as Array).flatMap( + (kind): Array => { + const grants = byKind.get(kind); + const target = grants?.[0]; + if (!grants || !target) return []; + const optionExpiresAt = expiresAt(target); + return [ + { + creditId: target.id, + ...RESET_KINDS[kind], + availableCount: grants.reduce((sum, grant) => sum + grant.resets_left, 0), + ...(optionExpiresAt ? { expiresAt: optionExpiresAt } : {}), + }, + ]; + }, + ); + const nextExpiresAt = expiresAt(next); return { availableCount: next ? live.reduce((sum, grant) => sum + grant.resets_left, 0) : 0, - ...(Option.isSome(nextExpiresAt) - ? { nextExpiresAt: DateTime.formatIso(nextExpiresAt.value) } - : {}), + ...(nextExpiresAt ? { nextExpiresAt } : {}), ...(next ? { nextCreditId: next.id } : {}), + ...(next ? { options } : {}), }; } diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 8a8c4e1be719..9721864fcdfd 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2649,7 +2649,7 @@ export const layerWsRpc = ( detail: "This provider does not bank reset credits.", }); } - const outcome = yield* instance.consumeResetCredit().pipe( + const outcome = yield* instance.consumeResetCredit(input.creditId).pipe( Effect.mapError( (error) => new ProviderSetupError({ diff --git a/apps/web/src/components/usage/UsageLimits.tsx b/apps/web/src/components/usage/UsageLimits.tsx index 43ee023af240..e41aa20998b1 100644 --- a/apps/web/src/components/usage/UsageLimits.tsx +++ b/apps/web/src/components/usage/UsageLimits.tsx @@ -11,12 +11,13 @@ import { import { useAtomValue } from "@effect/atom-react"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; import { - formatDuration, formatResetsIn, type LimitPace, paceOf, paceRemainingPercent, remainingPercent, + type ResetCreditChoice, + resetCreditChoices, } from "@t3tools/shared/usageLimits"; import { GaugeIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react"; import { Fragment, useLayoutEffect, useState } from "react"; @@ -237,22 +238,21 @@ const OUTCOME_TEXT: Record = { alreadyRedeemed: "That credit was already redeemed.", }; -export function useResetCredit( - environmentId: EnvironmentId, - input: ProviderConsumeResetCreditInput, -) { +export function useResetCredit(environmentId: EnvironmentId) { const canManageProviders = useEnvironmentScope(environmentId, AuthProvidersManageScope); const consume = useAtomCommand(serverEnvironment.consumeResetCredit, { reportFailure: false }); + // Kept after close so the dialog's text survives its exit animation. + const [choice, setChoice] = useState(null); const [confirming, setConfirming] = useState(false); const [busy, setBusy] = useState(false); const [status, setStatus] = useState(null); const redeem = async () => { setConfirming(false); - if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return; + if (!choice || !readEnvironmentScope(environmentId, AuthProvidersManageScope)) return; setBusy(true); setStatus(null); - const result = await consume({ environmentId, input }); + const result = await consume({ environmentId, input: choice.input }); setBusy(false); if (result._tag === "Success") { setStatus(result.value.warning ?? OUTCOME_TEXT[result.value.outcome]); @@ -265,7 +265,13 @@ export function useResetCredit( ); }; - return { canManageProviders, confirming, setConfirming, busy, status, redeem }; + const confirm = (next: ResetCreditChoice) => { + if (!readEnvironmentScope(environmentId, AuthProvidersManageScope)) return; + setChoice(next); + setConfirming(true); + }; + + return { canManageProviders, choice, confirming, setConfirming, confirm, busy, status, redeem }; } /** Require confirmation because redemption spends credits. Mount outside popovers, which stack above @@ -273,11 +279,13 @@ export function useResetCredit( export function ResetCreditDialog({ open, onOpenChange, + choice, onConfirm, disabled = false, }: { readonly open: boolean; readonly onOpenChange: (open: boolean) => void; + readonly choice: ResetCreditChoice | null; readonly onConfirm: () => void; readonly disabled?: boolean; }) { @@ -286,10 +294,7 @@ export function ResetCreditDialog({ Use a reset credit? - - This redeems one credit on your account and clears the current rate-limit windows. It - cannot be undone. - + {choice?.confirmDescription} }>Cancel @@ -302,22 +307,6 @@ export function ResetCreditDialog({ ); } -export function resetCreditsSummary( - credits: ServerProviderResetCredits, - now: number, - compact = false, -): string { - const expiresIn = credits.nextExpiresAt - ? formatDuration(Date.parse(credits.nextExpiresAt) - now) - : null; - if (credits.availableCount === 0) return "No reset credits banked"; - if (compact) - return `${credits.availableCount} banked${expiresIn ? ` · expires in ${expiresIn}` : ""}`; - return `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${ - expiresIn ? ` · next expires in ${expiresIn}` : "" - }`; -} - export function ResetCredits({ environmentId, input, @@ -329,30 +318,31 @@ export function ResetCredits({ readonly credits: ServerProviderResetCredits; readonly now: number; }) { - const { canManageProviders, confirming, setConfirming, busy, status, redeem } = useResetCredit( - environmentId, - input, - ); + const { canManageProviders, choice, confirming, setConfirming, confirm, busy, status, redeem } = + useResetCredit(environmentId); if (credits.availableCount === 0 && status === null) return null; return ( -
    - {resetCreditsSummary(credits, now)} - {credits.availableCount > 0 ? ( - - ) : null} +
    + {resetCreditChoices(credits, input, now).map((choice) => ( +
    + {choice.summary} + {choice.availableCount > 0 ? ( + + ) : null} +
    + ))} {status ? {status} : null} void redeem()} disabled={!canManageProviders} /> diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 00f437246584..f2d5790ece53 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -13,6 +13,8 @@ import { type LimitPoolWindow, paceRemainingPercent, remainingPercent, + type ResetCreditChoice, + resetCreditChoices, } from "@t3tools/shared/usageLimits"; import type { Popover as PopoverPrimitive } from "@base-ui/react/popover"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; @@ -39,14 +41,7 @@ import { Button } from "../ui/button"; import { OpenAI } from "../Icons"; import { Alert, AlertTitle } from "../ui/alert"; import { Popover, PopoverCreateHandle, PopoverPopup, PopoverTrigger } from "../ui/popover"; -import { - PaceIcon, - ResetCreditDialog, - barColor, - usePaceMark, - resetCreditsSummary, - useResetCredit, -} from "./UsageLimits"; +import { PaceIcon, ResetCreditDialog, barColor, usePaceMark, useResetCredit } from "./UsageLimits"; function accountInitials(email: string): string { const [local = "", domain = ""] = email.split("@"); @@ -146,7 +141,7 @@ function SegmentPopover({ readonly reset: LimitPoolWindow["resets"][number] | undefined; readonly now: number; readonly redeem: ReturnType | null; - readonly onRedeem: () => void; + readonly onRedeem: (choice: ResetCreditChoice) => void; }) { const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat); const remaining = remainingPercent(window); @@ -156,8 +151,10 @@ function SegmentPopover({ account.environments.length > 0 ? account.environments.map((environment) => environment.label).join(", ") : account.sourceLabel; - const credits = - redeem && account.limits.resetCredits?.availableCount ? account.limits.resetCredits : null; + const choices = + redeem && account.redeem && account.limits.resetCredits?.availableCount + ? resetCreditChoices(account.limits.resetCredits, account.redeem.input, now, true) + : []; return (
    @@ -196,20 +193,24 @@ function SegmentPopover({ +{reset.restoresPercent}% of pool ) : null}
    - {credits && redeem ? ( -
    - - {resetCreditsSummary(credits, now, true)} - - + {choices.length > 0 && redeem ? ( +
    + {choices.map((choice) => ( + + {choice.summary} + {choice.availableCount > 0 ? ( + + ) : null} + + ))}
    ) : null}
    @@ -264,9 +265,9 @@ function ActiveSegmentPopover({ { + onRedeem={(choice) => { handle.close(); - payload.redeem?.setConfirming(true); + payload.redeem?.confirm(choice); }} /> @@ -303,13 +304,14 @@ function RedeemableSegment({ }: Omit[0], "redeem"> & { readonly redeemAt: NonNullable; }) { - const redeem = useResetCredit(redeemAt.environmentId, redeemAt.input); + const redeem = useResetCredit(redeemAt.environmentId); return ( <> void redeem.redeem()} disabled={!redeem.canManageProviders} /> diff --git a/packages/contracts/src/providerUsageLimits.ts b/packages/contracts/src/providerUsageLimits.ts index 5c4927d4a164..67acbe0d35b0 100644 --- a/packages/contracts/src/providerUsageLimits.ts +++ b/packages/contracts/src/providerUsageLimits.ts @@ -20,11 +20,23 @@ export const ServerProviderUsageWindow = Schema.Struct({ }); export type ServerProviderUsageWindow = typeof ServerProviderUsageWindow.Type; +/** One kind of banked reset, such as Claude's weekly reset or its Fable-only reset. */ +export const ServerProviderResetCreditOption = Schema.Struct({ + creditId: TrimmedNonEmptyString, + label: TrimmedNonEmptyString, + description: TrimmedNonEmptyString, + availableCount: NonNegativeInt, + expiresAt: Schema.optional(IsoDateTime), +}); +export type ServerProviderResetCreditOption = typeof ServerProviderResetCreditOption.Type; + export const ServerProviderResetCredits = Schema.Struct({ availableCount: NonNegativeInt, nextExpiresAt: Schema.optional(IsoDateTime), /** Pins hub redemption to the displayed credit, including retries from another client. */ nextCreditId: Schema.optional(TrimmedNonEmptyString), + /** Present when resets differ in what they refill; redeem one by its `creditId`. */ + options: Schema.optional(ForwardCompatibleArray(ServerProviderResetCreditOption)), }); export type ServerProviderResetCredits = typeof ServerProviderResetCredits.Type; @@ -87,7 +99,10 @@ export type UsageLimitSourceConsumeResetCreditInput = typeof UsageLimitSourceConsumeResetCreditInput.Type; export const ProviderConsumeResetCreditInput = Schema.Union([ - Schema.Struct({ instanceId: ProviderInstanceId }), + Schema.Struct({ + instanceId: ProviderInstanceId, + creditId: Schema.optional(TrimmedNonEmptyString), + }), UsageLimitSourceConsumeResetCreditInput, ]); export type ProviderConsumeResetCreditInput = typeof ProviderConsumeResetCreditInput.Type; diff --git a/packages/provider-core/src/server/driver.ts b/packages/provider-core/src/server/driver.ts index a1771e2e748e..3fee55c6fbca 100644 --- a/packages/provider-core/src/server/driver.ts +++ b/packages/provider-core/src/server/driver.ts @@ -45,10 +45,9 @@ export interface ProviderInstance { ) => Effect.Effect; readonly refreshModels?: () => Effect.Effect; readonly invalidateCaches?: Effect.Effect; - readonly consumeResetCredit?: () => Effect.Effect< - ProviderConsumeResetCreditOutcome, - ProviderDriverError - >; + readonly consumeResetCredit?: ( + creditId: string | undefined, + ) => Effect.Effect; readonly orchestrationAdapter: ProviderAdapter.ProviderAdapterV2["Service"]; readonly textGeneration: ProviderTextGeneration; readonly auth?: ProviderAuthController; diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 1707deb735a4..24403fe8a6c5 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -11,6 +11,7 @@ import { isProviderAvailable, PROVIDER_DISPLAY_NAMES, type ServerProvider, + type ServerProviderResetCredits, type ServerProviderUsageLimits, type ServerProviderUsageWindow, type UsageLimitSourceSnapshots, @@ -675,6 +676,56 @@ export function formatDuration(ms: number): string { return `${minutes}m`; } +/** One redeemable reset as clients offer it; `input` already names the chosen credit. */ +export interface ResetCreditChoice { + readonly key: string; + readonly summary: string; + readonly actionLabel: string; + readonly confirmDescription: string; + readonly availableCount: number; + readonly input: ProviderConsumeResetCreditInput; +} + +export function resetCreditChoices( + credits: ServerProviderResetCredits, + input: ProviderConsumeResetCreditInput, + now: number, + compact = false, +): ReadonlyArray { + const expiresIn = (at: string | undefined) => (at ? formatDuration(Date.parse(at) - now) : null); + if (credits.options && "instanceId" in input) { + return credits.options.map((option) => { + const expires = expiresIn(option.expiresAt); + return { + key: option.creditId, + summary: `${option.label} · ${option.availableCount} left${expires ? ` · expires in ${expires}` : ""}`, + actionLabel: "Use", + confirmDescription: `${option.label}: ${option.description} This cannot be undone.`, + availableCount: option.availableCount, + input: { ...input, creditId: option.creditId }, + }; + }); + } + const count = credits.availableCount; + const expires = expiresIn(credits.nextExpiresAt); + return [ + { + key: "next", + summary: + count === 0 + ? "No reset credits banked" + : compact + ? `${count} banked${expires ? ` · expires in ${expires}` : ""}` + : `${count} ${count === 1 ? "reset credit" : "reset credits"} banked${expires ? ` · next expires in ${expires}` : ""}`, + actionLabel: "Use reset", + confirmDescription: + "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.", + availableCount: count, + input, + }, + ]; +} + export function formatResetsIn(window: ServerProviderUsageWindow, now: number): string | null { const resetsAt = resetMillis(window); if (resetsAt === null) return null; From 04f6cfca87203192ccf2c36f7ba8c80baf9ba9da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 15:48:43 -0800 Subject: [PATCH 049/170] fix(desktop): desktop IPC only answers the main app window (#34094) Co-authored-by: Claude Fable 5.2 --- apps/desktop/src/ipc/DesktopIpc.test.ts | 67 +++++++++++++++++++ apps/desktop/src/ipc/DesktopIpc.ts | 54 ++++++++++++++- .../src/ipc/methods/notificationBadge.test.ts | 2 +- apps/desktop/src/ipc/methods/preview.test.ts | 17 +++-- apps/desktop/src/ipc/methods/window.test.ts | 2 +- apps/desktop/src/main.ts | 2 +- apps/desktop/src/window/DesktopWindow.ts | 3 +- 7 files changed, 133 insertions(+), 14 deletions(-) create mode 100644 apps/desktop/src/ipc/DesktopIpc.test.ts diff --git a/apps/desktop/src/ipc/DesktopIpc.test.ts b/apps/desktop/src/ipc/DesktopIpc.test.ts new file mode 100644 index 000000000000..45f63b951f36 --- /dev/null +++ b/apps/desktop/src/ipc/DesktopIpc.test.ts @@ -0,0 +1,67 @@ +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import { assert, it } from "@effect/vitest"; +import { vi } from "vite-plus/test"; + +vi.mock("electron", () => ({})); + +import * as ElectronWindow from "../electron/ElectronWindow.ts"; +import * as DesktopIpc from "./DesktopIpc.ts"; + +it.effect("answers only the main window's top frame", () => + Effect.gen(function* () { + const mainFrame = {}; + const invoke = new Map(); + const sync = new Map(); + const ipc = yield* DesktopIpc.DesktopIpc.pipe( + Effect.provide( + DesktopIpc.layer({ + removeHandler: (channel) => void invoke.delete(channel), + handle: (channel, listener) => void invoke.set(channel, listener), + removeAllListeners: (channel) => void sync.delete(channel), + on: (channel, listener) => void sync.set(channel, listener), + }).pipe( + Layer.provide( + Layer.mock(ElectronWindow.ElectronWindow, { + main: Effect.succeedSome({ + webContents: { id: 1, mainFrame }, + } as unknown as Electron.BrowserWindow), + }), + ), + ), + ), + ); + yield* ipc.handle( + DesktopIpc.makeIpcMethod({ + channel: "token", + payload: Schema.Void, + result: Schema.String, + handler: () => Effect.succeed("secret"), + }), + ); + yield* ipc.handleSync({ channel: "token-sync", handler: () => Effect.succeed("secret") }); + + const senders = { + app: { sender: { id: 1 }, senderFrame: mainFrame }, + appSubframe: { sender: { id: 1 }, senderFrame: {} }, + previewGuest: { sender: { id: 2 }, senderFrame: {} }, + }; + const results: Record = {}; + for (const [name, sender] of Object.entries(senders)) { + const event = { ...sender, returnValue: "unset" as unknown }; + sync.get("token-sync")!(event); + results[name] = [ + yield* Effect.promise(() => + Promise.resolve(invoke.get("token")!(sender, undefined)).catch(() => "rejected"), + ), + event.returnValue, + ]; + } + assert.deepEqual(results, { + app: ["secret", "secret"], + appSubframe: ["rejected", undefined], + previewGuest: ["rejected", undefined], + }); + }).pipe(Effect.scoped), +); diff --git a/apps/desktop/src/ipc/DesktopIpc.ts b/apps/desktop/src/ipc/DesktopIpc.ts index 354acc5a8155..69d4f70c15a0 100644 --- a/apps/desktop/src/ipc/DesktopIpc.ts +++ b/apps/desktop/src/ipc/DesktopIpc.ts @@ -1,17 +1,23 @@ 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 Scope from "effect/Scope"; +import * as ElectronWindow from "../electron/ElectronWindow.ts"; + export interface DesktopIpcInvokeEvent { readonly sender: { readonly id: number }; + readonly senderFrame?: unknown; } -export interface DesktopIpcSyncEvent { +export interface DesktopIpcSyncEvent extends DesktopIpcInvokeEvent { returnValue: unknown; } +export type DesktopIpcSenderGuard = (event: DesktopIpcInvokeEvent) => Effect.Effect; + export type DesktopIpcHandleListener = ( event: DesktopIpcInvokeEvent, raw: unknown, @@ -52,6 +58,15 @@ export class DesktopIpcUnregistrationError extends Schema.TaggedError()( + "DesktopIpcUntrustedSenderError", + { channel: Schema.String }, +) { + override get message(): string { + return `Rejected ${this.channel} from a sender that is not the app window.`; + } +} + export const DesktopIpcError = Schema.Union([ DesktopIpcRegistrationError, DesktopIpcUnregistrationError, @@ -80,7 +95,11 @@ export class DesktopIpc extends Context.Service< } >()("@t3tools/desktop/ipc/DesktopIpc") {} -export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] => +// ipcMain is shared by every webContents, including preview guests that load arbitrary pages. +export const make = ( + ipcMain: DesktopIpcMain, + isTrustedSender: DesktopIpcSenderGuard, +): DesktopIpc["Service"] => DesktopIpc.of({ handle: Effect.fn("desktop.ipc.registerInvoke")(function* ({ channel, @@ -98,6 +117,9 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] => runPromise( Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ channel }); + if (!(yield* isTrustedSender(event))) { + return yield* new DesktopIpcUntrustedSenderError({ channel }); + } return yield* handler(raw, event); }).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")), ), @@ -131,6 +153,11 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] => event.returnValue = runSync( Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ channel }); + // Throwing here would surface as an uncaught main-process exception. + if (!(yield* isTrustedSender(event))) { + yield* Effect.logWarning("Rejected sync IPC from an untrusted sender."); + return undefined; + } return yield* handler(); }).pipe( Effect.annotateLogs({ channel }), @@ -152,7 +179,28 @@ export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] => }), }); -export const layer = (ipcMain: DesktopIpcMain) => Layer.succeed(DesktopIpc, make(ipcMain)); +export const layer = (ipcMain: DesktopIpcMain) => + Layer.effect( + DesktopIpc, + Effect.gen(function* () { + const electronWindow = yield* ElectronWindow.ElectronWindow; + return make(ipcMain, (event) => + Effect.map( + electronWindow.main, + (main) => + Option.isSome(main) && + main.value.webContents.id === event.sender.id && + main.value.webContents.mainFrame === event.senderFrame, + ), + ); + }), + ); + +export const layerTest = (ipcMain: DesktopIpcMain) => + Layer.succeed( + DesktopIpc, + make(ipcMain, () => Effect.succeed(true)), + ); export interface DesktopIpcMethodRegistration< Payload, diff --git a/apps/desktop/src/ipc/methods/notificationBadge.test.ts b/apps/desktop/src/ipc/methods/notificationBadge.test.ts index 7126b1cd3194..b3c85c9ead28 100644 --- a/apps/desktop/src/ipc/methods/notificationBadge.test.ts +++ b/apps/desktop/src/ipc/methods/notificationBadge.test.ts @@ -80,7 +80,7 @@ it.effect("validates IPC and clears on native focus, quit, and disposal", () => Effect.provideService(HostProcess.Platform, "linux"), Effect.provide([ ElectronApp.layer, - DesktopIpc.layer({ + DesktopIpc.layerTest({ handle: (channel, handler) => { handlers.set(channel, handler); }, diff --git a/apps/desktop/src/ipc/methods/preview.test.ts b/apps/desktop/src/ipc/methods/preview.test.ts index 802f2f3fb18b..bd7e44bec830 100644 --- a/apps/desktop/src/ipc/methods/preview.test.ts +++ b/apps/desktop/src/ipc/methods/preview.test.ts @@ -42,14 +42,17 @@ describe("preview IPC methods", () => { Effect.scoped( Effect.gen(function* () { let listener: DesktopIpc.DesktopIpcHandleListener | undefined; - const ipc = DesktopIpc.make({ - removeHandler: vi.fn(), - handle: (_channel, registered) => { - listener = registered; + const ipc = DesktopIpc.make( + { + removeHandler: vi.fn(), + handle: (_channel, registered) => { + listener = registered; + }, + removeAllListeners: vi.fn(), + on: vi.fn(), }, - removeAllListeners: vi.fn(), - on: vi.fn(), - }); + () => Effect.succeed(true), + ); yield* ipc.handle(method); return yield* Effect.promise(async () => structuredClone(await listener!({ sender: { id: 7 } }, { tabId: "capture-tab" })), diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index eebabd429025..376f85d2baf9 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -202,7 +202,7 @@ describe("installRelayTelemetryEnabled", () => { yield* installRelayTelemetryEnabled().pipe( Effect.provideService(HostProcess.Environment, env), Effect.provide( - Layer.mergeAll(DesktopIpc.layer(ipcMain), DesktopManagedPolicy.layerTest(policy)), + Layer.mergeAll(DesktopIpc.layerTest(ipcMain), DesktopManagedPolicy.layerTest(policy)), ), ); const event = { returnValue: undefined as unknown }; diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index d109518be15e..e3971d7c74ea 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -139,7 +139,7 @@ const layerElectron = Layer.mergeAll( ElectronTheme.layer, ElectronUpdater.layer, ElectronWindow.layer, - DesktopIpc.layer(Electron.ipcMain), + DesktopIpc.layer(Electron.ipcMain).pipe(Layer.provide(ElectronWindow.layer)), ); const layerDesktopFoundation = Layer.mergeAll( diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 45a54714ca26..73f5b41810da 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -907,6 +907,8 @@ export const make = Effect.gen(function* () { void runPromise(revealWhenReady); }); + // Desktop IPC only answers the main window, so register it before its renderer can call in. + yield* electronWindow.setMain(window); loadApplication(); if (environment.isDevelopment) { window.webContents.openDevTools({ mode: "detach" }); @@ -925,7 +927,6 @@ export const make = Effect.gen(function* () { const createMain = Effect.gen(function* () { const window = yield* createWindow(); if (Option.isSome(window)) { - yield* electronWindow.setMain(window.value); mainClosedDuringStartup = false; yield* logWindowInfo("main window created"); } From 79bca436b24a6eabb05d3d1a95348ae40d31e713 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 16:05:37 -0800 Subject: [PATCH 050/170] feat(server): voice models reuse copies already on disk (#34096) Co-authored-by: Claude Fable 5.2 --- .../src/speech/SpeechModelStore.test.ts | 52 ++++++++ apps/server/src/speech/SpeechModelStore.ts | 120 ++++++++++++++++++ apps/server/src/speech/SpeechService.test.ts | 2 + apps/server/src/speech/SpeechService.ts | 23 +++- apps/server/src/speech/http.test.ts | 44 ++++++- apps/server/src/speech/http.ts | 40 +++++- .../settings/VoiceSettingsPanel.tsx | 54 +++++++- docs/internals/voice-input.md | 3 + docs/user/voice-input.md | 10 ++ .../src/voice-input/environment.ts | 11 ++ .../client-runtime/src/voice-input/index.ts | 1 + packages/contracts/src/environmentHttp.ts | 9 ++ packages/contracts/src/speech.ts | 7 + 13 files changed, 366 insertions(+), 10 deletions(-) diff --git a/apps/server/src/speech/SpeechModelStore.test.ts b/apps/server/src/speech/SpeechModelStore.test.ts index e08a4cf022f4..be25e4f290b1 100644 --- a/apps/server/src/speech/SpeechModelStore.test.ts +++ b/apps/server/src/speech/SpeechModelStore.test.ts @@ -12,6 +12,8 @@ import * as Path from "effect/Path"; import * as Stream from "effect/Stream"; import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + import * as ServerConfig from "../config.ts"; import * as SpeechModelStore from "./SpeechModelStore.ts"; @@ -168,3 +170,53 @@ it.effect("cleans only download partials on cancellation or restart", () => ]); }).pipe(Effect.provide(dependencies)), ); + +it.effect("links a verified model file from another folder and never deletes it", () => + Effect.gen(function* () { + const h = yield* harness; + const path = yield* Path.Path; + const elsewhere = yield* h.fs.makeTempDirectoryScoped({ prefix: "speech-other-app-" }); + const nested = path.join(elsewhere, "hub", "snapshots"); + yield* h.fs.makeDirectory(nested, { recursive: true }); + const impostor = path.join(elsewhere, "same-size.gguf"); + const existing = path.join(nested, "renamed-by-the-other-app.gguf"); + yield* h.fs.writeFile(impostor, new Uint8Array(bytes.length)); + yield* h.fs.writeFile(existing, bytes); + + expect(yield* h.store.link([h.model], impostor)).toEqual([]); + expect(yield* h.store.linkedFrom(h.model)).toBeUndefined(); + + expect(yield* h.store.link([h.model], elsewhere)).toEqual([h.model.id]); + expect(yield* h.store.linkedFrom(h.model)).toBe(existing); + expect(yield* h.store.installedPath(h.model)).toBe(h.stale); + expect(h.requests).toHaveLength(0); + // Pointing at T3 Code's own folder must not turn the link into a link to itself. + expect(yield* h.store.link([h.model], h.directory)).toEqual([]); + expect(yield* h.store.installedPath(h.model)).toBe(h.stale); + + yield* h.store.remove(h.model); + expect(yield* h.store.isReady(h.model)).toBe(false); + expect([...(yield* h.fs.readFile(existing))]).toEqual([...bytes]); + }).pipe(Effect.scoped, Effect.provide(dependencies)), +); + +it.effect("installs from a Hugging Face cache copy instead of downloading", () => + Effect.gen(function* () { + const h = yield* harness; + const path = yield* Path.Path; + const home = yield* h.fs.makeTempDirectoryScoped({ prefix: "speech-home-" }); + const snapshot = path.join( + home, + ".cache/huggingface/hub/models--fixture--speech-model/snapshots", + h.model.revision, + ); + yield* h.fs.makeDirectory(snapshot, { recursive: true }); + const cached = path.join(snapshot, h.model.filename); + yield* h.fs.writeFile(cached, bytes); + const store = yield* h.openStore.pipe(Effect.provideService(HostProcess.HomeDirectory, home)); + + expect(yield* store.download(h.model)).toBe(h.stale); + expect(yield* store.linkedFrom(h.model)).toBe(cached); + expect(h.requests).toHaveLength(0); + }).pipe(Effect.scoped, Effect.provide(dependencies)), +); diff --git a/apps/server/src/speech/SpeechModelStore.ts b/apps/server/src/speech/SpeechModelStore.ts index 99f3fe6ca5bb..d12999194df2 100644 --- a/apps/server/src/speech/SpeechModelStore.ts +++ b/apps/server/src/speech/SpeechModelStore.ts @@ -14,7 +14,10 @@ import type { PlatformError } from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as HostProcess from "@t3tools/shared/HostProcess"; + import * as ServerConfig from "../config.ts"; +import { expandHomePath } from "../os-jank.ts"; import type { SpeechModel } from "./model.ts"; type ModelFile = Pick; @@ -44,6 +47,7 @@ export class SpeechModelStore extends Context.Service< readonly isReady: (model: ModelFile) => Effect.Effect; /** The installed file once its SHA-256 has been verified, hashing it on first use. */ readonly installedPath: (model: ModelFile) => Effect.Effect; + /** Links a copy the Hugging Face cache or Handy already holds; fetches only without one. */ readonly download: ( model: ModelFile, progress?: SpeechModelDownloadProgress, @@ -51,6 +55,17 @@ export class SpeechModelStore extends Context.Service< string, SpeechModelDownloadError | PlatformError | HttpClientError.HttpClientError >; + /** + * Installs catalog files already on this machine as symlinks, never copies. + * `source` is a file or a folder to search; returns the ids it installed. + */ + readonly link: ( + models: ReadonlyArray, + source: string, + ) => Effect.Effect, PlatformError>; + /** The outside file a linked model points at. */ + readonly linkedFrom: (model: ModelFile) => Effect.Effect; + /** Removes T3 Code's file or link; a linked file itself is left in place. */ readonly remove: (model: ModelFile) => Effect.Effect; } >()("t3/speech/SpeechModelStore") {} @@ -59,9 +74,14 @@ const DOWNLOAD_ATTEMPTS = 3; const PARTIAL_FILENAME = /\.gguf\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.part$/i; +const LINK_SEARCH_DEPTH = 5; +const LINK_SEARCH_ENTRIES = 5_000; + const make = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const home = yield* HostProcess.HomeDirectory; + const platform = yield* HostProcess.Platform; const http = yield* HttpClient.HttpClient; const random = yield* SecureRandom.SecureRandom; const config = yield* ServerConfig.ServerConfig; @@ -73,6 +93,28 @@ const make = Effect.gen(function* () { } } const modelPath = (model: ModelFile) => path.join(directory, model.filename); + const appDataDirectories = + platform === "darwin" + ? [path.join(home, "Library", "Application Support")] + : platform === "win32" + ? [path.join(home, "AppData", "Roaming")] + : [path.join(home, ".local", "share"), path.join(home, ".config")]; + // Where the Hugging Face cache and Handy keep these same pinned files. + const knownCopies = (model: ModelFile) => [ + path.join( + home, + ".cache", + "huggingface", + "hub", + `models--${model.id.replace("/", "--")}`, + "snapshots", + model.revision, + model.filename, + ), + ...appDataDirectories.map((appData) => + path.join(appData, "com.pais.handy", "models", model.filename), + ), + ]; // Files whose digest failed, by identity, so status polls stop calling them ready. const corrupt = new Map(); @@ -179,12 +221,81 @@ const make = Effect.gen(function* () { return downloaded; }); + const filesUnder = Effect.fn("SpeechModelStore.filesUnder")(function* (source: string) { + const files: Array<{ readonly file: string; readonly size: number }> = []; + const pending = [{ entry: source, depth: LINK_SEARCH_DEPTH }]; + for (let visited = 0; pending.length > 0 && visited < LINK_SEARCH_ENTRIES; visited += 1) { + const { entry, depth } = pending.pop()!; + const info = yield* statFile(entry); + if (info?.type === "File") files.push({ file: entry, size: Number(info.size) }); + if (info?.type !== "Directory" || depth === 0) continue; + for (const name of yield* fs.readDirectory(entry).pipe(Effect.orElseSucceed(() => []))) + pending.push({ entry: path.join(entry, name), depth: depth - 1 }); + } + return files; + }); + + const realPath = (file: string) => fs.realPath(file).pipe(Effect.orElseSucceed(() => undefined)); + + const link: SpeechModelStore["Service"]["link"] = Effect.fn("SpeechModelStore.link")( + function* (models, source) { + const root = path.resolve( + yield* expandHomePath(source.trim()).pipe( + Effect.provideService(Path.Path, path), + Effect.provideService(HostProcess.HomeDirectory, home), + ), + ); + yield* fs.makeDirectory(directory, { recursive: true }); + const linked: string[] = []; + for (const { file, size } of yield* filesUnder(root)) { + for (const model of models) { + if (model.size !== size || linked.includes(model.id)) continue; + const finalPath = modelPath(model); + // Pointing at T3 Code's own model folder must not replace a file with a link to itself. + if ((yield* realPath(file)) === (yield* realPath(finalPath))) continue; + if (yield* verifiedPath(model, finalPath)) continue; + const hashed = yield* expectedFile(model, file); + if (!hashed || !(yield* digestMatches(model, file))) continue; + // Staged then renamed, so a failed link never removes the file already installed. + const staged = `${finalPath}.${yield* random.uuidV4()}.part`; + // Windows grants symlinks only to privileged accounts; a hard link also shares the bytes. + const hardLinked = yield* fs.symlink(file, staged).pipe( + Effect.as(false), + Effect.catch(() => fs.link(file, staged).pipe(Effect.as(true))), + ); + const current = yield* expectedFile(model, staged); + const marker = identity(model, hashed); + if (!current || identity(model, current) !== marker) { + yield* fs.remove(staged, { force: true }); + continue; + } + yield* fs.rename(staged, finalPath); + // A hard link cannot be read back, so its origin is recorded beside it. + yield* ( + hardLinked + ? fs.writeFileString(`${finalPath}.source`, file, { mode: 0o600 }) + : fs.remove(`${finalPath}.source`, { force: true }) + ).pipe(Effect.ignore); + yield* fs + .writeFileString(`${finalPath}.verified`, marker, { mode: 0o600 }) + .pipe(Effect.ignore); + linked.push(model.id); + } + } + return linked; + }, + ); + const download: SpeechModelStore["Service"]["download"] = Effect.fn("SpeechModelStore.download")( function* (model, progress = {}) { yield* Effect.annotateCurrentSpan({ modelId: model.id }); const finalPath = modelPath(model); yield* fs.makeDirectory(directory, { recursive: true }); if (yield* verifiedPath(model, finalPath, progress.onVerificationStart)) return finalPath; + for (const copy of knownCopies(model)) { + const linked = yield* link([model], copy).pipe(Effect.orElseSucceed(() => [])); + if (linked.length > 0) return finalPath; + } const partialPath = `${finalPath}.${yield* random.uuidV4()}.part`; const url = `https://huggingface.co/${model.id}/resolve/${model.revision}/${model.filename}`; return yield* Effect.gen(function* () { @@ -211,6 +322,7 @@ const make = Effect.gen(function* () { if (!complete || !(yield* digestMatches(model, partialPath))) return yield* new SpeechModelDownloadError({ modelId: model.id, reason: "verification" }); yield* fs.rename(partialPath, finalPath); + yield* fs.remove(`${finalPath}.source`, { force: true }).pipe(Effect.ignore); // Rename changes file metadata, so record the verified file's final identity. const info = yield* fs.stat(finalPath); yield* fs @@ -228,6 +340,13 @@ const make = Effect.gen(function* () { ); return SpeechModelStore.of({ + link, + linkedFrom: Effect.fn("SpeechModelStore.linkedFrom")((model) => + fs.readLink(modelPath(model)).pipe( + Effect.catch(() => fs.readFileString(`${modelPath(model)}.source`)), + Effect.orElseSucceed(() => undefined), + ), + ), isReady: Effect.fn("SpeechModelStore.isReady")((model) => expectedFile(model, modelPath(model)).pipe( Effect.map( @@ -243,6 +362,7 @@ const make = Effect.gen(function* () { const file = modelPath(model); yield* fs.remove(file, { force: true }); yield* fs.remove(`${file}.verified`, { force: true }); + yield* fs.remove(`${file}.source`, { force: true }); }), }); }); diff --git a/apps/server/src/speech/SpeechService.test.ts b/apps/server/src/speech/SpeechService.test.ts index 41db47f0376a..8d980f284627 100644 --- a/apps/server/src/speech/SpeechService.test.ts +++ b/apps/server/src/speech/SpeechService.test.ts @@ -103,6 +103,8 @@ const store = Layer.succeed( installedPath: (model) => Effect.sync(() => (readyModels.has(model.id) ? "test.gguf" : undefined)), download, + link: () => Effect.succeed([]), + linkedFrom: () => Effect.undefined, remove: (model) => Effect.sync(() => { readyModels.delete(model.id); diff --git a/apps/server/src/speech/SpeechService.ts b/apps/server/src/speech/SpeechService.ts index c5f0faebe18f..b4ae198b9447 100644 --- a/apps/server/src/speech/SpeechService.ts +++ b/apps/server/src/speech/SpeechService.ts @@ -138,6 +138,8 @@ export class SpeechService extends Context.Service< readonly selectModel: (modelId: string) => Effect.Effect; readonly cancelDownload: (modelId: string) => Effect.Effect; readonly removeModel: (modelId: string) => Effect.Effect; + /** Uses catalog model files already on this machine, from a file or folder path. */ + readonly linkModels: (source: string) => Effect.Effect; readonly prepareModel: Effect.Effect; readonly transcribe: ( pcmBytes: Uint8Array, @@ -467,6 +469,7 @@ const make = Effect.gen(function* () { size: definition.size, supportsStreaming: definition.supportsStreaming, supportsBufferedStreaming: true, + supportsModelLinking: true, supportsTranslation: definition.supportsTranslation, languages: definition.languages, supportsLanguageDetection: definition.supportsLanguageDetection, @@ -489,8 +492,8 @@ const make = Effect.gen(function* () { const models = yield* Effect.forEach( SPEECH_MODELS, (definition) => - store.isReady(definition).pipe( - Effect.map((ready): EnvironmentSpeechModel => { + Effect.all([store.isReady(definition), store.linkedFrom(definition)]).pipe( + Effect.map(([ready, linkedFrom]): EnvironmentSpeechModel => { const operation = downloading?.modelId === definition.id ? downloading : undefined; return { id: definition.id, @@ -514,6 +517,7 @@ const make = Effect.gen(function* () { ? "installed" : "downloadable", ...(operation ? { downloaded: operation.downloaded } : {}), + ...(ready && linkedFrom ? { linkedFrom } : {}), }; }), ), @@ -951,6 +955,21 @@ const make = Effect.gen(function* () { ), ), ), + linkModels: Effect.fn("SpeechService.linkModels")(function* (source) { + yield* requireSupported; + const settings = yield* readSettings("model linking"); + const linked = yield* exclusive( + "model linking", + store + .link(SPEECH_MODELS, source) + .pipe(Effect.mapError((cause) => speechError("model linking", cause))), + ); + const first = linked[0]; + if (first === undefined) return yield* new SpeechModelNotFoundError({ modelId: source }); + if (!(yield* store.isReady(selectedModel(settings)))) + yield* writeSettings("model linking", { speechModelId: first }); + return yield* modelsEffect; + }), updateAcceleration: Effect.fn("SpeechService.updateAcceleration")((acceleration) => writeSettings("acceleration update", { speechAcceleration: acceleration }).pipe( Effect.andThen(freshStatus("acceleration update")), diff --git a/apps/server/src/speech/http.test.ts b/apps/server/src/speech/http.test.ts index f67129be6042..d86f77fbdbd8 100644 --- a/apps/server/src/speech/http.test.ts +++ b/apps/server/src/speech/http.test.ts @@ -80,6 +80,7 @@ effectIt.live("rejects oversized chunked audio without invoking transcription", prepareModel: Effect.void, models: () => Effect.succeed({ models: [] }), downloadModel: () => Effect.succeed({ models: [] }), + linkModels: () => Effect.succeed({ models: [] }), selectModel: () => Effect.succeed({ models: [] }), cancelDownload: () => Effect.succeed({ models: [] }), updateAcceleration: () => Effect.succeed({ supported: false as const, reason: "test" }), @@ -164,7 +165,31 @@ effectIt.effect( HttpApiBuilder.layer(HttpApi.make("environment").add(EnvironmentVoiceHttpApi)).pipe( Layer.provide(speechHttpApiLayer), Layer.provide(principal(AuthOrchestrationOperateScope, AuthSettingsWriteScope)), - Layer.provide(Layer.mock(SpeechService.SpeechService)({})), + Layer.provide( + Layer.mock(SpeechService.SpeechService)({ + models: () => + Effect.succeed({ + models: [ + { + id: "fixture/model", + name: "Fixture", + description: "", + size: 1, + languages: ["en"], + accuracy: 0, + speed: 0, + recommended: false, + supportsStreaming: false, + supportsLanguageDetection: false, + supportsTranslation: false, + active: true, + state: "installed", + linkedFrom: "/home/someone/models/fixture.gguf", + }, + ], + }), + }), + ), Layer.provide(cloud), Layer.provide(dependencies), Layer.provide(HttpServer.layerServices), @@ -228,6 +253,22 @@ effectIt.effect( 422, ); expect(transcribe).toHaveBeenLastCalledWith("openrouter", "acme/transcribe-1"); + // Naming a path on the environment needs filesystem access, not only settings access. + const link = yield* Effect.promise(() => + handler( + new Request("http://localhost/api/voice/models/link", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ path: "/models" }), + }), + context, + ), + ); + expect(link.status).toBe(403); + const listed = yield* Effect.promise(() => + handler(new Request("http://localhost/api/voice/models"), context), + ); + expect(yield* Effect.promise(() => listed.text())).not.toContain("/home/someone"); }).pipe(Effect.scoped), ); @@ -268,6 +309,7 @@ effectIt.effect.each([ prepareModel: Effect.void, models: () => Effect.succeed({ models: [] }), downloadModel: () => Effect.fail(error), + linkModels: () => Effect.fail(error), selectModel: () => Effect.fail(error), cancelDownload: () => Effect.fail(error), updateAcceleration: () => Effect.fail(error), diff --git a/apps/server/src/speech/http.ts b/apps/server/src/speech/http.ts index eb4a7a01b88f..bf91b4c1ef3a 100644 --- a/apps/server/src/speech/http.ts +++ b/apps/server/src/speech/http.ts @@ -1,9 +1,12 @@ import { decodeSpeechPcmRequest } from "@t3tools/shared/speech"; import { + AuthFilesystemReadScope, AuthOrchestrationOperateScope, AuthSettingsWriteScope, type AuthEnvironmentScope, + EnvironmentAuthenticatedPrincipal, EnvironmentHttpApi, + type EnvironmentSpeechModels, EnvironmentVoiceBodyLimit, SPEECH_MAX_OPTIONS_BYTES, } from "@t3tools/contracts"; @@ -53,6 +56,14 @@ const mapSpeechError = (effect: Effect.Effect model) }; +}); + export const speechHttpApiLayer = HttpApiBuilder.group( EnvironmentHttpApi, "voice", @@ -133,35 +144,54 @@ export const speechHttpApiLayer = HttpApiBuilder.group( "models", Effect.fn("environment.voice.models")(function* (args) { yield* guard(args.endpoint.name); - return yield* speech.models(args.query.benchmarks === "1").pipe(mapSpeechError); + return yield* speech + .models(args.query.benchmarks === "1") + .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths)); }), ) .handle( "downloadModel", Effect.fn("environment.voice.downloadModel")(function* (args) { yield* guard(args.endpoint.name, AuthSettingsWriteScope); - return yield* speech.downloadModel(args.payload.modelId).pipe(mapSpeechError); + return yield* speech + .downloadModel(args.payload.modelId) + .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths)); }), ) .handle( "selectModel", Effect.fn("environment.voice.selectModel")(function* (args) { yield* guard(args.endpoint.name, AuthSettingsWriteScope); - return yield* speech.selectModel(args.payload.modelId).pipe(mapSpeechError); + return yield* speech + .selectModel(args.payload.modelId) + .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths)); }), ) .handle( "cancelModelDownload", Effect.fn("environment.voice.cancelModelDownload")(function* (args) { yield* guard(args.endpoint.name, AuthSettingsWriteScope); - return yield* speech.cancelDownload(args.payload.modelId).pipe(mapSpeechError); + return yield* speech + .cancelDownload(args.payload.modelId) + .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths)); }), ) .handle( "removeModel", Effect.fn("environment.voice.removeModel")(function* (args) { yield* guard(args.endpoint.name, AuthSettingsWriteScope); - return yield* speech.removeModel(args.payload.modelId).pipe(mapSpeechError); + return yield* speech + .removeModel(args.payload.modelId) + .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths)); + }), + ) + .handle( + "linkModels", + Effect.fn("environment.voice.linkModels")(function* (args) { + yield* guard(args.endpoint.name, AuthSettingsWriteScope); + // The request names a path on this machine and the result reveals what is there. + yield* requireEnvironmentScope(AuthFilesystemReadScope); + return yield* speech.linkModels(args.payload.path).pipe(mapSpeechError); }), ) .handle( diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.tsx index 495abdefb6b6..e2137cf24e13 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.tsx @@ -3,6 +3,7 @@ import { downloadEnvironmentSpeechModel, getEnvironmentSpeechModels, getEnvironmentSpeechStatus, + linkEnvironmentSpeechModels, removeEnvironmentSpeechModel, selectEnvironmentSpeechModel, updateEnvironmentSpeechAcceleration, @@ -11,6 +12,7 @@ import { import type { PreparedConnection } from "@t3tools/client-runtime/connection"; import { openRouterIcon } from "@t3tools/client-runtime/provider-clients"; import { + AuthFilesystemReadScope, AuthSettingsWriteScope, CLOUD_SPEECH_LABELS, CloudSpeechProvider, @@ -42,6 +44,7 @@ import { StarIcon, SlidersHorizontalIcon, Trash2Icon, + UnlinkIcon, XIcon, } from "lucide-react"; import { useEffect, useRef, useState, type ReactNode } from "react"; @@ -215,6 +218,11 @@ function ModelCard(props: ModelCardProps) { ) : null}

    {model.description}

    + {model.linkedFrom ? ( +

    + Using your file at {model.linkedFrom} +

    + ) : null} - + {model.linkedFrom ? ( + + ) : ( + + )} ) : null}
    @@ -779,6 +795,8 @@ function SpeechModelBrowser(props: { const [search, setSearch] = useState(""); const [sort, setSort] = useState("recommended"); const [downloadedOnly, setDownloadedOnly] = useState(false); + const [existingPath, setExistingPath] = useState(""); + const canReadFiles = useEnvironmentScope(prepared.environmentId, AuthFilesystemReadScope); const [languageSearch, setLanguageSearch] = useState(""); const [selection, setSelection] = useState(null); const [preferred] = useState(preferredSpeechLanguages); @@ -981,6 +999,38 @@ function SpeechModelBrowser(props: { ); })}
    + {status.supportsModelLinking && canReadFiles ? ( +
    { + event.preventDefault(); + void run("Could not use a model from that path", async () => { + await runEnvironmentSpeech( + linkEnvironmentSpeechModels(prepared, existingPath), + ); + setExistingPath(""); + }); + }} + > +
    + setExistingPath(e.target.value)} + /> +
    + +
    + ) : null}
    diff --git a/docs/internals/voice-input.md b/docs/internals/voice-input.md index e381debdb792..00964ab4ae33 100644 --- a/docs/internals/voice-input.md +++ b/docs/internals/voice-input.md @@ -63,6 +63,9 @@ at a time. Batch uploads carry their options in the body framing defined in [shared/speech.ts](../../packages/shared/src/speech.ts); streaming sends them in the socket's first command. Model files and the selected model, hardware placement, and unload timeout are environment state in server settings. +A model file from another app is installed as a symlink only after its SHA-256 +matches a catalog entry, so the store never loads a file the catalog does not pin +and removing a model never deletes a file T3 Code did not download. The Silero silence detector is optional. If its download fails, recordings use raw audio during the retry cooldown so a detector outage cannot block dictation. diff --git a/docs/user/voice-input.md b/docs/user/voice-input.md index 7e5c36fa4d1e..0672ae23ea23 100644 --- a/docs/user/voice-input.md +++ b/docs/user/voice-input.md @@ -54,6 +54,16 @@ isn’t already selected. **Test model** lets you try it without sending a messa If you use the composer microphone before a model is installed, it offers to download one. The recommendation uses your Voice language, or your system’s preferred languages with **Auto-detect**. +If another app already downloaded one of these models, you don’t need a second copy. +**Download** first looks in Handy’s model folder and the Hugging Face cache on that +environment and uses a copy it finds there instead of downloading. For a copy anywhere +else, on web or desktop, paste the path of the model file or its folder under the model +list and choose **Use existing**. The path is on the environment +that transcribes, not on the device you are using. T3 Code checks that the file is exactly a +model from its list and then uses it in place. Removing the model in T3 Code leaves your file +alone; if the other app deletes it, download or link the model again. Files in another +format, such as Core ML, ONNX, or MLX builds of the same model, can’t be used. + Select the languages you dictate in to compare models that support all of them. Accuracy shows how often the model got words or characters wrong in each language; speed is the time to transcribe 30 seconds on a reference GPU. Choose diff --git a/packages/client-runtime/src/voice-input/environment.ts b/packages/client-runtime/src/voice-input/environment.ts index 52fa5a0d1fe5..a8ea541f7513 100644 --- a/packages/client-runtime/src/voice-input/environment.ts +++ b/packages/client-runtime/src/voice-input/environment.ts @@ -292,6 +292,17 @@ export const updateEnvironmentSpeechModelUnloadTimeout = ( client.updateModelUnloadTimeout({ headers, payload: { timeout } }), }); +export const linkEnvironmentSpeechModels = (prepared: PreparedConnection, path: string) => + request({ + group: "voice", + prepared, + method: "POST", + path: (urls) => urls.linkModels(), + // Hashing several multi-gigabyte files takes longer than an ordinary request. + timeoutMs: INFERENCE_OR_DOWNLOAD_TIMEOUT_MS, + run: ({ client, headers }) => client.linkModels({ headers, payload: { path } }), + }); + export const removeEnvironmentSpeechModel = (prepared: PreparedConnection, modelId: string) => request({ group: "voice", diff --git a/packages/client-runtime/src/voice-input/index.ts b/packages/client-runtime/src/voice-input/index.ts index 5843267800f6..5283d64eb0dc 100644 --- a/packages/client-runtime/src/voice-input/index.ts +++ b/packages/client-runtime/src/voice-input/index.ts @@ -21,6 +21,7 @@ export { transcribeCloudPcm, getEnvironmentSpeechStatus, getEnvironmentSpeechStreamUrl, + linkEnvironmentSpeechModels, postProcessEnvironmentTranscript, removeEnvironmentSpeechModel, selectEnvironmentSpeechModel, diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index db0bd2daae61..4bbae77fb922 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -56,6 +56,7 @@ import { CloudSpeechModels, CloudSpeechProvider, EnvironmentSpeechAccelerationRequest, + EnvironmentSpeechModelLinkRequest, EnvironmentSpeechModelRequest, EnvironmentSpeechModels, EnvironmentSpeechModelUnloadTimeoutRequest, @@ -888,6 +889,14 @@ export class EnvironmentVoiceHttpApi extends HttpApiGroup.make("voice") error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError], }).middleware(EnvironmentAuthenticatedAuth), ) + .add( + HttpApiEndpoint.post("linkModels", "/api/voice/models/link", { + headers: OptionalBearerHeaders, + payload: EnvironmentSpeechModelLinkRequest, + success: EnvironmentSpeechModels, + error: [...EnvironmentScopedOperationErrors, EnvironmentRequestInvalidError], + }).middleware(EnvironmentAuthenticatedAuth), + ) .add( HttpApiEndpoint.post("updateAcceleration", "/api/voice/acceleration", { headers: OptionalBearerHeaders, diff --git a/packages/contracts/src/speech.ts b/packages/contracts/src/speech.ts index ac87096a24cc..ff3362f67fc0 100644 --- a/packages/contracts/src/speech.ts +++ b/packages/contracts/src/speech.ts @@ -194,6 +194,8 @@ export const EnvironmentSpeechModel = Schema.Struct({ active: Schema.Boolean, state: EnvironmentSpeechModelState, downloaded: Schema.optionalKey(Schema.Finite), + /** The file outside T3 Code's model folder this model is used from. */ + linkedFrom: Schema.optionalKey(Schema.String), }); export type EnvironmentSpeechModel = typeof EnvironmentSpeechModel.Type; @@ -203,6 +205,10 @@ export const EnvironmentSpeechModels = Schema.Struct({ export type EnvironmentSpeechModels = typeof EnvironmentSpeechModels.Type; export const EnvironmentSpeechModelRequest = Schema.Struct({ modelId: SpeechModelId }); +/** A model file, or a folder to search for them, on the environment's own disk. */ +export const EnvironmentSpeechModelLinkRequest = Schema.Struct({ + path: TrimmedNonEmptyString.check(Schema.isMaxLength(4096)), +}); export const EnvironmentSpeechState = Schema.Literals(["missing-model", "ready", "transcribing"]); export type EnvironmentSpeechState = typeof EnvironmentSpeechState.Type; @@ -215,6 +221,7 @@ const SupportedSpeechStatus = Schema.Struct({ size: Schema.Finite, supportsStreaming: Schema.Boolean, supportsBufferedStreaming: Schema.optionalKey(Schema.Boolean), + supportsModelLinking: Schema.optionalKey(Schema.Boolean), supportsTranslation: Schema.Boolean, languages: Schema.optionalKey(Schema.Array(Schema.String)), supportsLanguageDetection: Schema.optionalKey(Schema.Boolean), From 1d80047048c29c9ce91c1509200d07788aaad1a8 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 10 Nov 2026 18:23:05 -0600 Subject: [PATCH 051/170] fix(web): scroll project picker to top on first result (#34113) --- apps/web/src/components/CommandPalette.tsx | 7 ++++++- apps/web/src/components/CommandPaletteResults.tsx | 10 +++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index a73322fc6511..a6dd4fe1d40c 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -2650,6 +2650,7 @@ function OpenCommandPaletteDialog(props: { scrollCommandPaletteRowIntoView( resultListRef.current, resultRows.rowIndexByItemIndex[0] ?? 0, + true, ); return; } @@ -2921,7 +2922,11 @@ function OpenCommandPaletteDialog(props: { setHighlightedItemValue(typeof value === "string" ? value : null); const rowIndex = resultRows.rowIndexByItemIndex[eventDetails.index]; if (eventDetails.reason === "keyboard" && rowIndex !== undefined) { - scrollCommandPaletteRowIntoView(resultListRef.current, rowIndex); + scrollCommandPaletteRowIntoView( + resultListRef.current, + rowIndex, + eventDetails.index === 0, + ); } }} onValueChange={(nextQuery, { event }) => handleQueryChange(nextQuery, event.target)} diff --git a/apps/web/src/components/CommandPaletteResults.tsx b/apps/web/src/components/CommandPaletteResults.tsx index f337f555382b..864c190b89c5 100644 --- a/apps/web/src/components/CommandPaletteResults.tsx +++ b/apps/web/src/components/CommandPaletteResults.tsx @@ -78,7 +78,15 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) { ); } -export function scrollCommandPaletteRowIntoView(list: LegendListRef | null, rowIndex: number) { +export function scrollCommandPaletteRowIntoView( + list: LegendListRef | null, + rowIndex: number, + isFirstItem: boolean, +) { + if (isFirstItem) { + void list?.scrollToOffset({ offset: 0, animated: false }); + return; + } void list?.scrollIndexIntoView({ index: rowIndex, animated: false, From 3a8c250cb0c8056f2f563091fd412fe5db809fa1 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 10 Nov 2026 18:30:11 -0600 Subject: [PATCH 052/170] feat(opencode): track native image job outcomes and previews (#34089) OpenCode image-generation tool success acknowledges a launched background job. Keep that job pending until its native outcome arrives, retain the outcome on the original tool item, and serve size-limited image previews through existing rendering and remote file paths. Recover outcomes after stream loss, allow later exact-path notices to add previews, and clear descendant image tasks from parent rosters on completion or transport failure. Keep older-server fallback and the pinned SDK. Validation: check:changed passed with 147 tests; required CI passed and review findings were addressed on 62addc83319ad73fd25f52fbeb3cbcf06504a093. Client screenshots use controlled fixtures; no paid image generation was used. Model: GPT 6.1 Sol. Harness: Codex in T3 Code. --- .../Adapters/OpenCode2AdapterV2.test.ts | 422 +++++++++++++++++- .../Adapters/OpenCode2AdapterV2.testkit.ts | 9 + .../src/server/v2/OpenCode2Client.test.ts | 81 ++++ .../src/server/v2/OpenCode2Client.ts | 82 ++++ .../src/server/v2/adapter.ts | 211 ++++++++- 5 files changed, 795 insertions(+), 10 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index aae63afa9962..b07bb23c85eb 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -317,7 +317,7 @@ const colorForm = { const resumed = ( entries: ReadonlyArray, options?: { - readonly version?: "2.2.5"; + readonly version?: "2.2.5" | "2.2.6"; readonly goal?: OrchestrationV2ProviderThread["goal"]; readonly external?: boolean; readonly supervised?: boolean; @@ -326,6 +326,7 @@ const resumed = ( readonly resolveExtractedTextPath?: (path: string) => Effect.Effect; readonly fileSystem?: FileSystem.FileSystem; readonly onPrompt?: (input: unknown) => void; + readonly borrowers?: { current: number }; }, ) => Effect.gen(function* () { @@ -335,7 +336,7 @@ const resumed = ( out("session.get", { sessionID: SESSION }), replyData("session.get", sessionInfo()), ...noOpenRequests, - ...(options?.version === "2.2.5" + ...(options?.version !== undefined ? [out("rpc.call", ""), reply("rpc.call", { output: null })] : []), ...withInstructions([ @@ -352,6 +353,7 @@ const resumed = ( ], { ...(options?.version === undefined ? {} : { version: options.version }), + ...(options?.borrowers === undefined ? {} : { borrowers: options.borrowers }), ...(options?.fileSystem === undefined ? {} : { fileSystem: options.fileSystem }), ...(options?.onPrompt === undefined ? {} : { onPrompt: options.onPrompt }), ...(options?.external === undefined ? {} : { external: options.external }), @@ -2891,6 +2893,422 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect.each(["completed", "error", "cancelled"] as const)( + "retains native image job %s after its launch returns", + (outcome) => + Effect.gen(function* () { + const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-image" }; + const notice = (sessionID: string) => + event("session.inbox.enqueued", { + sessionID, + inboxID: `msg_image_${sessionID}`, + item: { + type: "synthetic", + delivery: "steer", + payload: { + description: "Image generation", + text: + outcome === "completed" + ? "Image outcome retained. Saved image: /work/opencode2/image.png (test/image)." + : "Image outcome retained", + metadata: { + source: "experimental_image_generate", + jobID: "image_test", + state: outcome, + path: "/work/opencode2/image", + }, + }, + }, + }); + const { runtime, thread } = yield* resumed( + [ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.tool.input.started", { ...tool, name: "experimental_image_generate" }), + event("session.tool.called", { ...tool, input: { prompt: "A tree" }, executed: false }), + event( + "session.tool.success", + { + ...tool, + content: [{ type: "text", text: "Job launched" }], + metadata: { + jobID: "image_test", + path: "/work/opencode2/image", + model: "test/image", + }, + executed: false, + }, + undefined, + 2, + ), + event("session.execution.succeeded", { sessionID: SESSION }), + notice("ses_other"), + notice(SESSION), + ...(outcome === "completed" + ? [ + out("image.read", { + path: "/api/fs/read/image.png", + "location[directory]": WORK, + }), + reply("image.read", { imageBase64: "iVBORw0KGgo=" }), + ] + : []), + ], + { external: true }, + ); + let launched = false; + const events = yield* runtime.events.pipe( + Stream.takeUntil((e) => { + if (e.type !== "provider_thread.updated") return false; + if ( + e.providerThread.pendingBackgroundTasks?.some((task) => task.taskId === "image_test") + ) + launched = true; + return launched && e.pendingBackgroundWork === false; + }), + Stream.runCollect, + Effect.forkScoped, + ); + yield* runtime.startTurn(turnInput(thread)); + const collected = yield* Fiber.join(events); + const items = collected.flatMap((e) => + e.type === "turn_item.updated" && e.turnItem.nativeItemRef?.nativeId === "call-image" + ? [e.turnItem] + : [], + ); + assert.deepEqual( + items.map((item) => item.status), + [ + "running", + "running", + "running", + outcome === "error" ? "failed" : outcome === "cancelled" ? "interrupted" : "completed", + ], + ); + assert.include(JSON.stringify(items.at(-1)), "Image outcome retained"); + if (outcome === "completed") { + const item = items.at(-1); + assert.deepEqual(item?.type === "dynamic_tool" ? toolOutputImages(item.output) : [], [ + { mimeType: "image/png", data: "iVBORw0KGgo=" }, + ]); + } + const rosters = collected.flatMap((e) => + e.type === "provider_thread.updated" + ? [e.providerThread.pendingBackgroundTasks ?? []] + : [], + ); + assert.isTrue(rosters.some((tasks) => tasks.some((task) => task.taskId === "image_test"))); + assert.deepEqual(rosters.at(-1), []); + }).pipe(Effect.scoped), + ); + + it.effect.each(["history", "list", "late-preview"] as const)( + "recovers native image job outcomes from %s after reconnect", + (source) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed( + [ + out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "" }), + promptAccepted, + ...(() => { + const frames: Array = reconnected({}, "succeeded", { + content: [ + { + type: "tool", + id: "call-image-gap", + name: "experimental_image_generate", + executed: false, + state: { + status: "completed", + input: { prompt: "A tree" }, + content: [{ type: "text", text: "Job launched" }], + metadata: { jobID: "image_gap", path: "/tmp/image", model: "test/image" }, + }, + time: { created: 2, ran: 2, completed: 2 }, + }, + ], + }); + if (source !== "history") + frames.splice(2, 0, out("rpc.call", ""), reply("rpc.call", { output: null })); + return frames; + })(), + out("message.list", { sessionID: SESSION, type: "synthetic", limit: "100" }), + reply("message.list", { + data: + source !== "history" + ? [] + : [ + { + id: "msg_image_gap", + time: { created: 3 }, + type: "synthetic", + text: "Recovered image failure", + description: "Image generation", + metadata: { + source: "experimental_image_generate", + jobID: "image_gap", + state: "error", + path: "/tmp/image", + }, + }, + ], + cursor: {}, + }), + ...(source !== "history" + ? [ + out("imageJobs", { sessionID: SESSION, kind: "image" }), + reply("imageJobs", { + data: [ + { + kind: "image", + id: "image_gap", + sessionID: SESSION, + status: source === "late-preview" ? "completed" : "error", + path: "/tmp/image", + model: "test/image", + time: { started: 2, completed: 3 }, + }, + ], + }), + ] + : []), + ...(source === "late-preview" + ? [ + event("session.inbox.enqueued", { + sessionID: SESSION, + inboxID: "msg_image_late", + item: { + type: "synthetic", + delivery: "steer", + payload: { + description: "Image generation", + text: "Image request finished. Saved image: /tmp/image.png (test/image).", + metadata: { + source: "experimental_image_generate", + jobID: "image_gap", + state: "completed", + path: "/tmp/image", + }, + }, + }, + }), + out("image.read", { + path: "/api/fs/read/image.png", + "location[directory]": "/tmp", + }), + reply("image.read", { imageBase64: "iVBORw0KGgo=" }), + ] + : []), + ], + { ...(source !== "history" ? { version: "2.2.6" as const } : {}), external: true }, + ); + const events = yield* runtime.events.pipe( + Stream.takeUntil( + (e) => + e.type === "turn_item.updated" && + e.turnItem.nativeItemRef?.nativeId === "call-image-gap" && + (source === "late-preview" + ? e.turnItem.type === "dynamic_tool" && + toolOutputImages(e.turnItem.output).length > 0 + : e.turnItem.status === "failed"), + ), + Stream.runCollect, + Effect.forkScoped, + ); + yield* runtime.startTurn(turnInput(thread)); + const collected = yield* Fiber.join(events); + assert.include( + JSON.stringify(collected.at(-1)), + source === "late-preview" + ? "Saved image: /tmp/image.png" + : source !== "history" + ? "Image generation error" + : "Recovered image failure", + ); + assert.isTrue( + collected.some( + (e) => + e.type === "provider_thread.updated" && + e.providerThread.pendingBackgroundTasks?.some((task) => task.taskId === "image_gap"), + ), + ); + }).pipe(Effect.scoped), + ); + + it.effect("settles a recovered image outcome when preview I/O is interrupted", () => + Effect.gen(function* () { + const reading = yield* Deferred.make(); + const interrupted = yield* Deferred.make(); + const fs = yield* FileSystem.FileSystem; + const { runtime, thread } = yield* resumed( + [ + out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "" }), + promptAccepted, + ...reconnected({}, "succeeded", { + content: [ + { + type: "tool", + id: "call-image-slow", + name: "experimental_image_generate", + executed: false, + state: { + status: "completed", + input: { prompt: "A tree" }, + content: [{ type: "text", text: "Launched" }], + metadata: { jobID: "image_slow", path: "/tmp/image", model: "test/image" }, + }, + time: { created: 2, ran: 2, completed: 2 }, + }, + ], + }), + out("message.list", { sessionID: SESSION, type: "synthetic", limit: "100" }), + reply("message.list", { + data: [ + { + id: "msg_image_slow", + type: "synthetic", + time: { created: 3 }, + text: "Image request finished. Saved image: /tmp/image.png (test/image).", + description: "Image generation", + metadata: { + source: "experimental_image_generate", + jobID: "image_slow", + state: "completed", + path: "/tmp/image", + }, + }, + ], + cursor: {}, + }), + event("session.model.selected", { + sessionID: SESSION, + model: { providerID: "opencode", id: "big-pickle", variant: "recovery-observed" }, + }), + ], + { + fileSystem: { + ...fs, + stat: (path) => + path === "/tmp/image.png" + ? Deferred.succeed(reading, undefined).pipe( + Effect.andThen(Effect.never), + Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)), + ) + : fs.stat(path), + }, + }, + ); + const events = yield* runtime.events.pipe( + Stream.takeUntil( + (e) => + e.type === "provider_thread.updated" && + e.providerThread.nativeMetadata?.modelSelection?.options?.some( + (option) => option.value === "recovery-observed", + ) === true, + ), + Stream.runCollect, + Effect.forkScoped, + ); + yield* runtime.startTurn(turnInput(thread)); + yield* Deferred.await(reading); + yield* TestClock.adjust("5 seconds"); + yield* Deferred.await(interrupted); + const collected = yield* Fiber.join(events); + assert.isTrue( + collected.some( + (e) => + e.type === "turn_item.updated" && + e.turnItem.nativeItemRef?.nativeId === "call-image-slow" && + e.turnItem.status === "completed", + ), + ); + assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread)); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect.each(["root", "child"] as const)( + "settles %s native image tasks when reconnect attempts fail", + (owner) => + Effect.gen(function* () { + const attempts = yield* Effect.forEach([0, 1, 2, 3, 4], () => Deferred.make()); + let count = 0; + let failures = 0; + const borrowers = { + get current() { + return count; + }, + set current(next: number) { + if (next < count && count === 2) { + const attempt = attempts[failures++]; + if (attempt !== undefined) Deferred.doneUnsafe(attempt, Effect.void); + } + count = next; + }, + }; + const tool = { + sessionID: owner === "root" ? SESSION : CHILD, + assistantMessageID: "msg_assistant", + id: "call-image-lost", + }; + const { runtime, thread } = yield* resumed( + [ + ...(owner === "root" + ? [out("session.prompt", { sessionID: SESSION, text: "" }), promptAccepted] + : [ + ...backgroundLaunch(CHILD), + event("session.execution.started", { sessionID: CHILD }), + ]), + event("session.tool.input.started", { ...tool, name: "experimental_image_generate" }), + event( + "session.tool.success", + { + ...tool, + content: [{ type: "text", text: "Launched" }], + metadata: { jobID: "image_lost", path: "/tmp/image", model: "test/image" }, + executed: false, + }, + undefined, + 2, + ), + ...(owner === "child" + ? [event("session.execution.succeeded", { sessionID: CHILD })] + : []), + event("session.execution.succeeded", { sessionID: SESSION }), + { type: "runtime_exit", status: "success" }, + ], + { borrowers }, + ); + const events = yield* runtime.events.pipe(Stream.runCollect, Effect.forkScoped); + yield* runtime.startTurn(withLineage(thread)); + yield* Deferred.await(attempts[0]!); + for (const attempt of attempts.slice(1)) { + yield* TestClock.adjust("2 seconds"); + yield* Deferred.await(attempt); + } + const collected = yield* Fiber.join(events); + assert.isFalse(yield* runtime.hasPendingBackgroundWorkForThread!(thread)); + assert.isTrue( + collected.some( + (e) => + e.type === "turn_item.updated" && + e.turnItem.nativeItemRef?.nativeId === + (owner === "root" ? tool.id : `${CHILD}:${tool.id}`) && + e.turnItem.status === "failed", + ), + ); + const rootSnapshots = collected.flatMap((e) => + e.type === "provider_thread.updated" && e.providerThread.id === thread.id ? [e] : [], + ); + assert.isFalse(rootSnapshots.at(-1)?.pendingBackgroundWork); + assert.deepEqual(rootSnapshots.at(-1)?.providerThread.pendingBackgroundTasks, []); + assert.isTrue( + rootSnapshots.some((e) => + e.providerThread.pendingBackgroundTasks?.some((task) => task.taskId === "image_lost"), + ), + ); + }).pipe(Effect.scoped), + ); + it.effect("projects successful native todo updates into one checklist", () => Effect.gen(function* () { const updates = [ diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts index e4ad66e76539..2714b3a360d1 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts @@ -54,6 +54,10 @@ const operationOf = ( query: Record, body: unknown, ) => { + if (method === "GET" && path === "/api/experimental/job") + return { type: "imageJobs", input: query }; + if (method === "GET" && path.startsWith("/api/fs/read/")) + return { type: "image.read", input: { path, ...query } }; const rpc = /^\/api\/rpc\/([^/]+)\/([^/]+)$/.exec(path); if (method === "POST" && rpc !== null) return { @@ -176,6 +180,11 @@ const replayHttpClient = ( } // Recorded responses are the raw HTTP bodies; `null` is an empty 204. const body = await controller.response(operation.type); + if (typeof body === "object" && body !== null && "imageBase64" in body) { + return new Response(Buffer.from(String(body.imageBase64), "base64"), { + headers: { "content-type": "image/png" }, + }); + } if (body === "") return new Promise(() => {}); if (typeof body === "object" && body !== null && "status" in body && "body" in body) { return new Response(encodeJson(body.body), { diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts index 5ce763e024b8..30d00390769d 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.test.ts @@ -8,6 +8,7 @@ import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; +import * as UrlParams from "effect/http/UrlParams"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientResponse from "effect/http/HttpClientResponse"; import { describe } from "vite-plus/test"; @@ -167,3 +168,83 @@ describe("OpenCode2Client message history", () => { }), ); }); + +describe("OpenCode2Client native image jobs", () => { + it.effect.each([ + { path: "/work/image.png", location: "/work" }, + { path: "/tmp/images/session/image.png", location: "/tmp/images/session" }, + ])("reads remote image $path through its native filesystem location", ({ path, location }) => + Effect.gen(function* () { + const transport = HttpClient.make((request) => + Effect.sync(() => { + assert.strictEqual(request.url, "http://remote.test/api/fs/read/image.png"); + assert.deepEqual(UrlParams.toRecord(request.urlParams), { + "location[directory]": location, + }); + return HttpClientResponse.fromWeb( + request, + new Response(Buffer.from("iVBORw0KGgo=", "base64")), + ); + }), + ); + const service = yield* OpenCode2Client.make.pipe( + Effect.provideService(HttpClient.HttpClient, transport), + ); + const api = yield* service.connect({ baseUrl: "http://remote.test", password: "secret" }); + assert.deepEqual(yield* api.readImage(path, "/work"), { + uri: "data:image/png;base64,iVBORw0KGgo=", + mime: "image/png", + }); + }), + ); + + it.effect("rejects remote previews above the shared image limit", () => + Effect.gen(function* () { + const transport = HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(new Uint8Array(11 * 1024 * 1024))), + ), + ); + const service = yield* OpenCode2Client.make.pipe( + Effect.provideService(HttpClient.HttpClient, transport), + ); + const api = yield* service.connect({ baseUrl: "http://remote.test", password: "secret" }); + const result = yield* api.readImage("/work/image.png", "/work").pipe(Effect.result); + assert.equal(result._tag, "Failure"); + }), + ); + + it.effect("reads scoped image jobs without accepting other sessions or job kinds", () => + Effect.gen(function* () { + const job = { + kind: "image", + id: "image_test", + sessionID: "ses_owner", + status: "running", + path: "/work/image", + model: "test/image", + } as const; + const transport = HttpClient.make((request) => + Effect.sync(() => { + assert.strictEqual(request.headers.authorization, utf8Basic("secret")); + return HttpClientResponse.fromWeb( + request, + Response.json({ + data: [ + job, + { ...job, sessionID: "ses_other" }, + { ...job, kind: "shell" }, + { ...job, status: "future" }, + ], + }), + ); + }), + ); + const service = yield* OpenCode2Client.make.pipe( + Effect.provideService(HttpClient.HttpClient, transport), + ); + const api = yield* service.connect({ baseUrl: "http://remote.test", password: "secret" }); + assert.deepEqual(yield* api.imageJobs("ses_owner"), [job]); + }), + ); +}); diff --git a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts index 71fb1d70ce7d..c3725156f584 100644 --- a/packages/provider-opencode/src/server/v2/OpenCode2Client.ts +++ b/packages/provider-opencode/src/server/v2/OpenCode2Client.ts @@ -1,3 +1,5 @@ +import * as Path from "effect/Path"; +import { PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts"; import { OpenCode, type OpenCodeClient } from "@opencode/client/effect"; import { OpenCodeEvent } from "@opencode/protocol/groups/event"; import * as Context from "effect/Context"; @@ -50,9 +52,43 @@ export type OpenCode2StreamEvent = | OpenCode2UnreadableTerminal | OpenCode2UnreadableStart; +export class OpenCode2ImageError extends Schema.TaggedError()( + "OpenCode2ImageError", + { cause: Schema.Defect() }, +) {} + +const IMAGE_MIME: Readonly> = { + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".webp": "image/webp", + ".gif": "image/gif", +}; +export const imagePreviewMime = (extension: string) => IMAGE_MIME[extension.toLowerCase()]; + +const NativeImageJob = Schema.Struct({ + kind: Schema.Literal("image"), + id: Schema.String, + sessionID: Schema.String, + status: Schema.Literals(["running", "completed", "error", "cancelled"]), + path: Schema.String, + model: Schema.String, +}); +const decodeJobs = Schema.decodeUnknownEffect( + Schema.Struct({ data: Schema.Array(Schema.Unknown) }), +); +const decodeImageJob = Schema.decodeUnknownOption(NativeImageJob); + /** events resolves on subscription acceptance; subscribe before work because the stream is volatile. */ export interface OpenCode2Api { readonly client: OpenCodeClient; + readonly imageJobs: ( + sessionID: string, + ) => Effect.Effect, OpenCode2ImageError>; + readonly readImage: ( + path: string, + directory: string, + ) => Effect.Effect<{ uri: string; mime: string }, OpenCode2ImageError>; readonly events: Effect.Effect< Stream.Stream< OpenCode2StreamEvent, @@ -202,6 +238,7 @@ const fillCompactionRecents = HttpClient.transformResponse( /** @public */ export const make = Effect.gen(function* () { const httpClient = yield* HttpClient.HttpClient; + const paths = yield* Path.Path.pipe(Effect.provide(Path.layer)); return OpenCode2Client.of({ connect: Effect.fn("OpenCode2Client.connect")(function ({ baseUrl, password }) { const authenticated = HttpClient.mapRequest( @@ -212,6 +249,51 @@ export const make = Effect.gen(function* () { Effect.provideService(HttpClient.HttpClient, fillCompactionRecents(authenticated)), Effect.map((client) => ({ client, + imageJobs: (sessionID: string) => + authenticated + .get(`${baseUrl}/api/experimental/job`, { + urlParams: { sessionID, kind: "image" }, + }) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => response.json), + Effect.flatMap(decodeJobs), + Effect.map((page) => + page.data.flatMap((item) => { + const job = decodeImageJob(item); + return Option.isSome(job) && job.value.sessionID === sessionID + ? [job.value] + : []; + }), + ), + Effect.mapError((cause) => new OpenCode2ImageError({ cause })), + ), + readImage: Effect.fn("OpenCode2Client.readImage")( + function* (path: string, directory: string) { + const mime = imagePreviewMime(paths.extname(path)); + if (mime === undefined) + return yield* new OpenCode2ImageError({ cause: "Unsupported image format" }); + const relative = paths.relative(directory, path); + // OpenCode confines reads to the requested location, including its own temp images. + const outside = + relative === ".." || + relative.startsWith(`..${paths.sep}`) || + paths.isAbsolute(relative); + const location = outside ? paths.dirname(path) : directory; + const file = outside ? paths.basename(path) : relative; + const response = yield* authenticated + .get(`${baseUrl}/api/fs/read/${encodeURIComponent(file)}`, { + urlParams: { "location[directory]": location }, + }) + .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + const bytes = yield* response.arrayBuffer; + if (bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) + return yield* new OpenCode2ImageError({ cause: "Image exceeds preview limit" }); + return { uri: `data:${mime};base64,${Buffer.from(bytes).toString("base64")}`, mime }; + }, + Effect.timeout("10 seconds"), + Effect.mapError((cause) => new OpenCode2ImageError({ cause })), + ), events: readEvents.pipe( Effect.provideService( HttpClient.HttpClient, diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index bbd70cc108cd..19673f2597fe 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -1,3 +1,5 @@ +import * as Path from "effect/Path"; +import * as Option from "effect/Option"; import * as NodeURL from "node:url"; import { @@ -15,6 +17,7 @@ import { } from "@opencode/client/effect"; import { Mcp } from "@opencode/schema/mcp"; import { + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, isOrchestrationV2WorkActive, parseGoalCommand, type ChatAttachment, @@ -304,6 +307,18 @@ interface ThreadState { readonly sessionId: string; providerThread: OrchestrationV2ProviderThread; publishedBackgroundWork?: boolean; + readonly imageJobs: Map< + string, + { + readonly turn: ActiveTurn; + readonly toolId: string; + readonly tool: { readonly name: string; input: Record }; + previewed: boolean; + readonly path: string; + readonly model: string; + status: "running" | "completed" | "error" | "cancelled"; + } + >; goalRevision: number; goalFresh: boolean; goalRefreshing: boolean; @@ -529,8 +544,11 @@ const sessionIdOf = (providerThread: OrchestrationV2ProviderThread) => { const textOf = (content: ReadonlyArray<{ readonly type: string; readonly text?: string }>) => content.flatMap((part) => (part.type === "text" && part.text ? [part.text] : [])).join("\n"); -const stringField = (record: Readonly> | undefined, key: string) => { - const value = record?.[key]; +const stringField = (record: unknown, key: string) => { + const value = + typeof record === "object" && record !== null && key in record + ? Reflect.get(record, key) + : undefined; return typeof value === "string" && value.trim().length > 0 ? value : undefined; }; @@ -698,6 +716,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const host = yield* ProviderHost.ProviderHost; const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const fileSystem = yield* FileSystem.FileSystem; + const paths = yield* Path.Path; const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests; const crypto = yield* Digest.Digest; const driver = OPENCODE_PROVIDER; @@ -794,6 +813,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ): ThreadState => ({ sessionId, providerThread, + imageJobs: new Map(), goalRevision: 0, goalFresh: false, goalRefreshing: false, @@ -870,6 +890,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }; const owesWork = (state: ThreadState) => + [...state.imageJobs.values()].some((job) => job.status === "running") || state.wakes.length > 0 || state.reports.size > 0 || (state.subagent !== undefined && busy.has(state.sessionId)) || @@ -1161,6 +1182,31 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (projected) return; } } + if (tool.name === "experimental_image_generate" && status === "completed") { + const jobID = stringField(result?.metadata, "jobID"); + const path = stringField(result?.metadata, "path"); + const model = stringField(result?.metadata, "model"); + if (jobID !== undefined && path !== undefined && model !== undefined) { + // Tool success acknowledges launch, not the background image's outcome. + if ( + state.imageJobs.get(jobID)?.status !== undefined && + state.imageJobs.get(jobID)?.status !== "running" + ) + return; + if (!state.imageJobs.has(jobID)) + state.imageJobs.set(jobID, { + turn, + toolId: id, + tool, + previewed: false, + path, + model, + status: "running", + }); + status = "running"; + yield* syncRosterAncestors(state); + } + } const updatedAt = yield* DateTime.now; const startedAt = turn.startedAt.get(id) ?? updatedAt; const completedAt = status === "running" ? null : updatedAt; @@ -1425,14 +1471,28 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ? {} : { childThreadId: call.child.subagent.appThread.id }), })); + const imageTasks = sessionsOf(state).flatMap((session) => + [...session.imageJobs.entries()].flatMap(([taskId, job]) => + job.status === "running" + ? [ + { + taskId, + kind: "background_task" as const, + description: `Image generation (${job.model})`, + }, + ] + : [], + ), + ); + const allTasks = [...roster, ...imageTasks]; const current = state.providerThread.pendingBackgroundTasks ?? []; if ( state.publishedBackgroundWork === hasBackground(state) && - current.length === roster.length && + current.length === allTasks.length && current.every( (task, index) => - task.taskId === roster[index]?.taskId && - task.description === roster[index]?.description && + task.taskId === allTasks[index]?.taskId && + task.description === allTasks[index]?.description && (task.kind === "subagent" ? task.childThreadId : undefined) === roster[index]?.childThreadId, ) @@ -1441,7 +1501,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } state.providerThread = { ...state.providerThread, - pendingBackgroundTasks: roster, + pendingBackgroundTasks: allTasks, updatedAt: yield* DateTime.now, }; yield* emitProviderThread(state); @@ -1726,6 +1786,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* emitText(state, turn, open.block, open.kind, (text) => text, true); } for (const id of turn.tools.keys()) { + if ([...state.imageJobs.values()].some((job) => job.turn === turn && job.toolId === id)) + continue; yield* emitTool( state, turn, @@ -2266,7 +2328,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr files: event.data.content.flatMap((part) => (part.type === "file" ? [part] : [])), metadata: event.data.metadata, }); - turn.tools.delete(event.data.id); + if ( + ![...state.imageJobs.values()].some( + (job) => job.turn === turn && job.toolId === event.data.id, + ) + ) + turn.tools.delete(event.data.id); return; } case "session.tool.failed": { @@ -2389,6 +2456,85 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr yield* offerWake(state, wake); }); + const imageReport = Effect.fn("OpenCode2Adapter.imageReport")(function* ( + state: ThreadState, + payload: { + readonly text: string; + readonly metadata?: Readonly> | undefined; + }, + ) { + const jobID = stringField(payload.metadata, "jobID"); + const job = jobID === undefined ? undefined : state.imageJobs.get(jobID); + const outcome = stringField(payload.metadata, "state"); + if ( + job === undefined || + (outcome !== "completed" && outcome !== "error" && outcome !== "cancelled") + ) + return; + // Native job inventory exposes the stem, while a completion notice names the saved file. + const saved = /Saved image: (.+) \([^\n]+\)\./.exec(payload.text)?.[1]; + const previewPath = + saved !== undefined && saved.startsWith(job.path + ".") ? saved : undefined; + if ( + job.status !== "running" && + !( + job.status === "completed" && + outcome === "completed" && + !job.previewed && + previewPath !== undefined + ) + ) + return; + const files: Array<{ uri: string; mime: string }> = []; + yield* Effect.gen(function* () { + if (outcome !== "completed" || previewPath === undefined) return; + const image = yield* ( + connection.external + ? connection.readImage(previewPath, state.directory) + : Effect.gen(function* () { + const mime = OpenCode2Client.imagePreviewMime(paths.extname(previewPath)); + const info = yield* fileSystem.stat(previewPath); + if (mime === undefined || info.size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) + return yield* new OpenCode2Client.OpenCode2ImageError({ + cause: "Unsupported image preview", + }); + const bytes = yield* fileSystem.readFile(previewPath); + if (bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) + return yield* new OpenCode2Client.OpenCode2ImageError({ + cause: "Image exceeds preview limit", + }); + return { + uri: `data:${mime};base64,${Buffer.from(bytes).toString("base64")}`, + mime, + }; + }) + ).pipe(Effect.timeout(INVENTORY_TIMEOUT), Effect.option); + if (Option.isSome(image)) files.push(image.value); + }).pipe( + Effect.ensuring( + Effect.gen(function* () { + // A known outcome must still settle its tool if preview I/O is interrupted. + job.status = outcome; + job.previewed ||= files.length > 0; + job.turn.tools.set(job.toolId, job.tool); + yield* emitTool( + state, + job.turn, + job.toolId, + outcome === "completed" + ? "completed" + : outcome === "error" + ? "failed" + : "interrupted", + { output: payload.text, metadata: undefined, files }, + ); + job.turn.tools.delete(job.toolId); + yield* syncRosterAncestors(state); + }), + ), + ); + }); + const onReport = Effect.fnUntraced(function* ( state: ThreadState, inboxId: string, @@ -2397,6 +2543,9 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr readonly metadata?: Readonly> | undefined; }, ) { + if (stringField(payload.metadata, "source") === "experimental_image_generate") { + return yield* imageReport(state, payload); + } const childId = stringField(payload.metadata, "childID"); if (stringField(payload.metadata, "source") !== "subagent" || childId === undefined) return; strays.delete(childId); @@ -2683,8 +2832,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } for (const state of threads.values()) { for (const call of runningCalls(state)) yield* settleCall(call, "failed"); + for (const [jobID, job] of state.imageJobs) { + if (job.status !== "running") continue; + yield* imageReport(state, { text: message, metadata: { jobID, state: "error" } }); + } for (const wake of state.wakes.splice(0)) wake.dropped = true; state.reports.clear(); + yield* syncRosterAncestors(state); } yield* setSessionStatus("error", message); yield* Queue.end(events); @@ -2768,7 +2922,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ), metadata: part.state.metadata, }); - turn.tools.delete(part.id); + if ( + ![...state.imageJobs.values()].some( + (job) => job.turn === turn && job.toolId === part.id, + ) + ) + turn.tools.delete(part.id); } else if (part.state.status === "error") { yield* emitTool(state, turn, part.id, "failed", { output: part.state.error.message, @@ -2784,6 +2943,36 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }); // Restarts retain the previous session.outcome; without an idle item, the lost execution was interrupted. + const recoverImages = Effect.fn("OpenCode2Adapter.recoverImages")(function* ( + state: ThreadState, + ) { + if (![...state.imageJobs.values()].some((job) => job.status === "running")) return; + yield* OpenCode2Client.paginate( + { sessionID: Session.ID.make(state.sessionId), type: "synthetic" as const, limit: 100 }, + client.message.list, + ).pipe( + Stream.runForEach((message) => + message.type === "synthetic" && + stringField(message.metadata, "source") === "experimental_image_generate" + ? imageReport(state, message) + : Effect.void, + ), + ); + if ( + ![...state.imageJobs.values()].some((job) => job.status === "running") || + compareSemverVersions(connection.version, "2.2.6") < 0 + ) + return; + const jobs = yield* connection.imageJobs(state.sessionId); + for (const job of jobs) { + if (job.status === "running") continue; + yield* imageReport(state, { + text: `Image generation ${job.status}. Output path: ${job.path} (${job.model}).`, + metadata: { source: "experimental_image_generate", jobID: job.id, state: job.status }, + }); + } + }); + const reconcile = Effect.fn("OpenCode2Adapter.reconcile")(function* () { // Read deepest sessions first; subagent turns end before their waiting parents. const running = [...threads] @@ -2833,6 +3022,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr : { status: "interrupted" }; yield* endExecution(state, turn, terminal); } + for (const state of threads.values()) { + yield* recoverImages(state).pipe( + Effect.timeout(INVENTORY_TIMEOUT), + Effect.ignore({ log: true }), + ); + } for (const state of background) { for (const call of runningCalls(state)) { const child = call.child?.sessionId; From b883156e269de2002873aebdef6019f336b687a7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 17:17:38 -0800 Subject: [PATCH 053/170] fix(scripts): scenarios run where localhost resolves to IPv6 first (#34121) Co-authored-by: Claude Fable 5.2 --- docs/operations/scenarios.md | 14 +++++++++- scripts/e2e.config.ts | 11 +++++--- scripts/scenarios/start-app.ts | 49 +++++++++++++++++++++++++++------- 3 files changed, 61 insertions(+), 13 deletions(-) diff --git a/docs/operations/scenarios.md b/docs/operations/scenarios.md index c7a753f8ae2b..c49f23a4b206 100644 --- a/docs/operations/scenarios.md +++ b/docs/operations/scenarios.md @@ -70,7 +70,19 @@ cd scripts && pnpm exec e2e run scenarios/replay-turn-streams.e2e.ts --headed e2e starts the dev stack through [`start-app.ts`](../../scripts/scenarios/start-app.ts) on a free port, runs the tests, and stops it. Results land in `scripts/.e2e`: `report.json`, `summary.md`, -and per test a `trace.md`, its screenshots, and a video. The first run downloads e2e's browser. +and per test a `trace.md`, its screenshots, and a video. `vp run scenarios --target web` runs one +target; flags go straight after the script name, without `--`. + +The first run downloads e2e's browser (about 120 MB). To fetch it ahead of time, such as in a +machine image, run this from the repository root after `vp i`: + +```sh +node scripts/node_modules/playwright-core/cli.js install --only-shell chromium ffmpeg +``` + +e2e opens the web app at `127.0.0.1`, and the start script tells the web dev server to bind that +address. It does not use `localhost`, which some machines resolve to `::1` first. + `e2e run --help` lists the rest: `--grep`, `--watch`, `--last-failed`, `--changed-since`. Run one at a time per checkout: a run recreates the checkout's scenario T3 home and its `.e2e` diff --git a/scripts/e2e.config.ts b/scripts/e2e.config.ts index 6db320e4aa72..520fc8338da7 100644 --- a/scripts/e2e.config.ts +++ b/scripts/e2e.config.ts @@ -46,6 +46,11 @@ export const T3_HOME = resolved.home; export const MOBILE_T3_HOME = `${T3_HOME}-mobile`; export const MOBILE = resolved.mobile; const startApp = resolved.startApp; +/** + * The one address e2e opens the web app at and the app is told to bind. Never `localhost`: the + * runner and the app can resolve that name to different addresses. + */ +const LOOPBACK = "127.0.0.1"; /** * Leases a device from the Simlock pool, whose gateway speaks agent-device's lease protocol. @@ -131,12 +136,12 @@ export default { name: "web", engine: web({ viewport: { width: 1280, height: 800 } }), app: { - url: "http://127.0.0.1:0", + url: `http://${LOOPBACK}:0`, // Vite answers before the server does; this path is proxied to the server. - readyUrl: "http://127.0.0.1:{port}/.well-known/t3/environment", + readyUrl: `http://${LOOPBACK}:{port}/.well-known/t3/environment`, command: { executable: resolved.node, - args: [startApp, "web", T3_HOME, "{port}"], + args: [startApp, "web", T3_HOME, LOOPBACK, "{port}"], cwd: APP_DIR, startupTimeout: 300_000, log: ".e2e/app.log", diff --git a/scripts/scenarios/start-app.ts b/scripts/scenarios/start-app.ts index 5eabe224b977..5dee3f26c138 100644 --- a/scripts/scenarios/start-app.ts +++ b/scripts/scenarios/start-app.ts @@ -141,17 +141,21 @@ const startApp = Effect.fn("startApp")(function* (input: { ]; if (input.surface === "web") { - const [webPort = ""] = input.ports; - const serverPort = yield* net.reserveLoopbackPort(); + // e2e opens the app at this host, so the web server is told to bind exactly it. Left to its + // default, `localhost`, it binds ::1 alone on machines that resolve the name to IPv6 first. + const [host = "", webPort = ""] = input.ports; + const origin = `http://${host}:${webPort}`; + const serverPort = String(yield* net.reserveLoopbackPort()); const token = yield* (yield* SecureRandom.SecureRandom).uuidV4(); - const runner = yield* start({ + const ports = ["--port", serverPort, "--dev-url", origin]; + const webEnv = { ...env, T3CODE_PORT_OFFSET: String(Number(webPort) - BASE_WEB_PORT) }; + const server = yield* start({ cwd: checkout, command: node, - args: devRunner("dev", ["--port", String(serverPort)]), + args: devRunner("dev:server", ports), env: { - ...env, - T3CODE_PORT_OFFSET: String(Number(webPort) - BASE_WEB_PORT), - T3CODE_DEV_ALLOWED_ORIGINS: `http://127.0.0.1:${webPort}`, + ...webEnv, + T3CODE_DEV_ALLOWED_ORIGINS: origin, // Makes the startup pairing link reusable, so every test can sign in with it. T3CODE_DEV_AUTH_TOKEN: `${token}${token}`.replaceAll("-", ""), }, @@ -165,7 +169,32 @@ const startApp = Effect.fn("startApp")(function* (input: { .pipe(Effect.ignore); }, }); - return yield* runner.exitCode; + const web = yield* start({ + cwd: checkout, + command: node, + args: devRunner("dev:web", [...ports, "--", "--host", host]), + env: webEnv, + onLine: Console.log, + }); + // A web server that came up on another loopback address would leave e2e waiting out its + // whole startup timeout; say so at once instead. + const boundElsewhere = Effect.gen(function* () { + const elsewhere = host === "::1" ? "127.0.0.1" : "::1"; + if (yield* net.hasListenerOnHost(Number(webPort), host)) return yield* Effect.never; + if (!(yield* net.hasListenerOnHost(Number(webPort), elsewhere))) { + return yield* new ScenarioError({ message: "The web server is not listening yet." }); + } + yield* Console.error( + `The web server listens on ${elsewhere}:${webPort}, not on ${host}: it ignored --host.`, + ); + return 1; + }).pipe( + Effect.retry({ + schedule: Schedule.spaced("1 second"), + while: (error) => error._tag === "ScenarioError", + }), + ); + return yield* Effect.raceAll([server.exitCode, web.exitCode, boundElsewhere]); } // The device is another machine: the server listens on every interface, and Metro serves the @@ -212,7 +241,9 @@ const command = Command.make( ), home: Argument.String("t3-home").pipe(Argument.withDescription("T3 home to recreate.")), ports: Argument.String("port").pipe( - Argument.withDescription("web: . mobile: ."), + Argument.withDescription( + "web: . mobile: .", + ), Argument.variadic(), ), }, From 768f17c5187db6e3559856dc867ac5e5f988ed11 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 10 Nov 2026 18:40:09 -0800 Subject: [PATCH 054/170] ci: browser secret helper apt step fetches fewer indexes (#33966) Co-authored-by: Claude Opus 5.5 --- .github/workflows/ci.yml | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 260be6436c3e..5343dbb754ff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -140,10 +140,16 @@ jobs: - name: Start installing browser secret helper build libraries if: needs.changes.outputs.build != 'false' run: | - sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources + # Fetch only the indexes these main and universe packages need. The full set is ~42 MB, + # which a slow mirror can stretch past the wait below. + sudo sed -i -e 's|http://|https://|g' -e 's/^Components: .*/Components: main universe/' \ + /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources ( set +e - sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config xvfb + sudo apt-get update -o Acquire::Languages=none \ + -o Acquire::IndexTargets::deb::DEP-11::DefaultEnabled=false \ + -o Acquire::IndexTargets::deb::CNF::DefaultEnabled=false && + sudo apt-get install -y libsecret-1-dev pkg-config xvfb echo "$?" > "$RUNNER_TEMP/apt-status" ) > "$RUNNER_TEMP/apt.log" 2>&1 < /dev/null & @@ -287,10 +293,16 @@ jobs: # the background while Vite+ installs; the step before the tests waits for it. - name: Start installing browser secret helper build libraries run: | - sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources + # Fetch only the indexes these main and universe packages need. The full set is ~42 MB, + # which a slow mirror can stretch past the wait below. + sudo sed -i -e 's|http://|https://|g' -e 's/^Components: .*/Components: main universe/' \ + /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources ( set +e - sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config + sudo apt-get update -o Acquire::Languages=none \ + -o Acquire::IndexTargets::deb::DEP-11::DefaultEnabled=false \ + -o Acquire::IndexTargets::deb::CNF::DefaultEnabled=false && + sudo apt-get install -y libsecret-1-dev pkg-config echo "$?" > "$RUNNER_TEMP/apt-status" ) > "$RUNNER_TEMP/apt.log" 2>&1 < /dev/null & From d152d2c8240618f60308c3b42a160a414be57538 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 18:53:41 -0800 Subject: [PATCH 055/170] fix(client-runtime): a search query pasted from github.com lists pull requests again (#30150) Co-authored-by: Claude Opus 5.5 --- .../src/pullRequestQuery.test.ts | 15 ++++++++++ .../client-runtime/src/pullRequestQuery.ts | 30 +++++++++++++++---- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/packages/client-runtime/src/pullRequestQuery.test.ts b/packages/client-runtime/src/pullRequestQuery.test.ts index 33eddb7f1a6e..7d73813f3733 100644 --- a/packages/client-runtime/src/pullRequestQuery.test.ts +++ b/packages/client-runtime/src/pullRequestQuery.test.ts @@ -33,6 +33,7 @@ describe("reading qualifiers out of a typed query", () => { review: "changes-requested", checks: "failing", }); + expect(parsePullRequestQuery("-draft:true").filters).toEqual({ draft: "hide" }); }); it("leaves an unknown value and a stray colon as text, and reads an unknown key as a label", () => { @@ -53,6 +54,20 @@ describe("reading qualifiers out of a typed query", () => { ]); }); + // regression: #30131 a query pasted from github.com lists nothing + it("ignores GitHub's own search qualifiers instead of reading them as labels", () => { + expect( + parsePullRequestQuery( + "is:pr state:open archived:false repo:org/repo org:org user:alice sort:updated-desc -repo:org/fork -state:closed fix", + ), + ).toEqual({ text: "fix", filters: {} }); + }); + + it("sets no author when the query names more than one", () => { + expect(parsePullRequestQuery("author:alice author:bob").filters).toEqual({}); + expect(parsePullRequestQuery("author:me author:@me").filters).toEqual({ author: "me" }); + }); + it("cuts a typed query back to what the contract carries", () => { const many = Array.from({ length: 14 }, (_, index) => `l${index}`).join(","); const long = "x".repeat(240); diff --git a/packages/client-runtime/src/pullRequestQuery.ts b/packages/client-runtime/src/pullRequestQuery.ts index 9b333972d0fa..b80202c94b06 100644 --- a/packages/client-runtime/src/pullRequestQuery.ts +++ b/packages/client-runtime/src/pullRequestQuery.ts @@ -29,6 +29,11 @@ function splitQualifierList(raw: string): string[] { .filter((part) => part.length > 0); } +/** `me` and `@me` both name the viewer; logins are case-insensitive. */ +function authorKey(login: string): string { + return login.toLowerCase().replace(/^@me$/, "me"); +} + function boundedNames(names: ReadonlyArray): string[] { return names .slice(0, MAX_QUALIFIER_VALUES) @@ -43,7 +48,8 @@ export function parsePullRequestQuery(raw: string): { const text: string[] = []; const labels: string[][] = []; const excludedLabels: string[] = []; - let author: string | undefined; + // `null` once two different logins are named: GitHub ORs them, the contract carries one. + let author: string | null | undefined; let draft: PullRequestListFilters["draft"]; let review: PullRequestListFilters["review"]; let checks: PullRequestListFilters["checks"]; @@ -59,13 +65,16 @@ export function parsePullRequestQuery(raw: string): { else labels.push(names); continue; } - case "author": + case "author": { if (negated) break; - author = value.slice(0, MAX_QUALIFIER_LENGTH).trim(); + const login = value.slice(0, MAX_QUALIFIER_LENGTH).trim(); + if (author === undefined) author = login; + else if (author === null || authorKey(author) !== authorKey(login)) author = null; continue; + } case "draft": - if (negated || (value.toLowerCase() !== "true" && value.toLowerCase() !== "false")) break; - draft = value.toLowerCase() === "true" ? "only" : "hide"; + if (value.toLowerCase() !== "true" && value.toLowerCase() !== "false") break; + draft = (value.toLowerCase() === "true") !== negated ? "only" : "hide"; continue; case "review": { const decision = negated ? undefined : REVIEW_VALUES[value.toLowerCase()]; @@ -80,6 +89,15 @@ export function parsePullRequestQuery(raw: string): { checks = state; continue; } + // GitHub's own search qualifiers, not labels: the list sets scope and order itself. + case "is": + case "archived": + case "state": + case "repo": + case "org": + case "user": + case "sort": + continue; case "": break; default: @@ -104,7 +122,7 @@ export function parsePullRequestQuery(raw: string): { ...(excludedLabels.length === 0 ? {} : { excludedLabels: excludedLabels.slice(0, MAX_QUALIFIER_VALUES) }), - ...(author === undefined ? {} : { author }), + ...(typeof author === "string" ? { author } : {}), ...(draft === undefined ? {} : { draft }), ...(review === undefined ? {} : { review }), ...(checks === undefined ? {} : { checks }), From 4ca10398b1b60146a80d012d0335c5ce44fabc63 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 10 Nov 2026 20:57:49 -0600 Subject: [PATCH 056/170] fix(web): tighter outdated-conversation cards in the PR code panel (#34140) Co-authored-by: Claude Opus 5.5 --- .../web/src/components/pullRequest/PullRequestCodeTab.tsx | 2 +- .../pullRequest/PullRequestReviewAnnotation.tsx | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index 31fd309348be..3ab981865b49 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1503,7 +1503,7 @@ function PullRequestCodeTab({ -
    +
    {[...orphanFiles].map(([path, threads]) => (
    diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx index d2ae440fde9e..23808ed83140 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx @@ -229,7 +229,7 @@ export function ReviewThreadCard({ return (
    event.stopPropagation()} > @@ -250,7 +250,7 @@ export function ReviewThreadCard({ {thread.isOutdated ? outdated : null} {onFix ? (