diff --git a/apps/mobile/src/features/home/threadArchive.test.ts b/apps/mobile/src/features/home/threadArchive.test.ts new file mode 100644 index 0000000000..6d93ec8e80 --- /dev/null +++ b/apps/mobile/src/features/home/threadArchive.test.ts @@ -0,0 +1,34 @@ +import { ProviderInstanceId, RunId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models"; +import { threadCanArchive } from "./threadArchive"; + +function runtime( + status: ThreadRuntimeSummary["status"], + activeRunId: ThreadRuntimeSummary["activeRunId"], +): ThreadRuntimeSummary { + return { + status, + activeRunId, + providerInstanceId: ProviderInstanceId.make("codex"), + providerName: "codex", + lastError: null, + updatedAt: "2026-07-28T10:00:00.000Z", + }; +} + +describe("threadCanArchive", () => { + it("blocks provider-active work", () => { + const activeRunId = RunId.make("run-live"); + expect(threadCanArchive(runtime("preparing", activeRunId))).toBe(false); + expect(threadCanArchive(runtime("starting", activeRunId))).toBe(false); + expect(threadCanArchive(runtime("running", activeRunId))).toBe(false); + expect(threadCanArchive(runtime("queued", activeRunId))).toBe(false); + }); + + it("allows queued-only and post-provider waiting work", () => { + expect(threadCanArchive(runtime("queued", null))).toBe(true); + expect(threadCanArchive(runtime("waiting", null))).toBe(true); + }); +}); diff --git a/apps/mobile/src/features/home/threadArchive.ts b/apps/mobile/src/features/home/threadArchive.ts new file mode 100644 index 0000000000..aa1cd091fa --- /dev/null +++ b/apps/mobile/src/features/home/threadArchive.ts @@ -0,0 +1,10 @@ +import { threadRuntimeHasInterruptibleRun } from "@t3tools/client-runtime/state/thread-execution"; +import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models"; + +/** + * Archiving may discard queued work, but it must not detach a provider while + * that provider is still executing a turn. + */ +export function threadCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean { + return !threadRuntimeHasInterruptibleRun(runtime); +} diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 9ff359079d..adb9887b9a 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -1,7 +1,4 @@ -import { - threadRuntimeIsActive, - type EnvironmentThreadShell, -} from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { canSettle } from "@t3tools/client-runtime/state/thread-settled"; import * as Cause from "effect/Cause"; import * as Haptics from "expo-haptics"; @@ -20,6 +17,7 @@ import { appAtomRegistry } from "../../state/atom-registry"; import { environmentServerConfigsAtom } from "../../state/server"; import { environmentThreadShells, threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; +import { threadCanArchive } from "./threadArchive"; /** Version skew: never send settle/unsettle to a server that predates them (capability defaults false on decode for older servers). */ @@ -131,9 +129,9 @@ function useThreadActionExecutor( ); return false; } - // Archive keeps its original, narrower guard: never interrupt a - // thread mid-turn. - if (action === "archive" && threadRuntimeIsActive(thread.runtime)) { + // The server cancels queued runs on archive. Only an actual provider + // turn still needs the user to interrupt it first. + if (action === "archive" && !threadCanArchive(thread.runtime)) { Alert.alert( actionFailureTitle(action), "This thread is working. Interrupt it first, then try again.", diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ce76b2947e..22a80d94a8 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -628,7 +628,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const startNextQueuedRun = (threadId: ThreadId) => Effect.gen(function* () { const projection = yield* projectionStore.getThreadProjection(threadId); - if (projection.runs.some(isBlockingRun)) { + if ( + projection.thread.archivedAt !== null || + projection.thread.deletedAt !== null || + projection.runs.some(isBlockingRun) + ) { return; } @@ -997,13 +1001,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: updatedThread, }); - if (command.type === "thread.delete") { + if (command.type === "thread.archive" || command.type === "thread.delete") { const emitEvent = emit(events, command); const activeRunIds = new Set( projection.runs - .filter((run) => - ["preparing", "queued", "starting", "running", "waiting"].includes(run.status), - ) + .filter((run) => { + if (command.type === "thread.archive") { + return run.status === "queued"; + } + return ["preparing", "queued", "starting", "running", "waiting"].includes(run.status); + }) .map((run) => run.id), ); for (const run of projection.runs.filter((candidate) => activeRunIds.has(candidate.id))) { @@ -1049,24 +1056,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: { ...node, status: "cancelled", completedAt: now }, }); } - for (const request of projection.runtimeRequests.filter( - (candidate) => candidate.status === "pending", - )) { - yield* emitEvent({ - type: "runtime-request.updated", - threadId: command.threadId, - nodeId: request.nodeId, - occurredAt: now, - payload: { - ...request, - status: "cancelled", - responseCapability: { - type: "not_resumable", - reason: "The thread was deleted.", + if (command.type === "thread.delete") { + for (const request of projection.runtimeRequests.filter( + (candidate) => candidate.status === "pending", + )) { + yield* emitEvent({ + type: "runtime-request.updated", + threadId: command.threadId, + nodeId: request.nodeId, + occurredAt: now, + payload: { + ...request, + status: "cancelled", + responseCapability: { + type: "not_resumable", + reason: "The thread was deleted.", + }, + resolvedAt: now, }, - resolvedAt: now, - }, - }); + }); + } } } @@ -4183,6 +4192,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio .pipe( Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })), ); + if (projection.thread.archivedAt !== null || projection.thread.deletedAt !== null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} is not active.`, + }); + } const queuedRun = projection.runs.find((candidate) => candidate.id === command.queuedRunId); if (queuedRun === undefined || queuedRun.status !== "queued") { return yield* new OrchestratorDispatchError({ diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 60b58d9702..87e24aabd0 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -682,6 +682,141 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => { assert.equal(retry._tag, "OrchestratorCommandPreviouslyRejectedError"); }), ); + + it.effect("rejects settling a thread while a run is active", () => + Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + const threadId = ThreadId.make("runtime-layer-active-settle-thread"); + + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-active-settle-create"), + threadId, + projectId: ProjectId.make("runtime-layer-active-settle-project"), + title: "Active settle", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: "/tmp/runtime-layer-active-settle", + }); + yield* orchestrator.dispatch({ + type: "thread.settle", + commandId: CommandId.make("runtime-layer-active-settle-initial"), + threadId, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-active-settle-message"), + threadId, + messageId: MessageId.make("runtime-layer-active-settle-message"), + text: "Keep this run active.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + + const error = yield* orchestrator + .dispatch({ + type: "thread.settle", + commandId: CommandId.make("runtime-layer-active-settle"), + threadId, + }) + .pipe(Effect.flip); + + assert.equal(error._tag, "OrchestratorDispatchError"); + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal(projection.runs[0]?.status, "starting"); + assert.isNull(projection.thread.settledOverride); + assert.isNull(projection.thread.settledAt); + }), + ); + + it.effect("cancels queued work when a thread is archived", () => + Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + const threadId = ThreadId.make("runtime-layer-archive-queued-thread"); + + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-archive-queued-create"), + threadId, + projectId: ProjectId.make("runtime-layer-archive-queued-project"), + title: "Archive queued work", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: "/tmp/runtime-layer-archive-queued", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-archive-queued-active-message"), + threadId, + messageId: MessageId.make("runtime-layer-archive-queued-active-message"), + text: "Keep the provider occupied.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-archive-queued-next-message"), + threadId, + messageId: MessageId.make("runtime-layer-archive-queued-next-message"), + text: "Do not run this after archive.", + attachments: [], + modelSelection, + dispatchMode: { type: "queue_after_active" }, + }); + + const beforeArchive = yield* orchestrator.getThreadProjection(threadId); + const activeRun = beforeArchive.runs.find((run) => run.status === "starting"); + const queuedRun = beforeArchive.runs.find((run) => run.status === "queued"); + assert.isDefined(activeRun); + assert.isDefined(queuedRun); + + yield* orchestrator.dispatch({ + type: "thread.archive", + commandId: CommandId.make("runtime-layer-archive-queued-archive"), + threadId, + }); + + const archived = yield* orchestrator.getThreadProjection(threadId); + assert.isNotNull(archived.thread.archivedAt); + assert.equal(archived.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled"); + assert.equal( + archived.attempts.find((attempt) => attempt.runId === queuedRun.id)?.status, + "cancelled", + ); + assert.equal(archived.nodes.find((node) => node.runId === queuedRun.id)?.status, "cancelled"); + assert.equal(yield* orchestrator.resumeQueuedRuns, 0); + + const promoteError = yield* orchestrator + .dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("runtime-layer-archive-queued-promote"), + threadId, + queuedRunId: queuedRun.id, + targetRunId: activeRun.id, + }) + .pipe(Effect.flip); + assert.equal(promoteError._tag, "OrchestratorDispatchError"); + + const afterPromotion = yield* orchestrator.getThreadProjection(threadId); + assert.equal(afterPromotion.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled"); + }), + ); }); it.layer(SharedApplicationDataPlaneTestLayer)("pending provider interruption", (it) => {