From 35c17ca0c166477b3446646f77148e1bd4e7a2bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mads=20F=C3=B8hns?= Date: Mon, 16 Nov 2026 22:28:16 +0100 Subject: [PATCH] feat(sidebar): add an Automation space for bot-run threads Since upstream stopped holding a thread in Working once its watched PR's checks finish, the PR review bot's ~80 threads fill the sidebar as Done. A third space, Automation, sits next to Development and Dev support for threads that bots run. The switch, the thread menu's Move to submenu, the command palette's Switch to actions and the lists all read one list of spaces, so another space is a contract literal and a label. Three names do not fit the sidebar, so the current space shows its name and hidden ones show an icon and badge. Automation's badge counts approvals, questions, ready plans and unseen failed runs; every bot follow-up ends unread, so finished turns never count there. When a turn in an Automation thread completes, a server reactor waits 15 seconds, longer than the client's visit throttle, then snoozes the thread for a year if nothing waits on the user and nobody opened, woke or wrote to it during that turn. The new thread.auto-snooze command rechecks live state in the orchestrator, as thread.auto-settle does, then applies the ordinary snooze. Every client, including the installed upstream mobile app that ignores spaces, then lists it under Snoozed, and the existing rules wake it on an approval, a new question or a failure. SPY builds before this one decode the stored `space` strictly, so Automation is stored in a separate `addedSpace` key that they drop, seeing the thread as Development; rollbacks and older linked clients keep working. This build reads unknown `addedSpace` values the same way. Those servers also reject an "automation" command, so a threadSpaceIds capability lists each server's spaces, and clients offer and send only those. Commands, MCP inputs and the client model keep one `space` with all three values; t3_thread_launch, t3_thread_list and t3_thread_update's set_space accept "automation". Co-Authored-By: Claude Opus 5.5 --- .../src/environment/ServerEnvironment.ts | 2 + apps/server/src/mcp/OrchestratorMcpService.ts | 8 +- .../src/mcp/ThreadMetadataMcpService.ts | 11 +- .../src/mcp/toolkits/orchestrator/tools.ts | 2 +- .../src/mcp/toolkits/project/handlers.ts | 4 +- apps/server/src/mcp/toolkits/project/tools.ts | 4 +- .../AutomationSnoozeReactor.test.ts | 256 ++++++++++++++++++ .../AutomationSnoozeReactor.ts | 149 ++++++++++ .../Orchestrator.space.test.ts | 28 +- .../src/orchestration-v2/Orchestrator.ts | 45 ++- .../src/orchestration-v2/ProjectionStore.ts | 12 +- .../testkit/OrchestratorScenario.ts | 1 + .../src/provider/agentContextBudget.json | 2 +- apps/server/src/server.ts | 7 + apps/web/src/components/CommandPalette.tsx | 21 +- apps/web/src/components/Sidebar.tsx | 39 +-- .../src/components/chat/useComposerSend.ts | 13 +- .../components/chat/useMultipleModelSend.ts | 4 +- .../components/sidebar/SidebarSpaceSwitch.tsx | 59 ++-- .../sidebar/spaceAttention.logic.test.ts | 36 ++- .../sidebar/spaceAttention.logic.ts | 16 +- .../components/threadActionMenu.logic.test.ts | 34 ++- .../src/components/threadActionMenu.logic.ts | 24 +- .../web/src/hooks/useThreadActionMenu.test.ts | 2 +- apps/web/src/hooks/useThreadActionMenu.ts | 19 +- apps/web/src/state/entities.ts | 13 +- apps/web/src/threadSpace.test.ts | 32 +++ apps/web/src/threadSpace.ts | 43 ++- apps/web/src/uiStateStore.ts | 10 +- docs/internals/glossary.md | 24 +- docs/user/thread-sidebar.md | 32 ++- packages/client-runtime/src/state/models.ts | 5 +- .../src/state/threadCommands.ts | 9 +- packages/contracts/src/environment.ts | 2 + .../contracts/src/orchestrationV2.test.ts | 37 +++ packages/contracts/src/orchestrationV2.ts | 62 ++++- packages/contracts/src/orchestratorMcp.ts | 3 +- .../contracts/src/threadMetadataMcp.test.ts | 4 + packages/contracts/src/threadMetadataMcp.ts | 8 +- 39 files changed, 937 insertions(+), 145 deletions(-) create mode 100644 apps/server/src/orchestration-v2/AutomationSnoozeReactor.test.ts create mode 100644 apps/server/src/orchestration-v2/AutomationSnoozeReactor.ts create mode 100644 apps/web/src/threadSpace.test.ts diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index b88c1756dc4e1..4f8ba8e78255a 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -1,6 +1,7 @@ import { EnvironmentId, ORCHESTRATION_PROTOCOL_VERSION, + OrchestrationV2ThreadSpace, PROVIDER_SEND_TURN_MAX_FILE_BYTES, type ExecutionEnvironmentDescriptor, } from "@t3tools/contracts"; @@ -262,6 +263,7 @@ export const make = Effect.gen(function* () { threadAutoSettleOptOut: true, threadProjectFromScratch: true, threadSpaces: true, + threadSpaceIds: OrchestrationV2ThreadSpace.literals, threadTitleRegeneration: true, commandOutputStreaming: true, threadVisitedTracking: true, diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index a8d6cf80577d3..072b7593ce0c0 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1,5 +1,6 @@ import { CommandId, + orchestrationV2ThreadSpaceOf, type RunId, isProviderAvailable, MessageId, @@ -961,7 +962,7 @@ function listItemFromShell( interactionMode: shell.interactionMode, linkedPullRequest: shell.linkedPullRequest ?? null, ...threadPullRequests(shell.pullRequests), - space: shell.space ?? "development", + space: orchestrationV2ThreadSpaceOf(shell), ...threadSettlement(shell), ...threadSnooze(shell, nowMs), pinned: shell.pinnedAt != null, @@ -3133,7 +3134,7 @@ const make = Effect.gen(function* () { commandId, threadId, projectId: parent.thread.projectId, - ...(parent.thread.space === undefined ? {} : { space: parent.thread.space }), + space: orchestrationV2ThreadSpaceOf(parent.thread), title, modelSelection: target.modelSelection, runtimeMode, @@ -3267,7 +3268,8 @@ const make = Effect.gen(function* () { input.settled === undefined || threadSettlement(thread).settled === input.settled, ) .filter( - (thread) => input.space === undefined || (thread.space ?? "development") === input.space, + (thread) => + input.space === undefined || orchestrationV2ThreadSpaceOf(thread) === input.space, ) .filter( (thread) => diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.ts b/apps/server/src/mcp/ThreadMetadataMcpService.ts index 887d5506c6469..6da9dc506841f 100644 --- a/apps/server/src/mcp/ThreadMetadataMcpService.ts +++ b/apps/server/src/mcp/ThreadMetadataMcpService.ts @@ -1,5 +1,6 @@ import { CommandId, + orchestrationV2ThreadSpaceOf, OrchestratorMcpFailure, type OrchestrationV2AppThread, type OrchestrationV2Command, @@ -95,7 +96,13 @@ function resultFromThread(input: { readonly sequence: number; readonly thread: Pick< OrchestrationV2AppThread, - "id" | "title" | "titleRegeneration" | "linkedPullRequest" | "space" | "updatedAt" + | "id" + | "title" + | "titleRegeneration" + | "linkedPullRequest" + | "space" + | "addedSpace" + | "updatedAt" >; }): ThreadMetadataMcpUpdateResult { return { @@ -112,7 +119,7 @@ function resultFromThread(input: { startedAt: DateTime.formatIso(input.thread.titleRegeneration.startedAt), }, linkedPullRequest: input.thread.linkedPullRequest ?? null, - space: input.thread.space ?? "development", + space: orchestrationV2ThreadSpaceOf(input.thread), updatedAt: DateTime.formatIso(input.thread.updatedAt), }; } diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 006a60035fb5c..566e4abf48400 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -268,7 +268,7 @@ const ThreadReadTool = Tool.make("t3_thread_read", { const ThreadUpdateTool = Tool.make("t3_thread_update", { description: - "Rename a thread (`action:'rename'` with `title`), regenerate its title, or move it between the Development and Dev support spaces (`action:'set_space'` with `space`). Omit `threadId` for this thread. Workspace and branch cannot change here.", + "Rename a thread (`action:'rename'` with `title`), regenerate its title, or move it to another space (`action:'set_space'` with `space`). Omit `threadId` for this thread. Workspace and branch cannot change here.", // Keeps the input's action/field check, which rebuilding the struct would drop. parameters: ThreadMetadataMcpUpdateInput.mapFields( Struct.assign({ environmentId: OrchestratorMcpEnvironmentTarget }), diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 2d5469b16ad05..08092165aa5c8 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -1,5 +1,6 @@ import { CommandId, + orchestrationV2ThreadSpaceOf, MessageId, ThreadId, OrchestratorMcpFailure, @@ -265,7 +266,8 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { )?.supportedRuntimeModes, }); } - const space = input.space ?? caller?.space; + const space = + input.space ?? (caller === undefined ? undefined : orchestrationV2ThreadSpaceOf(caller)); const result = yield* ThreadMessageIntake.launchThread({ commandId, threadId, diff --git a/apps/server/src/mcp/toolkits/project/tools.ts b/apps/server/src/mcp/toolkits/project/tools.ts index 4e011d4e75a40..e61a545fe1f84 100644 --- a/apps/server/src/mcp/toolkits/project/tools.ts +++ b/apps/server/src/mcp/toolkits/project/tools.ts @@ -10,6 +10,7 @@ import { OrchestrationV2RunStatus, OrchestrationV2ThreadLaunchWorkspaceStrategy, OrchestrationV2ThreadSpace, + ORCHESTRATION_V2_THREAD_SPACE_SUMMARY, RuntimeMode, ProviderInteractionMode, Project, @@ -143,8 +144,7 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", { title: TrimmedNonEmptyString, space: Schema.optional( OrchestrationV2ThreadSpace.annotate({ - description: - 'Space for the new thread: "development" or "support" (Dev support). Omit to use the calling thread\'s space.', + description: `Space for the new thread: ${ORCHESTRATION_V2_THREAD_SPACE_SUMMARY}. Omit to use the calling thread's space.`, }), ), modelSelection: Schema.optional(ModelSelection), diff --git a/apps/server/src/orchestration-v2/AutomationSnoozeReactor.test.ts b/apps/server/src/orchestration-v2/AutomationSnoozeReactor.test.ts new file mode 100644 index 0000000000000..74d531f9b9dfe --- /dev/null +++ b/apps/server/src/orchestration-v2/AutomationSnoozeReactor.test.ts @@ -0,0 +1,256 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + EventId, + MessageId, + type OrchestrationV2DomainEvent, + type OrchestrationV2ThreadSpace, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as AutomationSnoozeReactor from "./AutomationSnoozeReactor.ts"; +import * as EffectOutbox from "./EffectOutbox.ts"; +import * as EventSink from "./EventSink.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; + +const instanceId = ProviderInstanceId.make("codex"); +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed for the snooze reactor"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = AutomationSnoozeReactor.layer.pipe( + Layer.provideMerge( + Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "automation-snooze" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), + ), + ), +); + +const startBotTurn = (space: OrchestrationV2ThreadSpace, sentBy: "agent" | "user") => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + yield* TestClock.adjust("1 hour"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make("project:automation-snooze"), + space, + title: "Review spysystem/t3code#8", + modelSelection: { instanceId, model: "gpt-5.1-codex" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "agent", + creationSource: "mcp", + }); + yield* TestClock.adjust("1 minute"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start"), + threadId, + messageId: MessageId.make("message:start"), + text: "Review the pull request", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: sentBy, + creationSource: sentBy === "user" ? "web" : "mcp", + }); + return (yield* projections.getThreadProjection(threadId)).runs[0]!; + }); + +const finishTurn = ( + run: Effect.Success>, + status: "completed" | "failed", +) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const finished = { + id: EventId.make("event:run-finished"), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { ...run, status, completedAt: now }, + } satisfies OrchestrationV2DomainEvent; + yield* (yield* EventSink.EventSinkV2).write({ events: [finished] }); + return finished; + }); + +const visit = (commandId: string) => + Effect.gen(function* () { + yield* (yield* Orchestrator.OrchestratorV2).dispatch({ + type: "thread.visit", + commandId: CommandId.make(commandId), + threadId, + visitedAt: DateTime.formatIso(yield* DateTime.now), + }); + }); + +const threadId = ThreadId.make("thread:automation-snooze"); + +interface Scenario { + readonly name: string; + readonly space: OrchestrationV2ThreadSpace; + readonly sentBy: "agent" | "user"; + readonly status: "completed" | "failed"; + readonly duringTurn?: "visit"; + readonly afterTurn?: "visit" | "move to Development"; + readonly snoozed: boolean; +} + +it.effect.each([ + { + name: "a quiet bot turn", + space: "automation", + sentBy: "agent", + status: "completed", + snoozed: true, + }, + { + name: "a Development thread", + space: "development", + sentBy: "agent", + status: "completed", + snoozed: false, + }, + { name: "a failed run", space: "automation", sentBy: "agent", status: "failed", snoozed: false }, + { + name: "a turn the user wrote", + space: "automation", + sentBy: "user", + status: "completed", + snoozed: false, + }, + { + name: "a turn someone watched", + space: "automation", + sentBy: "agent", + status: "completed", + duringTurn: "visit", + snoozed: false, + }, + { + // The client throttles visits, so a reader's visit for a short turn lands after it ends. + name: "a reader whose visit lands after the turn", + space: "automation", + sentBy: "agent", + status: "completed", + afterTurn: "visit", + snoozed: false, + }, + { + name: "a thread moved out while the grace runs", + space: "automation", + sentBy: "agent", + status: "completed", + afterTurn: "move to Development", + snoozed: false, + }, +])("snoozes after the turn: $name -> $snoozed", (scenario) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const reactor = yield* AutomationSnoozeReactor.AutomationSnoozeReactor; + const run = yield* startBotTurn(scenario.space, scenario.sentBy); + yield* TestClock.adjust("1 minute"); + if (scenario.duringTurn === "visit") yield* visit("visit-during-turn"); + yield* TestClock.adjust("5 minutes"); + const finished = yield* finishTurn(run, scenario.status); + + const reaction = yield* reactor.handle(finished).pipe(Effect.forkChild); + yield* TestClock.adjust("2 seconds"); + if (scenario.afterTurn === "visit") yield* visit("visit-after-turn"); + if (scenario.afterTurn === "move to Development") { + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("move-out"), + threadId, + space: "development", + }); + } + yield* TestClock.adjust("13 seconds"); + yield* Fiber.join(reaction); + + const shell = yield* projections.getThreadShell(threadId); + assert.equal( + shell?.snoozedUntil == null ? null : DateTime.formatIso(shell.snoozedUntil), + scenario.snoozed + ? DateTime.formatIso(DateTime.add(yield* DateTime.now, { days: 365 })) + : null, + ); + }).pipe(Effect.provide(layerTest)), +); + +it.effect.each(["nothing", "a visit", "a user message"] as const)( + "the auto-snooze command checks what happened after the reactor's read: %s", + (afterRead) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const run = yield* startBotTurn("automation", "agent"); + yield* TestClock.adjust("5 minutes"); + yield* finishTurn(run, "completed"); + const read = yield* projections.getThreadShell(threadId); + assert.ok(read); + + yield* TestClock.adjust("1 second"); + if (afterRead === "a visit") yield* visit("visit-after-read"); + if (afterRead === "a user message") { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("user-follow-up"), + threadId, + messageId: MessageId.make("message:user-follow-up"), + text: "One more thing", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + } + const snoozed = yield* orchestrator + .dispatch({ + type: "thread.auto-snooze", + commandId: CommandId.make("auto-snooze"), + threadId, + snapshotAt: read.updatedAt, + turnBeganAt: read.latestRunRequestedAt!, + snoozedUntil: DateTime.formatIso(DateTime.add(yield* DateTime.now, { days: 365 })), + }) + .pipe(Effect.exit); + + assert.equal(snoozed._tag, afterRead === "nothing" ? "Success" : "Failure"); + assert.equal( + (yield* projections.getThreadShell(threadId))?.snoozedUntil != null, + afterRead === "nothing", + ); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/orchestration-v2/AutomationSnoozeReactor.ts b/apps/server/src/orchestration-v2/AutomationSnoozeReactor.ts new file mode 100644 index 0000000000000..c69fd9052a393 --- /dev/null +++ b/apps/server/src/orchestration-v2/AutomationSnoozeReactor.ts @@ -0,0 +1,149 @@ +import { + CommandId, + orchestrationV2ThreadSpaceOf, + type OrchestrationV2AppThread, + type OrchestrationV2DomainEvent, + type OrchestrationV2ThreadShell, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import { forkParked } from "../serverActivation.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import { isSnoozed, threadHasQueuedTurnStart } from "./ThreadSettlementService.ts"; + +/** + * Renewed at each quiet turn end that finds the thread awake. A thread that stays + * snoozed keeps its deadline, so a busy bot thread surfaces about once a year; one + * that has been silent this long wakes once and can then auto-settle. + */ +const AUTOMATION_SNOOZE = Duration.days(365); + +/** + * Longer than the client's visit throttle (10 s): an open thread records a visit for + * its finished turn before the decision, so a thread on screen is never snoozed. + */ +const VISIT_GRACE = Duration.seconds(15); + +const atOrAfter = (value: DateTime.Utc | null | undefined, sinceMs: number) => + value != null && DateTime.toEpochMillis(value) >= sinceMs; + +/** + * The turn's start, when its finished turn should snooze the Automation thread; null + * otherwise. Bots run these threads, so the snooze keeps them out of every client's + * thread list, including mobile apps that do not know spaces. Approvals, new + * questions and failures wake it through the usual snooze rules. + */ +function automationSnoozeTurnBegan(input: { + readonly shell: OrchestrationV2ThreadShell; + readonly thread: Pick; + readonly completedRunId: string; + readonly nowMs: number; +}): DateTime.Utc | null { + const { shell, thread, nowMs } = input; + if (orchestrationV2ThreadSpaceOf(shell) !== "automation") return null; + if (shell.latestRunId !== input.completedRunId || shell.status !== "completed") return null; + if (shell.latestRunStopRequested === true || shell.activityRunStatus != null) return null; + if (shell.archivedAt !== null || shell.deletedAt !== null) return null; + if (shell.settledOverride === "settled" || shell.pinnedAt != null) return null; + // Waits on the user: an approval, a question, a guest, or a plan to accept. + if (shell.pendingRuntimeRequest !== null || (shell.pendingGuestMessageCount ?? 0) > 0) { + return null; + } + if (shell.interactionMode === "plan" && shell.hasActionableProposedPlan) return null; + if (threadHasQueuedTurnStart(shell, nowMs)) return null; + // Keeps a snooze someone chose, and the snoozedAt that question wakes compare against. + if (isSnoozed(shell, nowMs)) return null; + const turnBegan = shell.latestRunRequestedAt ?? shell.latestRunStartedAt; + if (turnBegan == null) return null; + // Anyone who opened, woke or wrote to the thread since the turn began is using it. + const turnBeganMs = DateTime.toEpochMillis(turnBegan); + const touched = [ + shell.lastVisitedAt, + thread.lastSnoozeWakeAt, + shell.latestUserAuthoredMessageAt, + ].some((interactedAt) => atOrAfter(interactedAt, turnBeganMs)); + return touched ? null : turnBegan; +} + +const isCompletedRun = (event: OrchestrationV2DomainEvent) => + event.type === "run.updated" && event.payload.status === "completed"; + +export class AutomationSnoozeReactor extends Context.Service< + AutomationSnoozeReactor, + { + readonly start: () => Effect.Effect; + /** Waits out the visit grace, then snoozes the thread if its finished turn was quiet. */ + readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect; + } +>()("t3/orchestration-v2/AutomationSnoozeReactor") {} + +const make = Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + + const handle: AutomationSnoozeReactor["Service"]["handle"] = Effect.fn( + "AutomationSnoozeReactor.handle", + )( + function* (event) { + if (event.type !== "run.updated" || event.payload.status !== "completed") return; + const before = yield* projections.getThreadShell(event.threadId); + if (before === null || orchestrationV2ThreadSpaceOf(before) !== "automation") return; + yield* Effect.sleep(VISIT_GRACE); + const shell = yield* projections.getThreadShell(event.threadId); + if (shell === null) return; + const thread = yield* projections.getThread(event.threadId); + const now = yield* DateTime.now; + const turnBeganAt = automationSnoozeTurnBegan({ + shell, + thread, + completedRunId: event.payload.id, + nowMs: DateTime.toEpochMillis(now), + }); + if (turnBeganAt === null) return; + yield* engine.dispatch({ + type: "thread.auto-snooze", + commandId: CommandId.make(`server:automation-snooze:${event.payload.id}`), + threadId: event.threadId, + snapshotAt: shell.updatedAt, + turnBeganAt, + snoozedUntil: DateTime.formatIso(DateTime.addDuration(now, AUTOMATION_SNOOZE)), + }); + }, + (effect, event) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logWarning("snoozing a finished Automation thread failed", { + threadId: event.threadId, + cause, + }), + ), + ), + ); + + const start: AutomationSnoozeReactor["Service"]["start"] = Effect.fn( + "AutomationSnoozeReactor.start", + )(function* () { + const scope = yield* Effect.scope; + yield* forkParked( + Stream.runForEach(Stream.filter(engine.streamDomainEvents, isCompletedRun), (event) => + // Each finished turn waits out its own grace without holding up the next event. + Effect.forkIn(handle(event), scope), + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Automation snooze event stream failed", { cause }), + ), + ), + ); + }); + + return { start, handle } satisfies AutomationSnoozeReactor["Service"]; +}); + +export const layer = Layer.effect(AutomationSnoozeReactor, make); diff --git a/apps/server/src/orchestration-v2/Orchestrator.space.test.ts b/apps/server/src/orchestration-v2/Orchestrator.space.test.ts index a18b239c03332..deb69d3b4749e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.space.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.space.test.ts @@ -1,6 +1,8 @@ import { assert, it } from "@effect/vitest"; import { CommandId, + type OrchestrationV2ThreadSpace, + orchestrationV2ThreadSpaceOf, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -38,7 +40,7 @@ const layerTest = Layer.mergeAll( ), ); -const createThread = (threadId: ThreadId, space?: "development" | "support") => +const createThread = (threadId: ThreadId, space?: OrchestrationV2ThreadSpace) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; yield* orchestrator.dispatch({ @@ -68,10 +70,10 @@ it.effect("creates a thread in the requested space and moves it without reorderi const created = yield* projections.getThreadShell(threadId); assert.ok(created); assert.equal(created.space, "support"); - const listedSpace = Effect.map( - projections.listActiveThreads(), - (entries) => entries.find((entry) => entry.id === threadId)?.space, - ); + const listedSpace = Effect.map(projections.listActiveThreads(), (entries) => { + const entry = entries.find((candidate) => candidate.id === threadId); + return entry === undefined ? undefined : orchestrationV2ThreadSpaceOf(entry); + }); assert.equal(yield* listedSpace, "support"); yield* TestClock.adjust("1 minute"); @@ -90,6 +92,22 @@ it.effect("creates a thread in the requested space and moves it without reorderi DateTime.toEpochMillis(moved.updatedAt), DateTime.toEpochMillis(created.updatedAt), ); + + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("move-to-automation"), + threadId, + space: "automation", + }); + const automated = yield* projections.getThreadShell(threadId); + assert.ok(automated); + assert.equal(orchestrationV2ThreadSpaceOf(automated), "automation"); + assert.equal(automated.space, undefined); + assert.equal(yield* listedSpace, "automation"); + assert.equal( + DateTime.toEpochMillis(automated.updatedAt), + DateTime.toEpochMillis(created.updatedAt), + ); }).pipe(Effect.provide(layerTest)), ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index efbc384b22c45..98e3a3228419f 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -28,6 +28,8 @@ import { type GuestMessageId, isCompactionCommandMessage, isOrchestrationV2WorkActive, + orchestrationV2ThreadSpaceFields, + orchestrationV2ThreadSpaceOf, isProviderNativeSubagentThread, MessageId, type NodeId, @@ -643,6 +645,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "thread.guest-message.dismiss": case "thread.settle": case "thread.auto-settle": + case "thread.auto-snooze": case "thread.unsettle": case "thread.snooze": case "thread.unsnooze": @@ -3803,7 +3806,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio interactionMode: command.interactionMode, branch: command.branch, worktreePath: command.worktreePath, - ...(command.space === undefined ? {} : { space: command.space }), + ...(command.space === undefined ? {} : orchestrationV2ThreadSpaceFields(command.space)), activeProviderThreadId: null, pullRequests: [], ...(command.linkOrigin === undefined ? {} : { linkOrigin: command.linkOrigin }), @@ -4916,7 +4919,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : command.regenerateTitle === false || command.title !== undefined ? { titleRegeneration: null } : {}), - ...(command.space === undefined ? {} : { space: command.space }), + ...(command.space === undefined ? {} : orchestrationV2ThreadSpaceFields(command.space)), // Moving between spaces is organization, not activity: a move on its // own keeps updatedAt so the thread does not jump to the top of a space. updatedAt: isSpaceOnlyMetadataUpdate(command) ? thread.updatedAt : now, @@ -15013,6 +15016,44 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); break; } + case "thread.auto-snooze": { + // Recheck live state: anything the user did since the reactor's read wins over the snooze. + const thread = yield* projectionStore + .getThread(command.threadId) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + const turnBeganMs = DateTime.toEpochMillis(command.turnBeganAt); + const touchedSinceTurnBegan = [thread.lastVisitedAt, thread.lastSnoozeWakeAt].some( + (at) => at != null && DateTime.toEpochMillis(at) >= turnBeganMs, + ); + if ( + orchestrationV2ThreadSpaceOf(thread) !== "automation" || + thread.settledOverride === "settled" || + thread.pinnedAt != null || + touchedSinceTurnBegan || + DateTime.toEpochMillis(thread.updatedAt) > DateTime.toEpochMillis(command.snapshotAt) + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Thread ${command.threadId} changed before the automatic snooze.`, + }); + } + yield* dispatchThreadMutation( + { + type: "thread.snooze", + commandId: command.commandId, + threadId: command.threadId, + snoozedUntil: command.snoozedUntil, + }, + events, + effects, + ); + break; + } case "thread.delete": { const now = yield* DateTime.now; const planDeletion = Effect.fn("Orchestrator.planDeletion")(function* ( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index ec13411bc967c..4e9251cd47643 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -493,6 +493,7 @@ export type ActiveThreadListEntry = Pick< | "settledAt" | "snoozedUntil" | "space" + | "addedSpace" | "updatedAt" >; @@ -1877,6 +1878,9 @@ export function threadShellFromProjection( autoSettleDisabledAt: projection.thread.autoSettleDisabledAt ?? null, ...(projection.thread.space === undefined ? {} : { space: projection.thread.space }), + ...(projection.thread.addedSpace === undefined + ? {} + : { addedSpace: projection.thread.addedSpace }), pinOrderKey: projection.thread.pinOrderKey ?? null, ...(projection.thread.tags?.length ? { tags: projection.thread.tags } : {}), lastVisitedAt: projection.thread.lastVisitedAt, @@ -2175,6 +2179,9 @@ function shellFromState(input: { autoSettleDisabledAt: input.state.thread.autoSettleDisabledAt ?? null, ...(input.state.thread.space === undefined ? {} : { space: input.state.thread.space }), + ...(input.state.thread.addedSpace === undefined + ? {} + : { addedSpace: input.state.thread.addedSpace }), pinOrderKey: input.state.thread.pinOrderKey ?? null, ...(input.state.thread.tags?.length ? { tags: input.state.thread.tags } : {}), lastVisitedAt: input.state.thread.lastVisitedAt, @@ -9060,6 +9067,7 @@ export const layer: Layer.Layer = readonly settled_at: string | null; readonly snoozed_until: string | null; readonly space: string | null; + readonly added_space: string | null; }>` SELECT t.thread_id, @@ -9076,7 +9084,8 @@ export const layer: Layer.Layer = json_extract(t.payload_json, '$.settledOverride') AS settled_override, json_extract(t.payload_json, '$.settledAt') AS settled_at, json_extract(t.payload_json, '$.snoozedUntil') AS snoozed_until, - json_extract(t.payload_json, '$.space') AS space + json_extract(t.payload_json, '$.space') AS space, + json_extract(t.payload_json, '$.addedSpace') AS added_space FROM orchestration_v2_projection_threads t WHERE t.deleted_at IS NULL AND t.archived_at IS NULL${projectId === undefined ? sql`` : sql` AND t.project_id = ${projectId}`} @@ -9102,6 +9111,7 @@ export const layer: Layer.Layer = settledAt: row.settled_at === null ? null : DateTime.makeUnsafe(row.settled_at), snoozedUntil: row.snoozed_until === null ? null : DateTime.makeUnsafe(row.snoozed_until), ...(row.space === "support" || row.space === "development" ? { space: row.space } : {}), + ...(row.added_space === "automation" ? { addedSpace: row.added_space } : {}), updatedAt: DateTime.makeUnsafe(row.updated_at), })); }, Effect.mapError(shellSnapshotReadError)); diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 0d428e1a6e1e0..8a1a8497a24a4 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -146,6 +146,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray config.environment.capabilities.threadSpaces) - ) { + // The same spaces the sidebar switch offers, so the palette cannot strand you either. + const switchableSpaces = switchableThreadSpaces(serverConfigs.values(), sidebarSpace); + for (const space of switchableSpaces) { + if (space === sidebarSpace) continue; actionItems.push({ kind: "action", - value: "action:switch-thread-space", - searchTerms: ["dev support", "support", "development", "space", "switch", "tickets"], - title: `Switch to ${THREAD_SPACE_LABELS[otherThreadSpace(sidebarSpace)]}`, + value: `action:switch-thread-space:${space}`, + searchTerms: [THREAD_SPACE_LABELS[space].toLowerCase(), space, "space", "switch"], + title: `Switch to ${THREAD_SPACE_LABELS[space]}`, icon: , run: async () => { - setSidebarSpace(otherThreadSpace(sidebarSpace)); + setSidebarSpace(space); }, }); + } + if (switchableSpaces.includes("support")) { actionItems.push({ kind: "action", value: "action:start-from-ticket", diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index dbdec94418808..361df96e7ff2b 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -181,6 +181,7 @@ import { ProjectRowActions } from "./ProjectComboboxRow"; import { buildDraftActionMenuItems, buildThreadActionMenuItems, + threadActionMoveTarget, threadActionRequiresOperate, } from "./threadActionMenu.logic"; import { @@ -261,7 +262,7 @@ import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar"; import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; import { SidebarUsageSummary } from "./sidebar/SidebarUsageSummary"; import { SidebarSpaceSwitch } from "./sidebar/SidebarSpaceSwitch"; -import { otherThreadSpace, threadSpaceOf, useSidebarSpace } from "../threadSpace"; +import { environmentThreadSpaces, threadSpaceOf, useSidebarSpace } from "../threadSpace"; import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader"; import { SidebarEnvironmentFilter } from "./sidebar/SidebarEnvironmentFilter"; import { resolveSidebarScope } from "./Sidebar.scope"; @@ -2719,9 +2720,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve nativeThreadId: serverConfigs.get(thread.environmentId)?.environment.capabilities .nativeThreadId === true, - spaces: - serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSpaces === - true, + spaces: environmentThreadSpaces( + serverConfigs.get(thread.environmentId)?.environment.capabilities, + ), }, snoozePresets, }), @@ -2743,6 +2744,22 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (preset) attemptSnooze(threadRef, preset); return; } + const moveTo = threadActionMoveTarget(clicked.value); + if (moveTo !== null) { + if (moveTo === threadSpaceOf(thread)) return; + const result = await setThreadSpace(threadRef, moveTo); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Failed to move thread", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + return; + } switch (clicked.value) { case "filter-by-project": if (threadProjectGroup) { @@ -2854,20 +2871,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve case "mark-unread": markThreadUnread(threadRef); return; - case "move-space": { - const result = await setThreadSpace(threadRef, otherThreadSpace(threadSpaceOf(thread))); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Failed to move thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - return; - } case "copy-path": if (!threadWorkspacePath) { toastManager.add( diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 2ddb3211b9b5c..3a98fd57bb145 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -63,7 +63,7 @@ import { writeTextToClipboard } from "~/hooks/useCopyToClipboard"; import { newMessageId, newThreadId } from "~/lib/utils"; import { useNewThreadHandler } from "../../hooks/useHandleNewThread"; import { buildThreadRouteParams } from "../../threadRoutes"; -import { readSidebarSpace } from "../../threadSpace"; +import { environmentThreadSpaces, readSidebarSpace } from "../../threadSpace"; import { beginBackgroundDraftSubmissionByRef, clearBackgroundDraftSubmissionByRef, @@ -900,7 +900,14 @@ export function useComposerSend(input: ComposerSendInput) { }; sendInFlightRef.current = true; // Read before the uploads below: the sidebar can switch spaces while they run. - const threadSpaceForSend = readSidebarSpace(); + const sidebarSpace = readSidebarSpace(); + // A server without this space would reject it; the thread lands in Development there. + const threadSpaceForSend = environmentThreadSpaces( + appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment + .capabilities, + ).includes(sidebarSpace) + ? sidebarSpace + : undefined; const sendGeneration = ++composerSendGenerationRef.current; const attachmentCapabilitiesBeforeUpload = readLiveAttachmentCapabilities(); if (attachmentCapabilitiesBeforeUpload.fileBlockReason !== null) { @@ -1307,7 +1314,7 @@ export function useComposerSend(input: ComposerSendInput) { ? { createThread: { projectId: activeProject.id, - space: threadSpaceForSend, + ...(threadSpaceForSend === undefined ? {} : { space: threadSpaceForSend }), title, modelSelection: threadCreateModelSelection, runtimeMode, diff --git a/apps/web/src/components/chat/useMultipleModelSend.ts b/apps/web/src/components/chat/useMultipleModelSend.ts index 96b8bb5652947..ae9c0b548762b 100644 --- a/apps/web/src/components/chat/useMultipleModelSend.ts +++ b/apps/web/src/components/chat/useMultipleModelSend.ts @@ -103,7 +103,7 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { }: { readonly threadId: ThreadId; readonly project: EnvironmentProject; - readonly space: OrchestrationV2ThreadSpace; + readonly space: OrchestrationV2ThreadSpace | undefined; readonly branch: string; readonly selections: ReadonlyArray; readonly targets: ReadonlyArray; @@ -186,7 +186,7 @@ export function useMultipleModelSend(input: MultipleModelSendInput) { bootstrap: { createThread: { projectId: project.id, - space, + ...(space === undefined ? {} : { space }), title, modelSelection: target.selection, runtimeMode, diff --git a/apps/web/src/components/sidebar/SidebarSpaceSwitch.tsx b/apps/web/src/components/sidebar/SidebarSpaceSwitch.tsx index 469a9d992182f..df07aa997981e 100644 --- a/apps/web/src/components/sidebar/SidebarSpaceSwitch.tsx +++ b/apps/web/src/components/sidebar/SidebarSpaceSwitch.tsx @@ -1,41 +1,44 @@ -import type { OrchestrationV2ThreadSpace } from "@t3tools/contracts"; -import { TicketIcon } from "lucide-react"; +import { isOrchestrationV2ThreadSpace, type OrchestrationV2ThreadSpace } from "@t3tools/contracts"; +import { BotIcon, CodeIcon, type LucideIcon, TicketIcon } from "lucide-react"; import { memo } from "react"; import { useNowMinute } from "../../hooks/useNowMinute"; import { cn } from "../../lib/utils"; import { useDelegatedUnderParent, useServerConfigs, useThreadShells } from "../../state/entities"; -import { otherThreadSpace, THREAD_SPACE_LABELS, useSidebarSpace } from "../../threadSpace"; +import { switchableThreadSpaces, THREAD_SPACE_LABELS, useSidebarSpace } from "../../threadSpace"; import { useUiStateStore } from "../../uiStateStore"; import { openDevSupportTicketDialog } from "../DevSupportTicketDialog"; import { Button } from "../ui/button"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { resolveSpaceAttention, type SpaceAttention } from "./spaceAttention.logic"; -/** Switches the sidebar between the Development and Dev support thread spaces. */ +const SPACE_ICONS: Record = { + development: CodeIcon, + support: TicketIcon, + automation: BotIcon, +}; + +/** Switches the sidebar between thread spaces. */ export const SidebarSpaceSwitch = memo(function SidebarSpaceSwitch() { const space = useSidebarSpace(); const setSidebarSpace = useUiStateStore((state) => state.setSidebarSpace); - const serverConfigs = useServerConfigs(); - const supported = [...serverConfigs.values()].some( - (config) => config.environment.capabilities.threadSpaces === true, - ); - // Keep the switch while the support view is open, so it cannot strand the - // user there if the capability disappears (e.g. a downgraded server). - if (!supported && space === "development") return null; + const shown = switchableThreadSpaces(useServerConfigs().values(), space); + if (shown.length === 0) return null; return (
{ const value = next[0]; - if (value === "development" || value === "support") setSidebarSpace(value); + if (isOrchestrationV2ThreadSpace(value)) setSidebarSpace(value); }} > - - + {shown.map((candidate) => ( + + ))} {space === "support" ? (