From 9a904f949856a7e43fa6697b8e98e6b9b17b0ea1 Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Sun, 22 Nov 2026 04:27:29 +0000 Subject: [PATCH 01/13] feat(server): a board task marker escapes its ids and reads back to its task Board and task ids are percent-encoded in the marker, so board a:b with task c and board a with task b:c no longer share a marker, a create command and a thread. Plain ids keep the spelling #186 wrote. boardTaskOfMarker resolves a thread's marker to its task, one way only; boardTaskThreadId names the one thread a task is created as. Co-Authored-By: Claude Fable 5.2 --- .../src/delivery/boardThreadMarker.test.ts | 57 ++++++++++++++++++- apps/server/src/delivery/boardThreadMarker.ts | 44 ++++++++++++-- 2 files changed, 95 insertions(+), 6 deletions(-) diff --git a/apps/server/src/delivery/boardThreadMarker.test.ts b/apps/server/src/delivery/boardThreadMarker.test.ts index 0b2f8723ab980..d061f179947ed 100644 --- a/apps/server/src/delivery/boardThreadMarker.test.ts +++ b/apps/server/src/delivery/boardThreadMarker.test.ts @@ -4,7 +4,13 @@ import * as NodePath from "node:path"; import { assert, it } from "@effect/vitest"; -import { boardTaskThreadMarker } from "./boardThreadMarker.ts"; +import { + BOARD_TASK_MARKER_LIKE, + boardTaskOfMarker, + boardTaskThreadCommandId, + boardTaskThreadId, + boardTaskThreadMarker, +} from "./boardThreadMarker.ts"; // A board task's thread reuses `lineage.engineIntake` as its marker, with a value of its own. That // is safe only while every reader but the engine intake asks whether the field is set, never what @@ -83,3 +89,52 @@ it("nothing but the marker module knows what a board task's marker looks like", ["apps/server/src/delivery/boardThreadMarker.ts"], ); }); + +it("keeps a colon in a board or task id from making two tasks one marker", () => { + const pairs = [ + [ + { board: "a:b", id: "c" }, + { board: "a", id: "b:c" }, + ], + [ + { board: "a%3Ab", id: "c" }, + { board: "a:b", id: "c" }, + ], + [ + { board: "a", id: "b" }, + { board: "a:", id: "b" }, + ], + ] as const; + for (const [left, right] of pairs) { + assert.notEqual(boardTaskThreadMarker(left), boardTaskThreadMarker(right)); + assert.notEqual(boardTaskThreadCommandId(left), boardTaskThreadCommandId(right)); + assert.notEqual(boardTaskThreadId(left), boardTaskThreadId(right)); + } +}); + +it("reads the task back out of a marker, and nothing out of any other value", () => { + for (const task of [ + { board: "board-1", id: "task-7" }, + { board: "a:b", id: "c" }, + { board: "a", id: "b:c" }, + { board: "with/slash and space", id: "100%" }, + ]) { + assert.deepEqual(boardTaskOfMarker(boardTaskThreadMarker(task)), task); + } + for (const value of [ + null, + undefined, + "", + // An engine intake's admission. + `intake-${"a".repeat(64)}:0`, + BOARD_TASK_MARKER_LIKE, + `${BOARD_TASK_MARKER_LIKE.slice(0, -1)}only-a-board`, + `${BOARD_TASK_MARKER_LIKE.slice(0, -1)}a:b:c`, + `${BOARD_TASK_MARKER_LIKE.slice(0, -1)}:task`, + // Not the spelling the grammar writes, and a broken escape. + `${BOARD_TASK_MARKER_LIKE.slice(0, -1)}%61:b`, + `${BOARD_TASK_MARKER_LIKE.slice(0, -1)}%zz:b`, + ]) { + assert.equal(boardTaskOfMarker(value), null, String(value)); + } +}); diff --git a/apps/server/src/delivery/boardThreadMarker.ts b/apps/server/src/delivery/boardThreadMarker.ts index 857eb3f40308c..b3b4d72cd06b0 100644 --- a/apps/server/src/delivery/boardThreadMarker.ts +++ b/apps/server/src/delivery/boardThreadMarker.ts @@ -1,16 +1,50 @@ -import { CommandId } from "@t3tools/contracts"; +import { CommandId, ThreadId } from "@t3tools/contracts"; -interface BoardTask { +export interface BoardTask { readonly board: string; readonly id: string; } +const PREFIX = "board-task:"; + +// Each id is percent-encoded, so the colon that separates them can never come from an id: board +// `a:b` with task `c` and board `a` with task `b:c` are two markers. An id of letters, digits, +// `-` and `_` is spelled as it is, so the markers written before this grammar still read. +const part = (value: string) => encodeURIComponent(value); + /** - * The lineage marker of a board task's conversation: it keeps the thread out of every list. One - * way only. The engine holds a task's thread, and nothing reads a task back out of a marker. + * The lineage marker of a board task's conversation: it keeps the thread out of every list. It is + * stamped when the thread is created and never after. The engine holds a task's thread + * (`boardThread`); the marker only says which task a thread was made for. */ -export const boardTaskThreadMarker = (task: BoardTask) => `board-task:${task.board}:${task.id}`; +export const boardTaskThreadMarker = (task: BoardTask) => + `${PREFIX}${part(task.board)}:${part(task.id)}`; /** One create command per task, so starting a task twice makes one thread. */ export const boardTaskThreadCommandId = (task: BoardTask) => CommandId.make(`${boardTaskThreadMarker(task)}:thread`); + +/** The thread a task's conversation is created as: one id per task, on every start. */ +export const boardTaskThreadId = (task: BoardTask) => ThreadId.make(boardTaskThreadMarker(task)); + +/** Matches every board task marker in SQL `LIKE`, and nothing an engine intake stamps. */ +export const BOARD_TASK_MARKER_LIKE = `${PREFIX}%`; + +/** + * Thread to task, and never the other way: the task a marker was stamped for, or null for a value + * that is no board task marker (an engine intake's admission, or a spelling this grammar does not + * write). A task's thread is read from the engine, never found by building a marker. + */ +export function boardTaskOfMarker(marker: string | null | undefined): BoardTask | null { + if (typeof marker !== "string" || !marker.startsWith(PREFIX)) return null; + const parts = marker.slice(PREFIX.length).split(":"); + if (parts.length !== 2) return null; + try { + const [board, id] = parts.map((value) => decodeURIComponent(value)) as [string, string]; + if (board === "" || id === "") return null; + // Only the spelling the grammar writes resolves, so no two markers name one task. + return boardTaskThreadMarker({ board, id }) === marker ? { board, id } : null; + } catch { + return null; + } +} From 78a00095b2d3ad4906949e81ec467e28ac68325a Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Sun, 22 Nov 2026 04:42:49 +0000 Subject: [PATCH 02/13] feat(server): a started board task gets one thread, bound to the engine's link The server reads the engine's lanes on a beat. A task the engine shows in work with no boardThread gets one thread, created under the task's own command id and thread id with the marker stamped at creation, led by the seat the engine's team configuration names as its lead. The link is registered by the PUT route with setBy the environment and expect null; a conflict leaves the other writer's link standing and archives the thread made here. The task is claimed with the thread's origin and each pass is the heartbeat. No client starts any of this, and act refuses the link and claim routes. Tested against a scratch engine that models the frozen 6a contract. Co-Authored-By: Claude Fable 5.2 --- .../src/delivery/BoardTaskThreads.test.ts | 492 ++++++++++++++++++ apps/server/src/delivery/BoardTaskThreads.ts | 450 ++++++++++++++++ apps/server/src/delivery/DeliveryService.ts | 83 ++- .../src/delivery/boardThreadEngine.testkit.ts | 349 +++++++++++++ .../src/delivery/boardThreadMarker.test.ts | 41 +- apps/server/src/delivery/boardThreadRows.ts | 71 +++ apps/server/src/server.ts | 14 + 7 files changed, 1475 insertions(+), 25 deletions(-) create mode 100644 apps/server/src/delivery/BoardTaskThreads.test.ts create mode 100644 apps/server/src/delivery/BoardTaskThreads.ts create mode 100644 apps/server/src/delivery/boardThreadEngine.testkit.ts create mode 100644 apps/server/src/delivery/boardThreadRows.ts diff --git a/apps/server/src/delivery/BoardTaskThreads.test.ts b/apps/server/src/delivery/BoardTaskThreads.test.ts new file mode 100644 index 0000000000000..a15c2a44bb2bf --- /dev/null +++ b/apps/server/src/delivery/BoardTaskThreads.test.ts @@ -0,0 +1,492 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + EnvironmentId, + ProjectId, + ThreadId, + type OrchestrationV2ServerCommand, +} from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as ServerConfig from "../config.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; +import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as BoardTaskThreads from "./BoardTaskThreads.ts"; +import { + scratchEngine, + scratchEngineHttp, + type ScratchEngine, +} from "./boardThreadEngine.testkit.ts"; +import * as BoardThreadRows from "./boardThreadRows.ts"; +import { + boardTaskOfMarker, + boardTaskThreadCommandId, + boardTaskThreadId, +} from "./boardThreadMarker.ts"; +import * as DeliveryService from "./DeliveryService.ts"; + +// Every case here runs against the scratch engine of boardThreadEngine.testkit.ts, through the +// delivery service's real request path. None of it has run against the merged engine half. + +const ENVIRONMENT = EnvironmentId.make("471fea73-5365-4bbb-96eb-8e35be50eaec"); +const OTHER = "0d9b2f0e-other-environment"; +const REPO = "/work/repo"; +const PROJECT = ProjectId.make("project:repo"); +const TEAMS = [ + { + team: "development", + seats: [ + { seat: "developer", role: "lead-developer", harness: "claude", model: "claude-fable-5-1" }, + { seat: "lead", role: "team-lead", harness: "codex", model: "gpt-6-astra" }, + ], + }, +]; + +interface StoredThread { + readonly commandId: string; + readonly projectId: string; + readonly title: string; + readonly modelSelection: unknown; + readonly marker: string | undefined; + archivedAt: string | null; +} + +/** What the thread store keeps across a server restart: threads and command receipts. */ +function threadStore() { + const threads = new Map(); + const receipts = new Set(); + const commands: Array = []; + const hooks: { afterCreate: (() => void) | null } = { afterCreate: null }; + const dispatch = (command: OrchestrationV2ServerCommand) => + Effect.suspend(() => { + commands.push(command); + // A command already answered is answered again with what it did the first time. + if (receipts.has(command.commandId)) return Effect.succeed({ storedEvents: [] }); + if (command.type === "thread.create") { + if (threads.has(command.threadId)) + return Effect.fail(new BoardTaskThreads.BoardTaskThreadsError({ reason: "thread" })); + threads.set(command.threadId, { + commandId: command.commandId, + projectId: command.projectId, + title: command.title, + modelSelection: command.modelSelection, + marker: command.engineIntake, + archivedAt: null, + }); + receipts.add(command.commandId); + const after = hooks.afterCreate; + hooks.afterCreate = null; + after?.(); + } + if (command.type === "thread.archive") { + threads.get(command.threadId)!.archivedAt = "2026-11-22T11:00:00.000Z"; + receipts.add(command.commandId); + } + if (command.type === "thread.unarchive") { + threads.get(command.threadId)!.archivedAt = null; + receipts.add(command.commandId); + } + return Effect.succeed({ storedEvents: [] }); + }); + return { threads, commands, hooks, dispatch }; +} +type ThreadStore = ReturnType; + +const INSTANCES = [ + { instanceId: "codex", driverKind: "codex", enabled: true }, + { instanceId: "claudeAgent", driverKind: "claudeAgent", enabled: true }, +]; + +function service( + store: ThreadStore, + options: { + readonly key?: string | null; + readonly instances?: ReadonlyArray<(typeof INSTANCES)[number]>; + readonly projects?: ReadonlyArray; + } = {}, +) { + return BoardTaskThreads.make.pipe( + Effect.provideService( + HostProcess.Environment, + options.key === null + ? {} + : { + [BoardTaskThreads.BOARD_THREAD_KEY_VARIABLE]: + options.key ?? "scratch approval passphrase", + }, + ), + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(ENVIRONMENT), + }), + Effect.provideService(ThreadManagementService.ThreadManagementService, { + dispatch: store.dispatch, + } as unknown as ThreadManagementService.ThreadManagementService["Service"]), + Effect.provideService(ProjectionStore.ProjectionStoreV2, { + getThreadRecords: (threadId: string) => + Effect.succeed({ + thread: { lineage: { engineIntake: store.threads.get(threadId)?.marker } }, + }), + } as unknown as ProjectionStore.ProjectionStoreV2["Service"]), + Effect.provideService(ProjectStore.ProjectStoreV2, { + findActiveByWorkspaceRoot: (root: string) => + Effect.succeed( + (options.projects ?? [REPO]).includes(root) + ? Option.some({ projectId: PROJECT }) + : Option.none(), + ), + } as unknown as ProjectStore.ProjectStoreV2["Service"]), + Effect.provideService(ProviderInstanceRegistry.ProviderInstanceRegistry, { + listInstances: Effect.succeed(options.instances ?? INSTANCES), + } as unknown as ProviderInstanceRegistry.ProviderInstanceRegistry["Service"]), + Effect.provideService(BoardThreadRows.BoardThreadRows, { + list: ({ archived }: { readonly archived: boolean }) => + Effect.succeed( + [...store.threads].flatMap(([threadId, thread]) => { + const task = boardTaskOfMarker(thread.marker); + return task === null || (thread.archivedAt !== null) !== archived + ? [] + : [ + { + threadId: ThreadId.make(threadId), + projectId: PROJECT, + title: thread.title, + archivedAt: thread.archivedAt, + task, + }, + ]; + }), + ), + }), + ); +} + +/** The delivery service as the server runs it, with the scratch engine behind its HTTP client. */ +const deliveryLayer = (engine: ScratchEngine, prefix: string) => + Layer.fresh(DeliveryService.layer(deriveProviderInstanceConfigMap)).pipe( + Layer.provideMerge(Layer.succeed(HostProcess.Environment, {})), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix })), + Layer.provideMerge(NodeServices.layer), + Layer.provideMerge( + ServerSettings.layerTest({ + delivery: { enabled: true, engineUrl: "http://127.0.0.1:4320" }, + }), + ), + Layer.provideMerge(scratchEngineHttp(engine)), + ); + +function board(options: Parameters[0] = {}) { + const engine = scratchEngine(options); + engine.setBoard("work", REPO); + engine.setTeams(TEAMS); + return engine; +} + +const TASK = { board: "work", id: "task-7" }; +const THREAD = boardTaskThreadId(TASK); +const creates = (store: ThreadStore) => + store.commands.filter((command) => command.type === "thread.create"); +const linkWrites = (engine: ScratchEngine) => + engine.events.filter((event) => event.kind === "task.board-thread-set"); + +it.effect("gives a started task one thread, led as the engine's team says, and links it", () => { + const engine = board(); + engine.addTask({ id: "task-7", title: "Ship the thing" }); + engine.addTask({ id: "draft-1", lane: "draft", state: "draft", submitted: false }); + engine.addTask({ id: "queued-1", lane: "queue", state: "ready" }); + engine.addTask({ id: "done-1", lane: "completed", state: "completed" }); + const store = threadStore(); + return Effect.gen(function* () { + const threads = yield* service(store); + assert.deepEqual([...(yield* threads.reconcile())], []); + // Only the task the engine says is in work has a thread. + assert.deepEqual([...store.threads.keys()], [THREAD]); + const [create] = creates(store); + assert.equal(create?.type, "thread.create"); + if (create?.type !== "thread.create") return; + assert.equal(create.commandId, boardTaskThreadCommandId(TASK)); + assert.equal(create.projectId, PROJECT); + assert.equal(create.title, "Ship the thing"); + assert.deepEqual(boardTaskOfMarker(create.engineIntake), TASK); + // The lead is the seat the engine's team names as its lead, on that seat's harness and model. + assert.deepEqual({ ...create.modelSelection }, { instanceId: "codex", model: "gpt-6-astra" }); + const link = engine.linkOf("task-7"); + assert.deepEqual( + { environmentId: link?.environmentId, threadId: link?.threadId, setBy: link?.setBy }, + { environmentId: ENVIRONMENT, threadId: THREAD, setBy: ENVIRONMENT }, + ); + const put = engine.requests.find((request) => request.method === "PUT"); + assert.deepInclude(put?.body, { expect: null }); + // The claim names the conversation that holds the task, and the next pass is its heartbeat. + assert.equal(engine.leaseOf("task-7")?.origin, `thread:${ENVIRONMENT}/${THREAD}`); + engine.advance(100_000); + yield* threads.reconcile(); + engine.advance(100_000); + assert.isNotNull(engine.leaseOf("task-7")); + // A second pass made nothing new and wrote nothing new. + assert.equal(creates(store).length, 1); + assert.equal(linkWrites(engine).length, 1); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-create-"))); +}); + +it.effect("makes one thread when a task is started twice and by two servers at once", () => { + const engine = board(); + engine.addTask({ id: "task-7" }); + const store = threadStore(); + return Effect.gen(function* () { + const first = yield* service(store); + const second = yield* service(store); + yield* Effect.all( + [first.reconcile(), first.reconcile(), second.reconcile(), second.reconcile()], + { concurrency: "unbounded" }, + ); + assert.deepEqual([...store.threads.keys()], [THREAD]); + assert.equal(linkWrites(engine).length, 1); + assert.equal(engine.linkOf("task-7")?.threadId, THREAD); + assert.isNull(store.threads.get(THREAD)!.archivedAt); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-double-"))); +}); + +it.effect("finishes the link after a restart between the create and the engine write", () => { + const engine = board(); + engine.addTask({ id: "task-7" }); + const store = threadStore(); + return Effect.gen(function* () { + // The server stops answering right after the thread exists: the link is never written. + store.hooks.afterCreate = () => engine.setDown(true); + const before = yield* service(store); + const failed = yield* before.reconcile().pipe(Effect.result); + assert.equal(failed._tag, "Failure"); + assert.deepEqual([...store.threads.keys()], [THREAD]); + assert.isNull(engine.linkOf("task-7")); + // A new server process: nothing in memory, the same stored thread and receipts. + engine.setDown(false); + const after = yield* service(store); + yield* after.reconcile(); + assert.deepEqual([...store.threads.keys()], [THREAD]); + assert.equal(creates(store).length, 2); + assert.equal(engine.linkOf("task-7")?.threadId, THREAD); + assert.equal(linkWrites(engine).length, 1); + // The claim of the process that died lapses, and the same thread holds the task again. + engine.advance(121_000); + yield* after.reconcile(); + assert.equal(engine.leaseOf("task-7")?.origin, `thread:${ENVIRONMENT}/${THREAD}`); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-restart-"))); +}); + +it.effect("adopts the link another writer set first and never overwrites it", () => { + const engine = board(); + engine.addTask({ id: "task-7" }); + const store = threadStore(); + return Effect.gen(function* () { + engine.beforeNextPut(() => { + engine.writeLink("task-7", { environmentId: OTHER, threadId: "their-thread", setBy: OTHER }); + }); + const threads = yield* service(store); + yield* threads.reconcile(); + assert.equal(engine.linkOf("task-7")?.threadId, "their-thread"); + assert.equal(engine.linkOf("task-7")?.setBy, OTHER); + // The thread made here holds no task: it is archived, not deleted, and claims nothing. + assert.isNotNull(store.threads.get(THREAD)!.archivedAt); + assert.isNull(engine.leaseOf("task-7")); + yield* threads.reconcile(); + assert.equal(engine.linkOf("task-7")?.threadId, "their-thread"); + assert.equal(linkWrites(engine).length, 1); + assert.equal(engine.requests.filter((request) => request.method === "PUT").length, 1); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-conflict-"))); +}); + +it.effect("makes no thread for a moved task, and archives one the engine refuses as moved", () => { + const engine = board(); + engine.addTask({ id: "moved-1", state: "moved" }); + engine.addTask({ id: "task-7" }); + const store = threadStore(); + return Effect.gen(function* () { + // The task moves to another machine after the lanes were read and before the link is written. + store.hooks.afterCreate = () => { + engine.task("task-7").state = "moved"; + }; + const threads = yield* service(store); + const holds = yield* threads.reconcile(); + assert.deepEqual([...holds], [["task-7", "moved"]]); + assert.deepEqual([...store.threads.keys()], [THREAD]); + assert.isNotNull(store.threads.get(THREAD)!.archivedAt); + assert.isNull(engine.linkOf("task-7")); + assert.isNull(engine.leaseOf("task-7")); + // The task that had already moved was never given a thread or a write. + assert.isFalse(engine.requests.some((request) => request.path.includes("moved-1"))); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-moved-"))); +}); + +it.effect("keeps two tasks apart when a board id carries the separator", () => { + const engine = board(); + engine.setBoard("team:alpha", REPO); + engine.setBoard("team", REPO); + engine.addTask({ id: "t1", set: "team:alpha" }); + engine.addTask({ id: "alpha-t1", set: "team" }); + const store = threadStore(); + return Effect.gen(function* () { + const threads = yield* service(store); + assert.deepEqual([...(yield* threads.reconcile())], []); + const first = boardTaskThreadId({ board: "team:alpha", id: "t1" }); + const second = boardTaskThreadId({ board: "team", id: "alpha-t1" }); + assert.notEqual(first, second); + assert.deepEqual([...store.threads.keys()].toSorted(), [first, second].toSorted()); + // The engine takes a thread id with a colon and a percent sign as it is. + assert.equal(engine.linkOf("t1")?.threadId, first); + assert.equal(engine.linkOf("alpha-t1")?.threadId, second); + assert.deepEqual(boardTaskOfMarker(store.threads.get(first)!.marker), { + board: "team:alpha", + id: "t1", + }); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-colon-"))); +}); + +it.effect("says why a started task has no thread instead of falling back to a default", () => { + const cases = [ + { + hold: "no-lead", + teams: [{ team: "development", seats: [{ seat: "qa", role: "qa", harness: "kimi" }] }], + }, + { + hold: "no-lead-model", + teams: [ + { team: "development", seats: [{ seat: "lead", role: "team-lead", harness: "codex" }] }, + ], + }, + { + hold: "no-provider", + teams: [ + { + team: "development", + seats: [{ seat: "lead", role: "team-lead", harness: "hermes", model: "m" }], + }, + ], + }, + { + hold: "ambiguous-provider", + instances: [ + { instanceId: "codex-work", driverKind: "codex", enabled: true }, + { instanceId: "codex-home", driverKind: "codex", enabled: true }, + ], + }, + { hold: "no-project", projects: [] }, + ] as const; + return Effect.forEach(cases, (entry) => { + const engine = board(); + engine.addTask({ id: "task-7" }); + if ("teams" in entry) engine.setTeams(entry.teams); + const store = threadStore(); + return Effect.gen(function* () { + const threads = yield* service(store, { + ...("instances" in entry ? { instances: entry.instances } : {}), + ...("projects" in entry ? { projects: entry.projects } : {}), + }); + assert.deepEqual([...(yield* threads.reconcile())], [["task-7", entry.hold]]); + assert.equal(store.threads.size, 0); + assert.isNull(engine.linkOf("task-7")); + }).pipe(Effect.provide(deliveryLayer(engine, `board-threads-${entry.hold}-`))); + }); +}); + +it.effect("writes no link without the approval key, and none on a wrong one", () => { + const engine = board(); + engine.addTask({ id: "task-7" }); + const store = threadStore(); + return Effect.gen(function* () { + const keyless = yield* service(store, { key: null }); + assert.deepEqual([...(yield* keyless.reconcile())], [["task-7", "no-key"]]); + // Nothing is sent: a keyless write would count against a person's approval attempts. + assert.isFalse(engine.requests.some((request) => request.method === "PUT")); + const wrong = yield* service(store, { key: "not the passphrase" }); + assert.deepEqual([...(yield* wrong.reconcile())], [["task-7", "refused"]]); + assert.isNull(engine.linkOf("task-7")); + assert.isNull(store.threads.get(THREAD)!.archivedAt); + const keyed = yield* service(store); + assert.deepEqual([...(yield* keyed.reconcile())], []); + assert.equal(engine.linkOf("task-7")?.threadId, THREAD); + assert.equal(store.threads.size, 1); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-key-"))); +}); + +it.effect( + "archives the thread of a task that was deleted, and leaves a finished task's open", + () => { + const engine = board(); + engine.addTask({ id: "task-7" }); + engine.addTask({ id: "task-8" }); + const store = threadStore(); + return Effect.gen(function* () { + const threads = yield* service(store); + yield* threads.reconcile(); + const finished = boardTaskThreadId({ board: "work", id: "task-8" }); + engine.task("task-8").lane = "completed"; + engine.task("task-8").state = "completed"; + engine.removeTask("task-7"); + yield* threads.reconcile(); + assert.isNotNull(store.threads.get(THREAD)!.archivedAt); + // A finished task keeps its conversation where the task view reads it; its slot is freed. + assert.isNull(store.threads.get(finished)!.archivedAt); + assert.equal(engine.linkOf("task-8")?.threadId, finished); + assert.isNull(engine.leaseOf("task-8")); + // A person restored the archived thread from the board: it is not archived a second time. + store.threads.get(THREAD)!.archivedAt = null; + yield* threads.reconcile(); + assert.isNull(store.threads.get(THREAD)!.archivedAt); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-ended-"))); + }, +); + +it.effect("makes nothing on an engine that serves no board thread link", () => { + const engine = board({ servesLink: false }); + engine.addTask({ id: "task-7" }); + const store = threadStore(); + return Effect.gen(function* () { + const threads = yield* service(store); + assert.deepEqual([...(yield* threads.reconcile())], []); + assert.equal(store.threads.size, 0); + assert.deepEqual( + engine.requests.map((request) => request.method), + ["GET"], + ); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-old-engine-"))); +}); + +it.effect("keeps the link and claim routes for the server: a client's act is refused", () => { + const engine = board(); + engine.addTask({ id: "task-7" }); + return Effect.gen(function* () { + const delivery = yield* DeliveryService.DeliveryService; + for (const path of [ + "/api/tasks/task-7/board-thread", + "/api/orchestration/tasks/task-7/claim", + "/api/orchestration/tasks/task-7/release", + ]) { + const refused = yield* delivery.act({ path, body: { key: engine.key } }).pipe(Effect.result); + assert.equal(refused._tag, "Failure"); + } + assert.deepEqual(engine.requests, []); + // The server's own clear is answered 204 with no body, whether or not a link was set. + const cleared = yield* delivery.boardThreadAct({ + method: "DELETE", + path: "/api/tasks/task-7/board-thread", + body: { key: engine.key, setBy: ENVIRONMENT }, + }); + assert.isNull(cleared.body); + const unknown = yield* delivery + .boardThreadAct({ + method: "DELETE", + path: "/api/tasks/no-such-task/board-thread", + body: { key: engine.key, setBy: ENVIRONMENT }, + }) + .pipe(Effect.result); + assert.equal(unknown._tag === "Failure" ? unknown.failure.status : null, 404); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-act-"))); +}); diff --git a/apps/server/src/delivery/BoardTaskThreads.ts b/apps/server/src/delivery/BoardTaskThreads.ts new file mode 100644 index 0000000000000..81e68bf43d9f6 --- /dev/null +++ b/apps/server/src/delivery/BoardTaskThreads.ts @@ -0,0 +1,450 @@ +// A board task's conversation, made by the server once the engine shows the task in work. Engine +// facts only: its lanes say what started and which thread each task holds, its teams say who +// leads. This never starts a task, and no client asks it to make a thread. +import { + DELIVERY_HARNESS_BY_DRIVER, + CommandId, + type DeliveryError, + ModelSelection, + type EnvironmentId, + type ThreadId, +} from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +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 Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; +import type * as Scope from "effect/Scope"; + +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as BoardThreadRows from "./boardThreadRows.ts"; +import { + boardTaskOfMarker, + boardTaskThreadCommandId, + boardTaskThreadId, + boardTaskThreadMarker, + type BoardTask, +} from "./boardThreadMarker.ts"; +import * as DeliveryService from "./DeliveryService.ts"; + +/** The engine's `boardThread` (spec 6a). The field names are the engine's and are not renamed. */ +const BoardThread = Schema.Struct({ + environmentId: Schema.String, + threadId: Schema.String, + setBy: Schema.String, + setAt: Schema.String, +}); +type BoardThread = typeof BoardThread.Type; + +const Card = Schema.Struct({ + id: Schema.String, + title: Schema.String, + team: Schema.String, + lane: Schema.String, + state: Schema.String, + set: Schema.optional(Schema.NullOr(Schema.String)), + // Absent on an engine without the link: such an engine is never written to. + boardThread: Schema.optional(Schema.NullOr(BoardThread)), +}); +type Card = typeof Card.Type; + +const Lanes = Schema.Struct({ + lanes: Schema.Array(Schema.Struct({ lane: Schema.String, cards: Schema.Array(Card) })), + sets: Schema.Array( + Schema.Struct({ + id: Schema.String, + target: Schema.optional( + Schema.NullOr(Schema.Struct({ path: Schema.optional(Schema.NullOr(Schema.String)) })), + ), + }), + ), +}); +const Teams = Schema.Array( + Schema.Struct({ + team: Schema.String, + seats: Schema.Array( + Schema.Struct({ + seat: Schema.String, + role: Schema.optional(Schema.NullOr(Schema.String)), + harness: Schema.String, + model: Schema.optional(Schema.NullOr(Schema.String)), + }), + ), + }), +); +/** What a refusal of the link routes carries: a stable code, and on a conflict the value held. */ +const Refusal = Schema.Struct({ + code: Schema.optional(Schema.String), + current: Schema.optional(Schema.NullOr(BoardThread)), +}); +const Linked = Schema.Struct({ boardThread: BoardThread }); +const Claimed = Schema.Struct({ holder: Schema.String }); + +const decodeLanes = Schema.decodeUnknownEffect(Lanes); +const decodeTeams = Schema.decodeUnknownEffect(Teams); +const decodeRefusal = Schema.decodeUnknownOption(Refusal); +const decodeLinked = Schema.decodeUnknownEffect(Linked); +const decodeClaimed = Schema.decodeUnknownOption(Claimed); +const decodeSelection = Schema.decodeUnknownEffect(ModelSelection); + +/** Every task of every board, with each card's link joined once by the engine. */ +const LANES_PATH = "/api/lanes?view=development&set=all"; + +// A task in one of these lanes has not started or is not a task run: it has no conversation yet. +// `intake` and `ready` are what an engine before the queue lane calls the same wait. +const NOT_STARTED = new Set(["draft", "chat", "queue", "intake", "ready"]); +// Finished work keeps the conversation it had and is given none anew. +const FINISHED = new Set(["completed", "closed-not-done"]); +// A task that moved is worked on another machine; the engine refuses its link here (`moved`). +const MOVED = new Set(["moved", "moving"]); + +/** + * The engine's approval key, when the host gives this server one. The link routes are keyed + * (spec 6a) and a server holds no person's passphrase, so without this the link is not written. + */ +export const BOARD_THREAD_KEY_VARIABLE = "T3_DELIVERY_BOARD_THREAD_KEY"; + +/** Why a started task has no conversation of its own yet. Told in the log, never guessed around. */ +export type BoardThreadHold = + | "no-board" + | "no-project" + | "no-lead" + | "no-lead-model" + | "no-provider" + | "ambiguous-provider" + | "foreign-thread" + | "no-key" + | "refused" + | "moved"; + +export class BoardTaskThreadsError extends Schema.TaggedError()( + "BoardTaskThreadsError", + { + reason: Schema.Literals(["engine", "thread"]), + cause: Schema.optional(Schema.Defect()), + }, +) {} + +export class BoardTaskThreads extends Context.Service< + BoardTaskThreads, + { + /** One pass over the engine's lanes. Safe to repeat and to run twice at once. */ + readonly reconcile: () => Effect.Effect< + ReadonlyMap, + BoardTaskThreadsError + >; + readonly start: () => Effect.Effect; + } +>()("t3/delivery/BoardTaskThreads") {} + +const refusalOf = (error: DeliveryError) => { + const decoded = decodeRefusal(error.body); + return { + status: error.status ?? null, + code: Option.isSome(decoded) ? (decoded.value.code ?? null) : null, + current: Option.isSome(decoded) ? (decoded.value.current ?? null) : null, + }; +}; + +export const make = Effect.gen(function* () { + const settings = yield* ServerSettings.ServerSettingsService; + const delivery = yield* DeliveryService.DeliveryService; + const identity = yield* ServerEnvironment.ServerEnvironmentIdentity; + const threads = yield* ThreadManagementService.ThreadManagementService; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const projects = yield* ProjectStore.ProjectStoreV2; + const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; + const rows = yield* BoardThreadRows.BoardThreadRows; + const hostEnvironment = yield* HostProcess.Environment; + const lock = yield* Semaphore.make(1); + // The token of each claim this server holds. It is kept in memory only: after a restart the + // old lease lapses within its window and the task is claimed again, still by the same thread. + const holders = new Map(); + const told = new Map(); + + const engine = (effect: Effect.Effect) => + effect.pipe(Effect.mapError((cause) => new BoardTaskThreadsError({ reason: "engine", cause }))); + const local = (effect: Effect.Effect) => + effect.pipe(Effect.mapError((cause) => new BoardTaskThreadsError({ reason: "thread", cause }))); + + /** The lead's provider and model, from the engine's team configuration and nothing else. */ + const leadSelection = Effect.fn("BoardTaskThreads.leadSelection")(function* ( + team: (typeof Teams.Type)[number] | undefined, + ) { + const lead = + team?.seats.find((seat) => seat.role === "team-lead") ?? + team?.seats.find((seat) => seat.seat === "lead"); + if (lead === undefined) return "no-lead" as const; + if (!lead.model) return "no-lead-model" as const; + const candidates = (yield* instances.listInstances).filter( + (instance) => + instance.enabled && DELIVERY_HARNESS_BY_DRIVER[instance.driverKind] === lead.harness, + ); + // Two instances of one harness are two accounts: the engine names a harness, not an account, + // so only the driver's own default instance or a sole instance is the one it means. + const instance = + candidates.find( + (candidate) => String(candidate.instanceId) === String(candidate.driverKind), + ) ?? (candidates.length === 1 ? candidates[0] : undefined); + if (instance === undefined) { + return candidates.length === 0 ? ("no-provider" as const) : ("ambiguous-provider" as const); + } + return yield* local(decodeSelection({ instanceId: instance.instanceId, model: lead.model })); + }); + + const archive = (task: BoardTask, threadId: ThreadId, why: string) => + local( + threads.dispatch({ + type: "thread.archive", + commandId: CommandId.make(`${boardTaskThreadMarker(task)}:archive:${why}`), + threadId, + }), + ).pipe(Effect.asVoid); + + /** + * The claim of a task whose conversation is this server's, and its heartbeat. A refusal is the + * engine's answer (the cap is reached, the task is paused, another holder's lease still stands) + * and changes nothing here: the next pass asks again. + */ + const holdClaim = Effect.fn("BoardTaskThreads.holdClaim")(function* ( + card: Card, + environmentId: EnvironmentId, + threadId: string, + ) { + const path = `/api/orchestration/tasks/${card.id}`; + const held = holders.get(card.id); + if (held !== undefined) { + const renewed = yield* delivery + .boardThreadAct({ method: "POST", path: `${path}/ack`, body: { holder: held } }) + .pipe(Effect.result); + if (renewed._tag === "Success") return; + holders.delete(card.id); + } + const claimed = yield* delivery + .boardThreadAct({ + method: "POST", + path: `${path}/claim`, + body: { origin: `thread:${environmentId}/${threadId}`, by: environmentId }, + }) + .pipe(Effect.result); + if (claimed._tag !== "Success") return; + const decoded = decodeClaimed(claimed.success.body); + if (Option.isSome(decoded)) holders.set(card.id, decoded.value.holder); + }); + + const releaseClaim = Effect.fn("BoardTaskThreads.releaseClaim")(function* (taskId: string) { + const holder = holders.get(taskId); + if (holder === undefined) return; + holders.delete(taskId); + yield* delivery + .boardThreadAct({ + method: "POST", + path: `/api/orchestration/tasks/${taskId}/release`, + body: { holder }, + }) + .pipe(Effect.ignore); + }); + + /** A started task with no conversation: make its thread once, and tell the engine. */ + const bind = Effect.fn("BoardTaskThreads.bind")(function* ( + card: Card, + context: { + readonly environmentId: EnvironmentId; + readonly teams: typeof Teams.Type; + readonly folders: ReadonlyMap; + readonly key: string | undefined; + }, + ) { + if (!card.set) return "no-board" as const; + const task = { board: card.set, id: card.id }; + const threadId = boardTaskThreadId(task); + const folder = context.folders.get(card.set); + const project = + folder === undefined + ? Option.none() + : yield* local(projects.findActiveByWorkspaceRoot(folder)); + if (Option.isNone(project)) return "no-project" as const; + const modelSelection = yield* leadSelection( + context.teams.find((team) => team.team === card.team), + ); + if (typeof modelSelection === "string") return modelSelection; + // The command id is the task's, so a second start, a second server pass and a restart between + // this create and the link below all answer with the one thread. The marker is stamped here + // and by nothing later. + yield* local( + threads.dispatch({ + type: "thread.create", + commandId: boardTaskThreadCommandId(task), + threadId, + projectId: project.value.projectId, + title: card.title, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "system", + creationSource: "server", + engineIntake: boardTaskThreadMarker(task), + }), + ); + const created = yield* local(projections.getThreadRecords(threadId, [])); + const stamped = boardTaskOfMarker(created.thread.lineage.engineIntake); + if (stamped?.board !== task.board || stamped.id !== task.id) return "foreign-thread" as const; + if (context.key === undefined) return "no-key" as const; + const put = yield* delivery + .boardThreadAct({ + method: "PUT", + path: `/api/tasks/${card.id}/board-thread`, + body: { + environmentId: context.environmentId, + threadId, + setBy: context.environmentId, + // No link was set when the lanes were read. A writer in between is answered 409. + expect: null, + key: context.key, + }, + }) + .pipe(Effect.result); + if (put._tag === "Success") { + yield* engine(decodeLinked(put.success.body)); + yield* holdClaim(card, context.environmentId, threadId); + return null; + } + const refusal = refusalOf(put.failure); + if (refusal.code === "conflict") { + // Another writer set the link first. Its value stands and is never overwritten; the thread + // made here holds no task, so it is archived, where the board still reaches it. + const held = refusal.current; + if (held?.environmentId === context.environmentId && held.threadId === threadId) { + yield* holdClaim(card, context.environmentId, threadId); + return null; + } + yield* archive(task, threadId, "displaced"); + return null; + } + if (refusal.code === "moved") { + yield* archive(task, threadId, "moved"); + return "moved" as const; + } + if (refusal.code === "not-found") { + yield* archive(task, threadId, "deleted"); + return null; + } + if (refusal.code === "refused") return "refused" as const; + return yield* new BoardTaskThreadsError({ reason: "engine", cause: put.failure }); + }); + + /** + * The threads this server made whose task ended: deleted in the engine, or held by another + * conversation now. They are archived, never deleted, and the board lists them. + */ + const settleEnded = Effect.fn("BoardTaskThreads.settleEnded")(function* ( + cards: ReadonlyMap, + environmentId: EnvironmentId, + ) { + for (const row of yield* local(rows.list({ archived: false }))) { + const card = cards.get(row.task.id); + if (card === undefined) { + const read = yield* delivery + .read({ path: `/api/tasks/${row.task.id}` }) + .pipe(Effect.result); + if (read._tag === "Success" || read.failure.status !== 404) continue; + yield* releaseClaim(row.task.id); + yield* archive(row.task, row.threadId, "deleted"); + continue; + } + const link = card.boardThread; + if ( + link !== null && + link !== undefined && + (link.environmentId !== environmentId || link.threadId !== row.threadId) + ) { + yield* releaseClaim(row.task.id); + yield* archive(row.task, row.threadId, "displaced"); + } + } + }); + + const reconcile = Effect.fn("BoardTaskThreads.reconcile")( + function* () { + const holds = new Map(); + const config = yield* settings.getSettings.pipe(Effect.orElseSucceed(() => null)); + if (config === null || !config.delivery.enabled) return holds; + const environmentId = yield* identity.getEnvironmentId; + const lanes = yield* engine(delivery.read({ path: LANES_PATH })).pipe( + Effect.flatMap((response) => engine(decodeLanes(response.body))), + ); + const cards = new Map( + lanes.lanes.flatMap((lane) => lane.cards.map((card) => [card.id, card] as const)), + ); + // An engine that serves no `boardThread` has no link to write to. Nothing is made for it. + if ([...cards.values()].some((card) => card.boardThread === undefined)) return holds; + const starting = [...cards.values()].filter( + (card) => + card.boardThread === null && + !NOT_STARTED.has(card.lane) && + !FINISHED.has(card.lane) && + !MOVED.has(card.state), + ); + if (starting.length > 0) { + const teams = yield* engine(delivery.read({ path: "/api/teams" })).pipe( + Effect.flatMap((response) => engine(decodeTeams(response.body))), + ); + const folders = new Map( + lanes.sets.flatMap((set) => + set.target?.path ? [[set.id, set.target.path] as const] : [], + ), + ); + const key = hostEnvironment[BOARD_THREAD_KEY_VARIABLE] || undefined; + for (const card of starting) { + const hold = yield* bind(card, { environmentId, teams, folders, key }); + if (hold !== null) holds.set(card.id, hold); + } + } + for (const card of cards.values()) { + const link = card.boardThread; + if (link === null || link === undefined || link.environmentId !== environmentId) continue; + if (NOT_STARTED.has(card.lane) || FINISHED.has(card.lane) || MOVED.has(card.state)) { + yield* releaseClaim(card.id); + continue; + } + yield* holdClaim(card, environmentId, link.threadId); + } + yield* settleEnded(cards, environmentId); + for (const [task, hold] of holds) { + if (told.get(task) === hold) continue; + yield* Effect.logWarning("A started board task has no conversation yet.", { task, hold }); + } + told.clear(); + for (const [task, hold] of holds) told.set(task, hold); + return holds; + }, + (effect) => lock.withPermits(1)(effect), + ); + + const start = Effect.fn("BoardTaskThreads.start")(function* () { + // The engine pushes nothing to T3, so its lanes are read on a beat well inside the claim's + // lease window (120 seconds); the same pass is the claim's heartbeat and restart catch-up. + yield* forkParked( + reconcile().pipe( + Effect.catchCause(() => + Effect.logDebug("Board task threads were not reconciled; the engine keeps its state."), + ), + Effect.repeat(Schedule.spaced("30 seconds")), + ), + ); + }); + return BoardTaskThreads.of({ reconcile, start }); +}); + +export const layer = Layer.effect(BoardTaskThreads, make); diff --git a/apps/server/src/delivery/DeliveryService.ts b/apps/server/src/delivery/DeliveryService.ts index c28d7aaa91749..7e84ca336aa68 100644 --- a/apps/server/src/delivery/DeliveryService.ts +++ b/apps/server/src/delivery/DeliveryService.ts @@ -127,6 +127,11 @@ const decodeDeliveryRequest = Schema.decodeUnknownEffect( }), ); +/** The engine writes for a board task's conversation; only the server makes them. */ +const BOARD_THREAD_LINK = /^\/api\/tasks\/[\w-]+\/board-thread$/; +const BOARD_THREAD_CLAIM = /^\/api\/orchestration\/tasks\/[\w-]+\/(claim|ack|release)$/; +const BOARD_THREAD_WRITE = new RegExp(`${BOARD_THREAD_LINK.source}|${BOARD_THREAD_CLAIM.source}`); + /** Two spellings of one folder compare equal: slashes, case on Windows, a trailing slash. */ const normalFolder = (value: string, platform: NodeJS.Platform) => { const slashed = value.replaceAll("\\", "/").replace(/\/+$/, ""); @@ -162,6 +167,15 @@ export class DeliveryService extends Context.Service< readonly nativeBuildAct: ( input: DeliveryActInput, ) => Effect.Effect; + /** + * The server's own writes for a board task's conversation: the `boardThread` link (PUT and + * DELETE) and the task claim with its heartbeat. No client reaches these: `act` refuses them. + */ + readonly boardThreadAct: (input: { + readonly method: "PUT" | "DELETE" | "POST"; + readonly path: string; + readonly body: unknown; + }) => Effect.Effect; readonly nativeIntakeAct: ( input: DeliveryActInput, ) => Effect.Effect; @@ -218,6 +232,7 @@ export const layerTest = Layer.succeed( act: disabled, nativeBuildAct: disabled, nativeIntakeAct: disabled, + boardThreadAct: disabled, bindThread: disabled, refreshThread: disabled, threadState: Effect.fn("DeliveryService.threadState")(() => @@ -437,7 +452,7 @@ const make = Effect.fn("DeliveryService.make")(function* ( }); const request = Effect.fn("DeliveryService.request")( function* ( - method: "GET" | "POST", + method: "GET" | "POST" | "PUT" | "DELETE", enginePath: string, body?: unknown, bounded = false, @@ -447,7 +462,7 @@ const make = Effect.fn("DeliveryService.make")(function* ( ) { if (expectedConfiguration !== undefined) yield* assertConfiguration(expectedConfiguration); const settings = yield* delivery; - if (method === "POST") invalidateDiscovery(); + if (method !== "GET") invalidateDiscovery(); const hostEnvironment = yield* HostProcess.Environment; if (!settings.enabled) { return yield* new DeliveryError({ @@ -555,7 +570,14 @@ const make = Effect.fn("DeliveryService.make")(function* ( if (bounded && method === "GET" && enginePath === "/api/health") { return yield* readHealth(settings.engineUrl, true); } - const base = method === "GET" ? HttpClientRequest.get(url) : HttpClientRequest.post(url); + const base = + method === "GET" + ? HttpClientRequest.get(url) + : method === "PUT" + ? HttpClientRequest.put(url) + : method === "DELETE" + ? HttpClientRequest.delete(url) + : HttpClientRequest.post(url); const prepared = method === "GET" ? base : base.pipe(HttpClientRequest.bodyJsonUnsafe(body ?? {})); if (expectedConfiguration !== undefined) yield* assertConfiguration(expectedConfiguration); @@ -584,6 +606,13 @@ const make = Effect.fn("DeliveryService.make")(function* ( detail: "Discovery response exceeds its size limit.", }); } + // The engine answers a clear with 204 and no body. + if (response.status === 204) { + return { + readAt: DateTime.formatIso(yield* DateTime.now), + body: null, + } satisfies DeliveryResponse; + } const parsed = yield* ( bounded ? response.json.pipe( @@ -618,7 +647,7 @@ const make = Effect.fn("DeliveryService.make")(function* ( return { readAt, body: parsed } satisfies DeliveryResponse; }, (effect, method) => - method === "POST" ? effect.pipe(Effect.ensuring(Effect.sync(invalidateDiscovery))) : effect, + method === "GET" ? effect : effect.pipe(Effect.ensuring(Effect.sync(invalidateDiscovery))), ); /** The root of the repository a folder is in, or the folder itself when it is in none. */ @@ -1535,21 +1564,29 @@ const make = Effect.fn("DeliveryService.make")(function* ( "Native build receipts can only be written by the server's native coordinator.", }), ) - : new URL(input.path, "http://delivery.invalid").pathname === "/api/delivery/requests" - ? preflightDeliveryRequest(input.body).pipe( - Effect.flatMap(({ configuration, observedHealth, dispatchDeadline }) => - request( - "POST", - input.path, - input.body, - false, - observedHealth, - configuration, - dispatchDeadline, - ), - ), + : BOARD_THREAD_WRITE.test(new URL(input.path, "http://delivery.invalid").pathname) + ? Effect.fail( + new DeliveryError({ + reason: "refused", + detail: + "A board task's conversation is claimed and linked by the server, when the engine says the task started.", + }), ) - : request("POST", input.path, input.body), + : new URL(input.path, "http://delivery.invalid").pathname === "/api/delivery/requests" + ? preflightDeliveryRequest(input.body).pipe( + Effect.flatMap(({ configuration, observedHealth, dispatchDeadline }) => + request( + "POST", + input.path, + input.body, + false, + observedHealth, + configuration, + dispatchDeadline, + ), + ), + ) + : request("POST", input.path, input.body), ), nativeBuildAct: Effect.fn("DeliveryService.nativeBuildAct")((input) => /^\/api\/native-builds\/att-[A-Za-z0-9-]+\/(claim|attach|complete)$/.test(input.path) @@ -1561,6 +1598,16 @@ const make = Effect.fn("DeliveryService.make")(function* ( }), ), ), + boardThreadAct: Effect.fn("DeliveryService.boardThreadAct")((input) => + (input.method === "POST" ? BOARD_THREAD_CLAIM : BOARD_THREAD_LINK).test(input.path) + ? request(input.method, input.path, input.body) + : Effect.fail( + new DeliveryError({ + reason: "invalid", + detail: "Invalid board thread mutation path.", + }), + ), + ), nativeIntakeAct: Effect.fn("DeliveryService.nativeIntakeAct")((input) => /^\/api\/native-intakes\/intake-[a-f0-9]{64}\/(claim|attach|complete|abandon|cancel)$/.test( input.path, diff --git a/apps/server/src/delivery/boardThreadEngine.testkit.ts b/apps/server/src/delivery/boardThreadEngine.testkit.ts new file mode 100644 index 0000000000000..0c8fef9ddcdf2 --- /dev/null +++ b/apps/server/src/delivery/boardThreadEngine.testkit.ts @@ -0,0 +1,349 @@ +// A scratch engine serving the frozen task-to-thread contract (BOARD-REVAMP-UI-SPEC.md 6a), with +// the shapes of the unmerged engine half (Operation-PaperClip pull request 167, at 1d8fc1db) and +// the task claim of slice 1. A model, not the engine: what passes here must still pass there. +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import { HttpClient, HttpClientResponse } from "effect/http"; + +const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); + +export interface ScratchLink { + readonly environmentId: string; + readonly threadId: string; + readonly setBy: string; + readonly setAt: string; +} + +export interface ScratchTask { + readonly id: string; + readonly number: number; + readonly title: string; + readonly team: string; + readonly set: string | null; + lane: string; + state: string; + submitted: boolean; + held: boolean; +} + +interface Lease { + readonly holder: string; + readonly origin: string; + heartbeat: number; +} + +interface Answer { + readonly status: number; + readonly body: unknown; +} + +const ENVIRONMENT_PART = /^[^\s\p{C}/]{1,256}$/u; +const THREAD_PART = /^[^\s\p{C}]{1,1024}$/u; +const LEASE_MS = 120_000; +const CLOSED = ["completed", "closed", "rejected", "cancelled"]; + +const refused = (status: number, error: string, details: Record = {}): Answer => ({ + status, + body: { error, ...details }, +}); +const sameTarget = ( + a: { environmentId: string; threadId: string } | null, + b: { environmentId: string; threadId: string } | null, +) => a !== null && b !== null && a.environmentId === b.environmentId && a.threadId === b.threadId; + +export function scratchEngine( + options: { + readonly key?: string; + readonly cap?: number; + /** `false` models an engine before slice 2: no card carries `boardThread`. */ + readonly servesLink?: boolean; + } = {}, +) { + const key = options.key ?? "scratch approval passphrase"; + const tasks = new Map(); + const links = new Map(); + const leases = new Map(); + const events: Array<{ kind: string; task: string; data: unknown }> = []; + const requests: Array<{ method: string; path: string; body: unknown }> = []; + const sets = new Map(); + let teams: unknown = []; + let clock = Date.parse("2026-11-22T10:00:00.000Z"); + let holderSeq = 0; + let down = false; + /** Runs once, just before the next link write is admitted: another writer getting in first. */ + let beforeNextPut: (() => void) | null = null; + + const live = () => { + for (const [task, lease] of leases) { + if (clock - lease.heartbeat > LEASE_MS) leases.delete(task); + } + return leases; + }; + const cardOf = (task: ScratchTask) => ({ + id: task.id, + number: task.number, + title: task.title, + team: task.team, + set: task.set, + lane: task.lane, + state: task.state, + submitted: task.submitted ? "2026-11-22T09:00:00.000Z" : null, + held: task.held, + ...(options.servesLink === false ? {} : { boardThread: links.get(task.id) ?? null }), + }); + + const putLink = (id: string, body: Record): Answer => { + const task = tasks.get(id); + if (!task) return refused(404, `no task ${id.slice(0, 40)}`, { code: "not-found", task: null }); + const invalid = (field: string, error: string) => + refused(400, error, { code: "invalid-field", field }); + const { environmentId, threadId, setBy, expect } = body; + if (typeof environmentId !== "string" || !ENVIRONMENT_PART.test(environmentId)) + return invalid( + "environmentId", + "environmentId is 1-256 characters without whitespace, control characters or /", + ); + if (typeof threadId !== "string" || !THREAD_PART.test(threadId)) + return invalid( + "threadId", + "threadId is 1-1024 characters without whitespace or control characters; / : and % are allowed", + ); + if (typeof setBy !== "string" || !ENVIRONMENT_PART.test(setBy)) + return invalid("setBy", "setBy names the T3 environment that writes the link"); + let believed: { environmentId: string; threadId: string } | null = null; + const expectsNone = expect === null; + if (expect !== undefined && !expectsNone) { + const value = expect as Record; + if ( + typeof expect !== "object" || + Array.isArray(expect) || + typeof value.environmentId !== "string" || + typeof value.threadId !== "string" + ) + return invalid( + "expect", + "expect is the link believed current: null, or { environmentId, threadId }", + ); + believed = { environmentId: value.environmentId, threadId: value.threadId }; + } + const previous = links.get(id) ?? null; + if (expectsNone && previous) + return refused(409, "a board thread is set; the caller believed none was", { + code: "conflict", + current: previous, + expect: null, + }); + if (believed && !sameTarget(believed, previous)) + return refused(409, "the board thread changed since the caller read it", { + code: "conflict", + current: previous, + expect: believed, + }); + if (previous && sameTarget(previous, { environmentId, threadId })) + return { + status: 200, + body: { task: id, number: task.number, boardThread: previous, unchanged: true }, + }; + const boardThread = { + environmentId, + threadId, + setBy, + setAt: DateTime.formatIso(DateTime.makeUnsafe(clock)), + }; + links.set(id, boardThread); + events.push({ kind: "task.board-thread-set", task: id, data: { previous, boardThread } }); + return { status: 200, body: { task: id, number: task.number, boardThread } }; + }; + + const clearLink = (id: string): Answer => { + if (!tasks.has(id)) + return refused(404, `no task ${id.slice(0, 40)}`, { code: "not-found", task: null }); + const previous = links.get(id) ?? null; + if (previous) { + links.delete(id); + events.push({ kind: "task.board-thread-cleared", task: id, data: { previous } }); + } + return { status: 204, body: null }; + }; + + const claim = (id: string, body: Record): Answer => { + const task = tasks.get(id); + if (!task) return refused(404, "no such task"); + if (typeof body.origin !== "string" || !body.origin.trim()) + return refused(400, "name the thread origin the claim is made from"); + if (!task.submitted) + return refused(409, `#${task.number} is not submitted; only submitted work is claimed`); + if (task.state === "moving" || task.state === "moved") + return refused(409, `#${task.number} moved to another machine; it is claimed there`); + if (CLOSED.includes(task.state)) + return refused(409, `#${task.number} is ${task.state}; finished work is not claimed`); + if (task.held) return refused(409, `#${task.number} is paused; resume it before it is claimed`); + const held = live().get(id); + if (held) return refused(409, `#${task.number} is already claimed by ${held.origin}`); + const cap = options.cap ?? 4; + if (live().size >= cap) + return refused(409, `the task cap is reached: ${live().size} of ${cap} slots are taken`); + const lease = { holder: `holder-${++holderSeq}`, origin: body.origin.trim(), heartbeat: clock }; + leases.set(id, lease); + events.push({ kind: "orchestration.claimed", task: id, data: { origin: lease.origin } }); + return { + status: 200, + body: { claimed: true, task: id, holder: lease.holder, origin: lease.origin }, + }; + }; + const withLease = ( + id: string, + body: Record, + then: (lease: Lease) => Answer, + ): Answer => { + const task = tasks.get(id); + if (!task) return refused(404, "no such task"); + const lease = live().get(id); + if (!lease) return refused(404, `no live lease holds #${task.number}`); + if (body.holder !== lease.holder) return refused(409, "the lease holder does not match"); + return then(lease); + }; + + const handle = (method: string, pathname: string, raw: unknown): Answer => { + const body = (raw && typeof raw === "object" ? raw : {}) as Record; + requests.push({ method, path: pathname, body: raw }); + if (method === "GET" && pathname === "/api/lanes") { + const cards = [...tasks.values()].map(cardOf); + return { + status: 200, + body: { + lanes: [...new Set(cards.map((card) => card.lane))].map((lane) => ({ + lane, + title: lane, + cards: cards.filter((card) => card.lane === lane), + })), + sets: [...sets].map(([id, target]) => ({ id, target })), + }, + }; + } + if (method === "GET" && pathname === "/api/teams") return { status: 200, body: teams }; + const detail = /^\/api\/tasks\/([\w-]+)$/.exec(pathname); + if (method === "GET" && detail) { + const task = tasks.get(detail[1]!); + // `thread` keeps meaning the task id; the conversation is only ever `boardThread`. + return task + ? { status: 200, body: { ...cardOf(task), thread: task.id, source: null } } + : refused(404, `no task ${detail[1]}`); + } + // The moved guard of every task write, which runs before the key is looked at. + const touched = + method !== "GET" ? /^\/api\/(tasks|runs|threads)\/([\w-]+)\/(?!moved$)/.exec(pathname) : null; + const guarded = touched ? tasks.get(touched[2]!) : undefined; + if (guarded?.state === "moving") + return refused( + 409, + `#${guarded.number} is on its way to another machine; it takes no work until that is settled`, + { code: "moved" }, + ); + if (guarded?.state === "moved") + return refused(409, `#${guarded.number} moved to another machine; it is worked there now`, { + code: "moved", + }); + const link = /^\/api\/tasks\/([\w-]+)\/board-thread$/.exec(pathname); + if (link && (method === "PUT" || method === "DELETE")) { + if (body.key !== key) + return refused(403, "the approval key is wrong or missing", { code: "refused" }); + if (method === "DELETE") return clearLink(link[1]!); + const before = beforeNextPut; + beforeNextPut = null; + before?.(); + return putLink(link[1]!, body); + } + const lease = /^\/api\/orchestration\/tasks\/([\w-]+)\/(claim|ack|release)$/.exec(pathname); + if (lease && method === "POST") { + const id = lease[1]!; + if (lease[2] === "claim") return claim(id, body); + if (lease[2] === "ack") + return withLease(id, body, (held) => { + held.heartbeat = clock; + return { status: 200, body: { renewed: true, task: id } }; + }); + return withLease(id, body, () => { + leases.delete(id); + return { status: 200, body: { released: true, task: id } }; + }); + } + return refused(404, `no route ${method} ${pathname}`); + }; + + return { + key, + events, + requests, + handle, + addTask(task: Partial & Pick) { + const added: ScratchTask = { + number: 1000 + tasks.size, + title: `Task ${task.id}`, + team: "development", + set: "work", + lane: "implementation", + state: "running", + submitted: true, + held: false, + ...task, + }; + tasks.set(added.id, added); + return added; + }, + task: (id: string) => tasks.get(id)!, + removeTask: (id: string) => { + tasks.delete(id); + links.delete(id); + leases.delete(id); + }, + setBoard: (id: string, path: string | null) => sets.set(id, { path }), + setTeams: (value: unknown) => { + teams = value; + }, + linkOf: (id: string) => links.get(id) ?? null, + /** Another writer's link, written as the engine would write it. */ + writeLink: (id: string, link: { environmentId: string; threadId: string; setBy: string }) => + putLink(id, link), + leaseOf: (id: string) => live().get(id) ?? null, + advance: (ms: number) => { + clock += ms; + }, + beforeNextPut: (run: () => void) => { + beforeNextPut = run; + }, + setDown: (value: boolean) => { + down = value; + }, + isDown: () => down, + }; +} + +export type ScratchEngine = ReturnType; + +/** The scratch engine behind the HTTP client the delivery service uses for the real one. */ +export const scratchEngineHttp = (engine: ScratchEngine) => + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.suspend(() => { + if (engine.isDown()) return Effect.fail(new Error("connection refused") as never); + const url = new URL(request.url); + const body = + request.body._tag === "Uint8Array" + ? decodeJson(new TextDecoder().decode(request.body.body)) + : undefined; + const answer = engine.handle(request.method, url.pathname, body); + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + answer.status === 204 + ? new Response(null, { status: 204 }) + : Response.json(answer.body, { status: answer.status }), + ), + ); + }), + ), + ); diff --git a/apps/server/src/delivery/boardThreadMarker.test.ts b/apps/server/src/delivery/boardThreadMarker.test.ts index d061f179947ed..380cc10b04b1f 100644 --- a/apps/server/src/delivery/boardThreadMarker.test.ts +++ b/apps/server/src/delivery/boardThreadMarker.test.ts @@ -65,18 +65,45 @@ const NOT_A_VALUE_READ: ReadonlyArray = [ /^engineIntake: _engineIntake,$/, // The engine intake stamping its own admission. /^engineIntake: admissionId,$/, + // A board task's thread stamped at its creation, by the marker module's own spelling. + /^engineIntake: boardTaskThreadMarker\(task\),$/, ]; -it("only the engine intake reads the marker's value; every other reader asks whether it is set", () => { +// The board task readers. Each hands the value to the marker module, thread to task only, and +// none builds a marker to find a thread: a task's thread is the engine's `boardThread`. +const BOARD_TASK_READS = [ + // The threads this server made for board tasks, selected on the marker's own prefix. + { + file: "apps/server/src/delivery/boardThreadRows.ts", + line: "json_extract(t.payload_json, '$.lineage.engineIntake') AS marker", + }, + { + file: "apps/server/src/delivery/boardThreadRows.ts", + line: "AND json_extract(t.payload_json, '$.lineage.engineIntake') LIKE ${BOARD_TASK_MARKER_LIKE}", + }, + // The thread just created is the task's own, before the engine is told of it. + { + file: "apps/server/src/delivery/BoardTaskThreads.ts", + line: "const stamped = boardTaskOfMarker(created.thread.lineage.engineIntake);", + }, +]; + +it("only the engine intake and the named board task readers read the marker's value", () => { const valueReads = linesNaming(/engineIntake|engine_intake/).filter( ({ line }) => !NOT_A_VALUE_READ.some((allowed) => allowed.test(line)), ); - assert.deepEqual(valueReads, [ - { - file: "apps/server/src/delivery/NativeIntake.ts", - line: "if (projection.thread.lineage.engineIntake !== admissionId)", - }, - ]); + const byPlace = (a: { file: string; line: string }, b: { file: string; line: string }) => + `${a.file}\n${a.line}`.localeCompare(`${b.file}\n${b.line}`); + assert.deepEqual( + valueReads.toSorted(byPlace), + [ + { + file: "apps/server/src/delivery/NativeIntake.ts", + line: "if (projection.thread.lineage.engineIntake !== admissionId)", + }, + ...BOARD_TASK_READS, + ].toSorted(byPlace), + ); }); it("nothing but the marker module knows what a board task's marker looks like", () => { diff --git a/apps/server/src/delivery/boardThreadRows.ts b/apps/server/src/delivery/boardThreadRows.ts new file mode 100644 index 0000000000000..854b9a30fe415 --- /dev/null +++ b/apps/server/src/delivery/boardThreadRows.ts @@ -0,0 +1,71 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; +import type * as SqlError from "effect/sql/SqlError"; + +import { BOARD_TASK_MARKER_LIKE, boardTaskOfMarker, type BoardTask } from "./boardThreadMarker.ts"; + +/** A thread this server made for a board task, with the task its marker names. */ +export interface BoardThreadRow { + readonly threadId: ThreadId; + readonly projectId: ProjectId; + readonly title: string; + readonly archivedAt: string | null; + readonly task: BoardTask; +} + +/** + * The board task threads of this server, which no list shows. Thread to task only: the rows are + * found by their marker and each names its task, and nothing here finds a thread from a task. + */ +export class BoardThreadRows extends Context.Service< + BoardThreadRows, + { + readonly list: (options: { + readonly archived: boolean; + }) => Effect.Effect, SqlError.SqlError>; + } +>()("t3/delivery/boardThreadRows") {} + +export const layer = Layer.effect( + BoardThreadRows, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return BoardThreadRows.of({ + list: Effect.fn("BoardThreadRows.list")(function* ({ archived }) { + const rows = yield* sql<{ + id: string; + projectId: string; + title: string; + archivedAt: string | null; + marker: string | null; + }>` + SELECT t.thread_id AS id, t.project_id AS "projectId", t.title, + t.archived_at AS "archivedAt", + json_extract(t.payload_json, '$.lineage.engineIntake') AS marker + FROM orchestration_v2_projection_threads AS t + WHERE t.deleted_at IS NULL + AND json_extract(t.payload_json, '$.lineage.engineIntake') LIKE ${BOARD_TASK_MARKER_LIKE} + ORDER BY t.updated_at DESC, id ASC + `.pipe(NodeSqliteClient.readOnly); + return rows.flatMap((row) => { + const task = boardTaskOfMarker(row.marker); + return task === null || (row.archivedAt !== null) !== archived + ? [] + : [ + { + threadId: ThreadId.make(row.id), + projectId: ProjectId.make(row.projectId), + title: row.title, + archivedAt: row.archivedAt, + task, + }, + ]; + }); + }), + }); + }), +); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 43a98be89fad6..20d1c111bc615 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -9,6 +9,8 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; import * as DelegatedTaskQuestionReactor from "./orchestration-v2/DelegatedTaskQuestionReactor.ts"; +import * as BoardTaskThreads from "./delivery/BoardTaskThreads.ts"; +import * as BoardThreadRows from "./delivery/boardThreadRows.ts"; import * as NativeIntake from "./delivery/NativeIntake.ts"; // Effect wraps this raw Node HTTP server after its startup and write-error guards attach. // @effect-diagnostics nodeBuiltinImport:off @@ -746,6 +748,18 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.provide(layerDelivery), Layer.provide(ServerEnvironment.layerIdentity), ), + Layer.effectDiscard( + Effect.gen(function* () { + const service = yield* BoardTaskThreads.BoardTaskThreads; + yield* service.start(); + }), + ).pipe( + Layer.provide(BoardTaskThreads.layer), + Layer.provide(BoardThreadRows.layer), + Layer.provide(ProjectionStoreV2.layer), + Layer.provide(layerDelivery), + Layer.provide(ServerEnvironment.layerIdentity), + ), Layer.effectDiscard( Effect.gen(function* () { const service = yield* PullRequestSyncReactor.PullRequestSyncReactor; From b1f224e86820de94e88c1344346700f00d937f23 Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Sun, 22 Nov 2026 04:46:46 +0000 Subject: [PATCH 03/13] feat(web): a task's conversation is the thread the engine links it to lib/taskConversation reads boardThread, on the task and on its card, and stays the only reader of it. The task.source stand-in is gone with no second source: a task with no link is a draft, queued or unlinked, and the thread a task was filed from is never shown as its conversation. A link wins wherever the task stands, so a task sent back to the queue keeps what was said. Co-Authored-By: Claude Fable 5.2 --- apps/web/src/lib/delivery.ts | 32 +++++++++- apps/web/src/lib/taskConversation.test.ts | 77 +++++++++++++++++++---- apps/web/src/lib/taskConversation.ts | 40 ++++++------ 3 files changed, 115 insertions(+), 34 deletions(-) diff --git a/apps/web/src/lib/delivery.ts b/apps/web/src/lib/delivery.ts index f5b14731a3942..1b952b90a92e8 100644 --- a/apps/web/src/lib/delivery.ts +++ b/apps/web/src/lib/delivery.ts @@ -929,6 +929,27 @@ export const waitingWords = (reason: string | null): string => ? `waits for ${reason}` : "is working"; +/** + * The engine's link from a task to the conversation its lead runs it in (`boardThread`, engine + * spec 6a). The names are the engine's. Only `lib/taskConversation` reads it. + */ +export interface BoardThreadLink { + readonly environmentId: string; + readonly threadId: string; + /** The T3 environment that wrote the link, never a person. */ + readonly setBy: string; + readonly setAt: string; +} + +export function parseBoardThread(value: unknown): BoardThreadLink | null { + if (!isRecord(value)) return null; + const environmentId = text(value.environmentId); + const threadId = text(value.threadId); + return environmentId && threadId + ? { environmentId, threadId, setBy: text(value.setBy), setAt: text(value.setAt) } + : null; +} + export interface DeliveryCard { readonly id: string; /** The number a person says and searches by, e.g. 1001. */ @@ -1028,6 +1049,8 @@ export interface DeliveryCard { readonly rank: number; /** The engine's own answer to whether this task waits on a person (a question, a plan, a sign-off). */ readonly waitsOnPerson: boolean; + /** The conversation the board's lead runs this task in, or null when the engine links none. */ + readonly boardThread: BoardThreadLink | null; /** Whether an approval of this task still stands. */ readonly approveStands: boolean; /** @@ -1282,6 +1305,7 @@ export const parseCard = (value: Json): DeliveryCard => { first: flag(value.first), rank: typeof value.rank === "number" && Number.isFinite(value.rank) ? value.rank : 0, waitsOnPerson: flag(value.waitsOnPerson), + boardThread: parseBoardThread(value.boardThread), approveStands: flag(value.approveStands), queue: parseQueueFact(value.queue), reworkRounds: @@ -1694,7 +1718,12 @@ export interface TaskView { readonly target: DeliveryTarget | null; /** The board triage thinks it belongs on, as on its card. Older engines omit it. */ readonly suggestedBoard?: SuggestedBoard | null; - /** The conversation this task was made from: `/`. */ + /** The conversation the board's lead runs this task in. Read through `lib/taskConversation`. */ + readonly boardThread: BoardThreadLink | null; + /** + * The conversation this task was filed from: `/`. A thread of its own, and + * never the task's conversation. + */ readonly source: { readonly kind: "thread"; readonly environmentId: string; @@ -1916,6 +1945,7 @@ export function parseTask(body: unknown): TaskView | null { })(), target: parseTarget(body.target), suggestedBoard: parseSuggestedBoard(body.suggestedBoard), + boardThread: parseBoardThread(body.boardThread), source: (() => { const source = isRecord(body.source) ? body.source : null; const ref = source ? text(source.ref) : ""; diff --git a/apps/web/src/lib/taskConversation.test.ts b/apps/web/src/lib/taskConversation.test.ts index dd84687cfd737..fd263f04ce200 100644 --- a/apps/web/src/lib/taskConversation.test.ts +++ b/apps/web/src/lib/taskConversation.test.ts @@ -1,3 +1,7 @@ +// @effect-diagnostics nodeBuiltinImport:off - reads the source tree synchronously, once. +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + import { describe, expect, it } from "vite-plus/test"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; @@ -10,36 +14,83 @@ import { steadySeatThread, taskConversation, } from "./taskConversation"; +import { parseBoardThread, parseCard, parseTask } from "./delivery"; + +const SRC = NodePath.resolve(import.meta.dirname, ".."); +const sourceFiles = (directory: string): ReadonlyArray => + NodeFS.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const path = NodePath.join(directory, entry.name); + if (entry.isDirectory()) return sourceFiles(path); + return /\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name) ? [path] : []; + }); -const source = { kind: "thread" as const, environmentId: "env-1", threadId: "thread-1" }; +const boardThread = { + environmentId: "env-1", + threadId: "thread-1", + setBy: "env-1", + setAt: "2026-11-22T10:00:00.000Z", +}; +// The thread the task was filed from: another conversation, which must never stand in. +const source = { kind: "thread" as const, environmentId: "env-9", threadId: "filed-from" }; const ref = { environmentId: EnvironmentId.make("env-1"), threadId: ThreadId.make("thread-1") }; describe("which conversation a task has", () => { - it("is the thread the task was made from, once the task is in work", () => { - expect(taskConversation({ source, isDraft: false, lane: "implementation" })).toEqual({ - kind: "thread", - ref, - }); + it("is the thread the engine links the task to, in work or sent back to the queue", () => { + for (const lane of ["implementation", "queue", "completed"]) { + expect(taskConversation({ boardThread, isDraft: false, lane })).toEqual({ + kind: "thread", + ref, + }); + } }); - it("has none for a draft or a queued task, even when it was made from a thread", () => { - expect(taskConversation({ source, isDraft: true, lane: "draft" })).toEqual({ + it("has none for a draft or a queued task with no link", () => { + expect(taskConversation({ boardThread: null, isDraft: true, lane: "draft" })).toEqual({ kind: "none", why: "draft", }); for (const lane of ["intake", "ready", "queue"]) { - expect(taskConversation({ source, isDraft: false, lane })).toEqual({ + expect(taskConversation({ boardThread: null, isDraft: false, lane })).toEqual({ kind: "none", why: "queued", }); } }); - it("is unlinked for a task in work that was not made from a thread", () => { - expect(taskConversation({ source: null, isDraft: false, lane: "planning" })).toEqual({ - kind: "none", - why: "unlinked", + it("is unlinked for a task in work with no link, and never the thread it was filed from", () => { + const task = { boardThread: null, source, isDraft: false, lane: "planning" }; + expect(taskConversation(task)).toEqual({ kind: "none", why: "unlinked" }); + }); + + it("reads the link as the engine serves it, on the task and on its card", () => { + const wire = { ...boardThread, threadId: "board-task:a%3Ab:c/with:colon" }; + expect(parseBoardThread(wire)).toEqual(wire); + expect(parseTask({ id: "t", card: {}, boardThread: wire })?.boardThread).toEqual(wire); + expect(parseCard({ id: "t", boardThread: wire }).boardThread).toEqual(wire); + for (const none of [null, undefined, {}, { environmentId: "env-1" }, "thread-1"]) { + expect(parseBoardThread(none)).toBeNull(); + } + // `thread` is the task id and `source` the filing thread: neither is read as the link. + const named = parseTask({ + id: "t", + card: {}, + thread: "t", + source: { kind: "thread", ref: "env-9/x" }, }); + expect(named?.source?.threadId).toBe("x"); + expect(named?.boardThread).toBeNull(); + }); + + it("is the only reader of the link", () => { + // Taking the field off the wire is the parser's; a read is anything else that names it. + const readers = sourceFiles(SRC).filter((file) => + NodeFS.readFileSync(file, "utf8") + .split("\n") + .some((line) => /\.boardThread\b/.test(line) && !line.includes("parseBoardThread(")), + ); + expect(readers.map((file) => NodePath.relative(SRC, file))).toEqual([ + NodePath.join("lib", "taskConversation.ts"), + ]); }); }); diff --git a/apps/web/src/lib/taskConversation.ts b/apps/web/src/lib/taskConversation.ts index bd54e1fa86065..cd1abb31c2951 100644 --- a/apps/web/src/lib/taskConversation.ts +++ b/apps/web/src/lib/taskConversation.ts @@ -9,9 +9,9 @@ import { BOARD_LANE, boardLaneOf } from "./boardLanes"; import type { DeliveryCard, TaskView } from "./delivery"; /** - * THROWAWAY, like boardLanes.ts. The one place that says which conversation is a task's, until - * the engine links tasks to threads (its build slices 1 and 2): an ordinary thread, the one the - * task was made from, stands in. Callers never read `task.source` themselves. + * The one place that says which conversation is a task's: the thread the engine links it to + * (`boardThread`). Nothing else reads that field, and the thread a task was filed from + * (`task.source`) is never a task's conversation. */ /** What a task's conversation is, before anyone asks whether it can be reached. */ @@ -20,27 +20,27 @@ export type TaskConversation = /** `draft` and `queued` have no conversation yet; `unlinked` is a task in work with none known. */ | { readonly kind: "none"; readonly why: "draft" | "queued" | "unlinked" }; -type ConversationInput = Pick; +type ConversationInput = Pick; /** - * A draft or a queued task has no conversation, whatever thread it was made from: the thread it - * came from is a conversation of its own and is not the team's. Once the task is in work the - * stand-in is that origin thread, if there is one. + * The engine's link is the conversation, wherever the task stands: a task sent back to the queue + * keeps what was said in it. With no link a draft or a queued task has none yet, and a task in + * work is `unlinked`. There is no other source to fall back to. */ export function taskConversation(task: ConversationInput): TaskConversation { + const link = task.boardThread; + if (link) { + return { + kind: "thread", + ref: { + environmentId: EnvironmentId.make(link.environmentId), + threadId: ThreadId.make(link.threadId), + }, + }; + } if (task.isDraft || task.lane === "draft") return { kind: "none", why: "draft" }; if (boardLaneOf(task.lane) === BOARD_LANE.queue) return { kind: "none", why: "queued" }; - const source = task.source; - if (!source || !source.environmentId || !source.threadId) { - return { kind: "none", why: "unlinked" }; - } - return { - kind: "thread", - ref: { - environmentId: EnvironmentId.make(source.environmentId), - threadId: ThreadId.make(source.threadId), - }, - }; + return { kind: "none", why: "unlinked" }; } /** What the centre of the task view shows. */ @@ -49,7 +49,7 @@ export type ConversationState = | { readonly kind: "open"; readonly ref: ScopedThreadRef; readonly offline: boolean } /** No conversation yet, and none expected until the task starts. No composer. */ | { readonly kind: "waiting"; readonly why: "draft" | "queued" } - /** In work with no known conversation: the engine's own log stands in, as it did before. */ + /** In work with no linked conversation: the engine's own log stands in, as it did before. */ | { readonly kind: "unlinked" }; export function conversationState( @@ -70,7 +70,7 @@ export const sameThread = (a: ScopedThreadRef | null, b: ScopedThreadRef | null) /** A seat's conversation, in the shape every agent row opens: see `subagentThreadTarget`. */ export type SeatThread = SubagentThreadTarget; -/** The part of a delegated child the stand-in reads: its thread, here or remote, and its seat. */ +/** The part of a delegated child this module reads: its thread, here or remote, and its seat. */ interface SeatChild { readonly childThreadId: ThreadId | null; readonly remoteChild?: From e6aa98edda337e8047ae2563bd1b670bb789c48e Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Sun, 22 Nov 2026 04:53:08 +0000 Subject: [PATCH 04/13] feat: the board lists the archived conversations of its tasks A task that ended leaves its thread archived, and no thread list shows a board task's thread. The board toolbar now opens a list of them, each to open, restore or delete. The server finds them by their marker and names the board and task of each; the client never reads a marker. Co-Authored-By: Claude Fable 5.2 --- apps/server/src/auth/RpcAuthorization.ts | 1 + apps/server/src/delivery/boardThreadRows.ts | 70 ++++---- .../src/observability/RpcInstrumentation.ts | 1 + .../ThreadLaunchService.test.ts | 15 ++ apps/server/src/ws.ts | 24 +++ .../ArchivedBoardThreads.logic.test.ts | 28 ++++ .../delivery/ArchivedBoardThreads.logic.ts | 16 ++ .../delivery/ArchivedBoardThreads.tsx | 152 ++++++++++++++++++ .../web/src/components/delivery/BoardPage.tsx | 10 +- packages/client-runtime/src/state/delivery.ts | 6 + packages/contracts/src/delivery.ts | 22 ++- packages/contracts/src/rpc.ts | 10 ++ 12 files changed, 322 insertions(+), 33 deletions(-) create mode 100644 apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts create mode 100644 apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts create mode 100644 apps/web/src/components/delivery/ArchivedBoardThreads.tsx diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 882f486c6610b..c3de6f335b2dc 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -134,6 +134,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.deliveryAct]: AuthOrchestrationOperateScope, [WS_METHODS.deliveryBindThread]: AuthOrchestrationOperateScope, [WS_METHODS.deliveryThreadBinding]: AuthOrchestrationReadScope, + [WS_METHODS.deliveryArchivedBoardThreads]: AuthOrchestrationReadScope, [WS_METHODS.deliveryReleaseThread]: AuthOrchestrationOperateScope, [WS_METHODS.deliverySetThreadLineup]: AuthOrchestrationOperateScope, [WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope, diff --git a/apps/server/src/delivery/boardThreadRows.ts b/apps/server/src/delivery/boardThreadRows.ts index 854b9a30fe415..9b3a18b956752 100644 --- a/apps/server/src/delivery/boardThreadRows.ts +++ b/apps/server/src/delivery/boardThreadRows.ts @@ -30,42 +30,50 @@ export class BoardThreadRows extends Context.Service< } >()("t3/delivery/boardThreadRows") {} +/** The rows, read with whatever database connection the caller holds. */ +export const listBoardThreadRows = Effect.fn("listBoardThreadRows")(function* (options: { + readonly archived: boolean; +}) { + const sql = yield* SqlClient.SqlClient; + const rows = yield* sql<{ + id: string; + projectId: string; + title: string; + archivedAt: string | null; + marker: string | null; + }>` + SELECT t.thread_id AS id, t.project_id AS "projectId", t.title, + t.archived_at AS "archivedAt", + json_extract(t.payload_json, '$.lineage.engineIntake') AS marker + FROM orchestration_v2_projection_threads AS t + WHERE t.deleted_at IS NULL + AND json_extract(t.payload_json, '$.lineage.engineIntake') LIKE ${BOARD_TASK_MARKER_LIKE} + ORDER BY t.updated_at DESC, id ASC + `.pipe(NodeSqliteClient.readOnly); + return rows.flatMap((row): ReadonlyArray => { + const task = boardTaskOfMarker(row.marker); + return task === null || (row.archivedAt !== null) !== options.archived + ? [] + : [ + { + threadId: ThreadId.make(row.id), + projectId: ProjectId.make(row.projectId), + title: row.title, + archivedAt: row.archivedAt, + task, + }, + ]; + }); +}); + export const layer = Layer.effect( BoardThreadRows, Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; return BoardThreadRows.of({ - list: Effect.fn("BoardThreadRows.list")(function* ({ archived }) { - const rows = yield* sql<{ - id: string; - projectId: string; - title: string; - archivedAt: string | null; - marker: string | null; - }>` - SELECT t.thread_id AS id, t.project_id AS "projectId", t.title, - t.archived_at AS "archivedAt", - json_extract(t.payload_json, '$.lineage.engineIntake') AS marker - FROM orchestration_v2_projection_threads AS t - WHERE t.deleted_at IS NULL - AND json_extract(t.payload_json, '$.lineage.engineIntake') LIKE ${BOARD_TASK_MARKER_LIKE} - ORDER BY t.updated_at DESC, id ASC - `.pipe(NodeSqliteClient.readOnly); - return rows.flatMap((row) => { - const task = boardTaskOfMarker(row.marker); - return task === null || (row.archivedAt !== null) !== archived - ? [] - : [ - { - threadId: ThreadId.make(row.id), - projectId: ProjectId.make(row.projectId), - title: row.title, - archivedAt: row.archivedAt, - task, - }, - ]; - }); - }), + list: Effect.fn("BoardThreadRows.list")((options) => + listBoardThreadRows(options).pipe(Effect.provideService(SqlClient.SqlClient, sql)), + ), }); }), ); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index ddcd3bbd235c7..113a06cd20e82 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -16,6 +16,7 @@ const RPC_AGGREGATES = { [WS_METHODS.deliveryAct]: "delivery", [WS_METHODS.deliveryBindThread]: "delivery", [WS_METHODS.deliveryThreadBinding]: "delivery", + [WS_METHODS.deliveryArchivedBoardThreads]: "delivery", [WS_METHODS.deliveryReleaseThread]: "delivery", [WS_METHODS.deliverySetThreadLineup]: "delivery", [WS_METHODS.serverSubscribeCheckoutUpdate]: "server", diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 5d64f0d134447..1c1afc82e5462 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -11,6 +11,7 @@ import * as ServerConfig from "../config.ts"; import { createPendingAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts"; import * as ThreadMessageIntake from "./ThreadMessageIntake.ts"; import { boardTaskThreadCommandId, boardTaskThreadMarker } from "../delivery/boardThreadMarker.ts"; +import { listBoardThreadRows } from "../delivery/boardThreadRows.ts"; import { assert, it, vi } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { @@ -577,6 +578,20 @@ it.effect("keeps a board task's thread out of both lists, however often it is cr [ThreadId.make("thread:top-level")], ); } + // The board reaches it by its marker: among the live ones, and once archived among those. + const rows = (archived: boolean) => + listBoardThreadRows({ archived }).pipe( + Effect.map((found) => found.map((row) => ({ threadId: row.threadId, task: row.task }))), + ); + assert.deepEqual(yield* rows(false), [{ threadId, task }]); + assert.deepEqual(yield* rows(true), []); + yield* threads.dispatch({ + type: "thread.archive", + commandId: CommandId.make("command:archive-board-task"), + threadId, + }); + assert.deepEqual(yield* rows(false), []); + assert.deepEqual(yield* rows(true), [{ threadId, task }]); }).pipe(Effect.provide(harness.layer)); }); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index a391562d28359..73f77416c9613 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -27,6 +27,7 @@ import * as Stream from "effect/Stream"; import { rpcInitialItems } from "./rpcInitialItems.ts"; import { subscribeChatGptHandoff } from "./provider/CodexChatGptHandoff.ts"; import { + DeliveryError, AcpRegistryOperationError, CommandId, authScopeResponse, @@ -266,6 +267,7 @@ import * as ThreadIssueService from "./orchestration-v2/ThreadIssueService.ts"; import * as IssueTrackerConnections from "./issue/IssueTrackerConnections.ts"; import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts"; import { listLinkedPullRequestThreads } from "./pullRequest/linkedThreads.ts"; +import { listBoardThreadRows } from "./delivery/boardThreadRows.ts"; import { pullRequestSyncKey } from "./pullRequest/pullRequestSyncKey.ts"; import * as SqlClient from "effect/sql/SqlClient"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; @@ -3692,6 +3694,7 @@ const layerForkWsRpc = (currentSession: EnvironmentAuth.AuthenticatedSession) => Effect.gen(function* () { const checkoutUpdate = yield* CheckoutUpdate.CheckoutUpdate; const delivery = yield* DeliveryService.DeliveryService; + const sql = yield* SqlClient.SqlClient; return ForkServerWsRpcGroup.of({ [WS_METHODS.serverSubscribeCheckoutUpdate]: (_input) => checkoutUpdate.states, [WS_METHODS.serverCheckCheckoutUpdate]: (_input) => @@ -3708,6 +3711,27 @@ const layerForkWsRpc = (currentSession: EnvironmentAuth.AuthenticatedSession) => : delivery.act(input), [WS_METHODS.deliveryBindThread]: (input) => delivery.bindThread(input), [WS_METHODS.deliveryThreadBinding]: (input) => delivery.threadState(input.threadId), + [WS_METHODS.deliveryArchivedBoardThreads]: () => + listBoardThreadRows({ archived: true }).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + Effect.map((rows) => ({ + threads: rows.map((row) => ({ + threadId: row.threadId, + projectId: row.projectId, + title: row.title, + archivedAt: row.archivedAt ?? "", + board: row.task.board, + taskId: row.task.id, + })), + })), + Effect.mapError( + () => + new DeliveryError({ + reason: "storage", + detail: "The archived board conversations could not be read.", + }), + ), + ), [WS_METHODS.deliveryReleaseThread]: (input) => delivery.releaseThread(input.threadId), [WS_METHODS.deliverySetThreadLineup]: (input) => delivery.setThreadLineup(input), }); diff --git a/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts new file mode 100644 index 0000000000000..a7ab75c8f51bd --- /dev/null +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts @@ -0,0 +1,28 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { expect, it } from "vite-plus/test"; + +import { archivedThreadsOfBoard } from "./ArchivedBoardThreads.logic"; + +const thread = (board: string, taskId: string, archivedAt: string) => ({ + threadId: ThreadId.make(`thread-${taskId}`), + projectId: ProjectId.make("project"), + title: taskId, + archivedAt, + board, + taskId, +}); + +it("lists the open board's archived conversations, newest first, and every board's on all", () => { + const threads = [ + thread("work", "a", "2026-11-20T10:00:00.000Z"), + thread("other", "b", "2026-11-22T10:00:00.000Z"), + thread("work", "c", "2026-11-21T10:00:00.000Z"), + ]; + expect(archivedThreadsOfBoard(threads, "work").map((entry) => entry.taskId)).toEqual(["c", "a"]); + expect(archivedThreadsOfBoard(threads, "all").map((entry) => entry.taskId)).toEqual([ + "b", + "c", + "a", + ]); + expect(archivedThreadsOfBoard(threads, "none")).toEqual([]); +}); diff --git a/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts new file mode 100644 index 0000000000000..5cac75af0d1e5 --- /dev/null +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts @@ -0,0 +1,16 @@ +import type { DeliveryArchivedBoardThreads } from "@t3tools/contracts"; + +export type ArchivedBoardThread = DeliveryArchivedBoardThreads["threads"][number]; + +/** + * The archived conversations the open board lists: its own, or every board's when every task is + * shown. Newest archive first. + */ +export function archivedThreadsOfBoard( + threads: ReadonlyArray, + board: string, +): ReadonlyArray { + return threads + .filter((thread) => board === "all" || thread.board === board) + .toSorted((a, b) => b.archivedAt.localeCompare(a.archivedAt)); +} diff --git a/apps/web/src/components/delivery/ArchivedBoardThreads.tsx b/apps/web/src/components/delivery/ArchivedBoardThreads.tsx new file mode 100644 index 0000000000000..0cf9b7341e4f4 --- /dev/null +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.tsx @@ -0,0 +1,152 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { ArchiveIcon, ArchiveX, Trash2Icon } from "lucide-react"; +import { useState } from "react"; + +import { useThreadActions } from "../../hooks/useThreadActions"; +import { deliveryEnvironment } from "../../state/delivery"; +import { useEnvironmentQuery } from "../../state/query"; +import { RelativeTime } from "../RelativeTime"; +import { Button } from "../ui/button"; +import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "../ui/popover"; +import { toastManager } from "../ui/toast"; +import { archivedThreadsOfBoard, type ArchivedBoardThread } from "./ArchivedBoardThreads.logic"; + +/** + * The board's door to the conversations of tasks that ended. Such a thread is archived, never + * deleted, and no thread list shows it, so this is where it is opened, restored or deleted. + */ +export function ArchivedBoardThreads(props: { + readonly environmentId: EnvironmentId; + /** The open board, or `all` for every board of the environment. */ + readonly board: string; +}) { + const [open, setOpen] = useState(false); + const navigate = useNavigate(); + const { unarchiveThread, confirmAndDeleteThread } = useThreadActions(); + const [pending, setPending] = useState(null); + // Read while the list is open: an archive is rare, and nothing on the board counts them. + const query = useEnvironmentQuery( + open + ? deliveryEnvironment.archivedBoardThreads({ environmentId: props.environmentId, input: {} }) + : null, + ); + const threads = archivedThreadsOfBoard(query.data?.threads ?? [], props.board); + + const act = async (action: "restore" | "delete", thread: ArchivedBoardThread) => { + if (pending !== null) return; + setPending(thread.threadId); + const target = scopeThreadRef(props.environmentId, thread.threadId); + const result = await settlePromise( + async () => + await (action === "restore" + ? unarchiveThread(target) + : confirmAndDeleteThread(target, thread.title)), + ); + setPending(null); + const failure = + result._tag === "Failure" ? result : result.value._tag === "Failure" ? result.value : null; + if (failure) { + const error = squashAtomCommandFailure(failure); + toastManager.add({ + type: "error", + title: + action === "restore" + ? "Could not restore the conversation" + : "Could not delete the conversation", + description: error instanceof Error ? error.message : String(error), + }); + return; + } + query.refresh(); + }; + + return ( + + + } + > + + + + Archived task conversations +

+ A task that was deleted, or whose project was removed, leaves its conversation here. It is + in no thread list. +

+ {query.error ? ( +

+ {query.error} +

+ ) : threads.length === 0 ? ( +

+ {query.isPending ? "Loading…" : "No archived conversations on this board."} +

+ ) : ( +
    + {threads.map((thread) => ( +
  • +
    + +

    + {props.board === "all" ? `${thread.board} · ` : null} + Archived +

    +
    + + +
  • + ))} +
+ )} +
+
+ ); +} diff --git a/apps/web/src/components/delivery/BoardPage.tsx b/apps/web/src/components/delivery/BoardPage.tsx index 9ddb0a0b201e6..1002772d291e6 100644 --- a/apps/web/src/components/delivery/BoardPage.tsx +++ b/apps/web/src/components/delivery/BoardPage.tsx @@ -52,6 +52,7 @@ import { } from "../../state/delivery"; import { BoardEngineNotice, BoardNotice, CloseNoticeButton } from "./BoardEngineNotice"; import { EngineAttentionBar } from "./EnginePanel"; +import { ArchivedBoardThreads } from "./ArchivedBoardThreads"; import { BoardToolbar } from "./BoardToolbar"; import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { SidebarInset } from "../ui/sidebar"; @@ -732,7 +733,14 @@ function EnvironmentBoardPage({ environmentId }: { readonly environmentId: Envir onEdit={(item) => setDialog({ kind: "view", editing: item })} /> } - help={} + help={ + <> + {active && !shared ? ( + + ) : null} + + + } filters={filters} grouping={grouping} view={view} diff --git a/packages/client-runtime/src/state/delivery.ts b/packages/client-runtime/src/state/delivery.ts index 3b42c784340c5..87577dd3b3d59 100644 --- a/packages/client-runtime/src/state/delivery.ts +++ b/packages/client-runtime/src/state/delivery.ts @@ -23,6 +23,12 @@ export function createDeliveryEnvironmentAtoms( tag: WS_METHODS.deliveryRead, staleTimeMs: 2_000, }), + /** The archived conversations of board tasks, for the board's own list of them. */ + archivedBoardThreads: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:delivery:archived-board-threads", + tag: WS_METHODS.deliveryArchivedBoardThreads, + staleTimeMs: 2_000, + }), /** A thread's team, or the team choice that is still held. Cheap, and read often. */ threadBinding, /** Query families include the environment and thread; previous query values never carry over. */ diff --git a/packages/contracts/src/delivery.ts b/packages/contracts/src/delivery.ts index afbc71f7a106a..07a5724db3e49 100644 --- a/packages/contracts/src/delivery.ts +++ b/packages/contracts/src/delivery.ts @@ -1,7 +1,7 @@ // Relay engine-owned payloads as JSON; type only the state T3 stores or acts on. import * as Schema from "effect/Schema"; -import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; import { ModelSelection } from "./modelSelection.ts"; export const DeliveryOrchestrationConfig = Schema.Struct({ @@ -220,6 +220,26 @@ export const DeliveryThreadState = Schema.Struct({ }); export type DeliveryThreadState = typeof DeliveryThreadState.Type; +/** + * The archived conversations of board tasks. A task that ended (deleted, its project removed, or + * held by another conversation) leaves its thread archived, and no thread list shows it: this is + * how the board reaches them. + */ +export const DeliveryArchivedBoardThreads = Schema.Struct({ + threads: Schema.Array( + Schema.Struct({ + threadId: ThreadId, + projectId: ProjectId, + title: Schema.String, + archivedAt: Schema.String, + /** The board and the task the thread was made for. */ + board: Schema.String, + taskId: Schema.String, + }), + ), +}); +export type DeliveryArchivedBoardThreads = typeof DeliveryArchivedBoardThreads.Type; + /** Replaces who joins a conversation from its next message on; null makes it an ordinary one. */ export const DeliverySetThreadLineupInput = Schema.Struct({ threadId: ThreadId, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index a45f1dc296a3b..48cfa729d179f 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -71,6 +71,7 @@ import { DeliveryThreadBinding, DeliveryThreadBindingInput, DeliveryThreadState, + DeliveryArchivedBoardThreads, } from "./delivery.ts"; import { AcpRegistryAcceptUrlAuthInput, @@ -636,6 +637,7 @@ export const WS_METHODS = { deliveryAct: "delivery.act", deliveryBindThread: "delivery.bindThread", deliveryThreadBinding: "delivery.threadBinding", + deliveryArchivedBoardThreads: "delivery.archivedBoardThreads", deliveryReleaseThread: "delivery.releaseThread", deliverySetThreadLineup: "delivery.setThreadLineup", scheduledTasksList: "scheduledTasks.list", @@ -1186,6 +1188,13 @@ const WsDeliveryBindThreadRpc = Rpc.make(WS_METHODS.deliveryBindThread, { error: Schema.Union([EnvironmentAuthorizationError, DeliveryError]), }); +/** The archived conversations of board tasks, which no thread list shows. */ +const WsDeliveryArchivedBoardThreadsRpc = Rpc.make(WS_METHODS.deliveryArchivedBoardThreads, { + payload: Schema.Struct({}), + success: DeliveryArchivedBoardThreads, + error: Schema.Union([EnvironmentAuthorizationError, DeliveryError]), +}); + /** Both null for a thread that was never bound: a manual or legacy thread. */ const WsDeliveryThreadBindingRpc = Rpc.make(WS_METHODS.deliveryThreadBinding, { payload: DeliveryThreadBindingInput, @@ -2715,6 +2724,7 @@ export const ForkWsRpcGroup = RpcGroup.make( WsDeliveryActRpc, WsDeliveryBindThreadRpc, WsDeliveryThreadBindingRpc, + WsDeliveryArchivedBoardThreadsRpc, WsDeliveryReleaseThreadRpc, WsDeliverySetThreadLineupRpc, WsServerSubscribeCheckoutUpdateRpc, From ad361b47cfc0b4f84e73f51d01403491ab885fdb Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Sun, 22 Nov 2026 04:59:19 +0000 Subject: [PATCH 05/13] feat(web): a card says what was said on it, and the waiting lane what it owes The card carries the engine's message count, how many are new and the last line. The Waiting on you lane adds up its open questions and sign-offs in its header. A board task's conversation raises nothing in the sidebar or as a notification, so the card and this lane are where a person sees they are asked. Every number is a field the engine already sends on the card. Co-Authored-By: Claude Fable 5.2 --- .../delivery/BoardLanes.browser.test.tsx | 15 ++++++ .../web/src/components/delivery/BoardPage.tsx | 29 ++++++++++- .../web/src/components/delivery/taskParts.tsx | 31 +++++++++++ apps/web/src/lib/boardLaneCards.test.ts | 51 ++++++++++++++++++- apps/web/src/lib/boardLaneCards.ts | 39 ++++++++++++++ 5 files changed, 163 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/delivery/BoardLanes.browser.test.tsx b/apps/web/src/components/delivery/BoardLanes.browser.test.tsx index 8f8d2d77d0b63..83abc1d28b3d6 100644 --- a/apps/web/src/components/delivery/BoardLanes.browser.test.tsx +++ b/apps/web/src/components/delivery/BoardLanes.browser.test.tsx @@ -77,6 +77,15 @@ const LANES: ReadonlyArray = [ { actor: "Sam", decision: "approve", stands: true }, ], paused: { needsPerson: true }, + messages: 128, + unread: 12, + last: { + at: "2026-11-22T10:00:00Z", + by: "lead-developer-with-a-long-seat-name", + from: "team", + kind: "reply", + text: "A long last line that has to be cut short on the card instead of widening it.", + }, }), ), ], @@ -158,5 +167,11 @@ it.each(CASES)( expect( screen.container.querySelector('[data-lane="an-engine-lane-this-build-has-not-heard-of"]'), ).not.toBeNull(); + // The waiting lane says what it owes in all, and the card what was said, inside their widths. + const waiting = screen.container.querySelector('[data-lane="needs-decision"]'); + expect(waiting?.querySelector('[data-lane-questions="3"]')).not.toBeNull(); + expect(waiting?.querySelector('[data-lane-sign-offs="1"]')).not.toBeNull(); + expect(waiting?.querySelector('[data-card-unread="12"]')).not.toBeNull(); + expect(waiting?.querySelector("[data-card-last]")).not.toBeNull(); }, ); diff --git a/apps/web/src/components/delivery/BoardPage.tsx b/apps/web/src/components/delivery/BoardPage.tsx index 1002772d291e6..0184d612a7702 100644 --- a/apps/web/src/components/delivery/BoardPage.tsx +++ b/apps/web/src/components/delivery/BoardPage.tsx @@ -17,7 +17,7 @@ import { useGT, useMessages } from "gt-react"; import { memo, useEffect, useMemo, useState } from "react"; import { isElectron } from "../../env"; -import { queuePlaces, reworkOf, waitKindsOf } from "../../lib/boardLaneCards"; +import { laneWaitCounts, queuePlaces, reworkOf, waitKindsOf } from "../../lib/boardLaneCards"; import { BOARD_LANE, boardLaneOf, boardLaneTitle, regroupLanes } from "../../lib/boardLanes"; import { deliveryEnvironmentChoice, @@ -62,6 +62,7 @@ import { InWorkSections, QueueLine, ReworkCount, WaitKinds } from "./BoardLaneCa import { TaskEditor } from "./TaskEditor"; import { Age, + CardActivity, CardPeople, CardSigns, laneTone, @@ -88,6 +89,30 @@ import { DeliveryDiagnosticNotice } from "./DeliveryDiagnosticNotice"; import { deliveryReadDiagnostic } from "../../lib/deliveryStates"; import { TaskDisclosure } from "./TaskDisclosure"; +/** + * What the Waiting on you lane owes in all: its open questions and its sign-offs. A board task's + * conversation raises nothing in the sidebar or as a notification, so this lane is where a + * person sees that they are asked. + */ +function LaneWaitCounts(props: { readonly cards: ReadonlyArray }) { + const { questions, signOffs } = laneWaitCounts(props.cards); + if (questions === 0 && signOffs === 0) return null; + return ( + + {questions > 0 ? ( + + {questions} {questions === 1 ? "question" : "questions"} + + ) : null} + {signOffs > 0 ? ( + + {signOffs} {signOffs === 1 ? "sign-off" : "sign-offs"} + + ) : null} + + ); +} + const CardFace = memo(function CardFace(props: { readonly card: DeliveryCard; readonly now: number; @@ -142,6 +167,7 @@ const CardFace = memo(function CardFace(props: { {card.blocker}

) : null} +
{showsKinds ? null : } @@ -349,6 +375,7 @@ export function Lane(props: { {lane.cards.length} {lane.cards.length !== props.total ? ` of ${props.total}` : ""} + {lane.lane === BOARD_LANE.needsDecision ? : null} {props.dragged && offer ? ( {offer} ) : null} diff --git a/apps/web/src/components/delivery/taskParts.tsx b/apps/web/src/components/delivery/taskParts.tsx index 2c24a48bc75e4..f47f4a390fddb 100644 --- a/apps/web/src/components/delivery/taskParts.tsx +++ b/apps/web/src/components/delivery/taskParts.tsx @@ -16,6 +16,7 @@ import { type TaskPriority, type TaskView, } from "../../lib/delivery"; +import { cardActivityOf } from "../../lib/boardLaneCards"; import { ageLabel, initialsOf, PRIORITY_LABEL } from "../../lib/deliveryBoard"; import { harnessLabel } from "../../lib/deliverySeats"; import { cn } from "../../lib/utils"; @@ -304,6 +305,36 @@ export function CardPeople(props: { readonly card: DeliveryCard }) { ); } +/** + * What was said on a task, for its card: how much, how much of it is new, and the last line. The + * full text stays in the conversation. Every part is the engine's own count. + */ +export function CardActivity(props: { readonly card: DeliveryCard }) { + const activity = cardActivityOf(props.card); + if (activity === null) return null; + return ( +

+ + {plural(activity.messages, "message", "messages")} + + {activity.unread > 0 ? ( + + {activity.unread} new + + ) : null} + {activity.text ? ( + + {activity.by ? `${activity.by}: ` : ""} + {activity.text} + + ) : null} +

+ ); +} + export function WaitingOn(props: { readonly card: DeliveryCard; readonly className?: string }) { const { card } = props; if (!card.waitingOn) return null; diff --git a/apps/web/src/lib/boardLaneCards.test.ts b/apps/web/src/lib/boardLaneCards.test.ts index 8a1071f0f8f61..9ad490d9bd009 100644 --- a/apps/web/src/lib/boardLaneCards.test.ts +++ b/apps/web/src/lib/boardLaneCards.test.ts @@ -1,6 +1,14 @@ import { describe, expect, it } from "vite-plus/test"; -import { queuePlaces, reworkOf, waitKindsOf, workSections, workStageOf } from "./boardLaneCards"; +import { + cardActivityOf, + laneWaitCounts, + queuePlaces, + reworkOf, + waitKindsOf, + workSections, + workStageOf, +} from "./boardLaneCards"; import { parseCard } from "./delivery"; const card = (extra: Record = {}) => @@ -102,4 +110,45 @@ describe("what a person owes a card", () => { expect(owed({ lane: "draft", actions: ["submit"] })).toEqual([]); expect(owed({ lane: "paused", actions: ["resume"] })).toEqual(["resume"]); }); + + it("adds up a lane's questions and sign-offs from the cards that wait on a person", () => { + const waiting = (extra: Record) => + card({ waitsOnPerson: true, waitingOn: "person", ...extra }); + expect( + laneWaitCounts([ + waiting({ questions: 2 }), + waiting({ questions: 1, actions: ["approve", "reject"] }), + waiting({ actions: ["approve"], approveStands: true }), + // Not waiting on a person: its questions and its approve action are not owed by one. + card({ questions: 5, actions: ["approve"] }), + ]), + ).toEqual({ questions: 3, signOffs: 1 }); + expect(laneWaitCounts([])).toEqual({ questions: 0, signOffs: 0 }); + }); +}); + +describe("what was said on a card", () => { + const last = { + at: "2026-11-22T10:00:00Z", + by: "lead", + from: "team", + kind: "reply", + text: "Done.", + }; + + it("gives the engine's counts and its last line, and nothing when nothing was said", () => { + expect(cardActivityOf(card({ messages: 4, unread: 2, last }))).toEqual({ + messages: 4, + unread: 2, + by: "lead", + text: "Done.", + }); + expect(cardActivityOf(card())).toBeNull(); + expect(cardActivityOf(card({ messages: 1 }))).toEqual({ + messages: 1, + unread: 0, + by: null, + text: null, + }); + }); }); diff --git a/apps/web/src/lib/boardLaneCards.ts b/apps/web/src/lib/boardLaneCards.ts index a83f955d0b2cb..0a1ffd979b0a5 100644 --- a/apps/web/src/lib/boardLaneCards.ts +++ b/apps/web/src/lib/boardLaneCards.ts @@ -157,6 +157,45 @@ export function waitKindsOf(card: Waiting): ReadonlyArray { return kinds.length > 0 ? kinds : ["other"]; } +/** + * What was said on a card, as the engine counts it: how many messages, how many of them new to + * the person, and the last one's line. Null when nothing was said. The engine keeps these today + * from its own log; the conversation's activity is mirrored onto them by a later engine slice. + */ +export function cardActivityOf(card: Pick): { + readonly messages: number; + readonly unread: number; + readonly by: string | null; + readonly text: string | null; +} | null { + if (card.messages <= 0 && card.unread <= 0 && !card.last?.text) return null; + return { + // The engine counts both; a count it sent smaller than the other is still not made up here. + messages: card.messages, + unread: card.unread, + by: card.last?.text ? card.last.by || null : null, + text: card.last?.text ? card.last.text : null, + }; +} + +/** + * What a lane of waiting cards owes in all: the open questions and the sign-offs, added up from + * the same card fields `waitKindsOf` reads. A card that does not wait on a person adds nothing. + */ +export function laneWaitCounts(cards: ReadonlyArray): { + readonly questions: number; + readonly signOffs: number; +} { + let questions = 0; + let signOffs = 0; + for (const card of cards) { + const kinds = waitKindsOf(card); + if (kinds.includes("question")) questions += card.questions; + if (kinds.includes("sign-off")) signOffs += 1; + } + return { questions, signOffs }; +} + /** Who has approved the task and still stands, for the sign-off line. */ export const standingApprovers = (card: Pick): ReadonlyArray => card.approvals From 015d5a5b13766be7bf3110bc459164772151606d Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Sun, 22 Nov 2026 05:17:16 +0000 Subject: [PATCH 06/13] fix(server): a marker refuses an id it cannot carry; link writes queue and read back The marker no longer escapes its ids. A task id is what the engine's routes take ([\w-]+) and a board id carries no colon, whitespace or control character; an id outside that is refused at write (boardTaskOf), so the task gets no thread and no link, and board-task:a:b reads one way. The pin covers only the two ids T3 writes into the marker: a thread id the engine supplies in boardThread is taken as it is. Every boardThread write waits in one server-side queue. On a 409 conflict the current link is read from the engine and stands; the thread made here is archived. moved and not-found are final: the thread is archived and an archived thread is never linked, on a later pass or after a restart, until a person restores it. Co-Authored-By: Claude Fable 5.2 --- .../src/delivery/BoardTaskThreads.test.ts | 102 ++++++++++++++---- apps/server/src/delivery/BoardTaskThreads.ts | 65 ++++++----- .../src/delivery/boardThreadEngine.testkit.ts | 29 +++-- .../src/delivery/boardThreadMarker.test.ts | 77 +++++++------ apps/server/src/delivery/boardThreadMarker.ts | 39 +++---- .../ThreadLaunchService.test.ts | 8 +- 6 files changed, 206 insertions(+), 114 deletions(-) diff --git a/apps/server/src/delivery/BoardTaskThreads.test.ts b/apps/server/src/delivery/BoardTaskThreads.test.ts index a15c2a44bb2bf..e4c2186813257 100644 --- a/apps/server/src/delivery/BoardTaskThreads.test.ts +++ b/apps/server/src/delivery/BoardTaskThreads.test.ts @@ -27,6 +27,7 @@ import { } from "./boardThreadEngine.testkit.ts"; import * as BoardThreadRows from "./boardThreadRows.ts"; import { + boardTaskOf, boardTaskOfMarker, boardTaskThreadCommandId, boardTaskThreadId, @@ -34,7 +35,7 @@ import { import * as DeliveryService from "./DeliveryService.ts"; // Every case here runs against the scratch engine of boardThreadEngine.testkit.ts, through the -// delivery service's real request path. None of it has run against the merged engine half. +// delivery service's real request path. BoardTaskThreads.engine.test.ts runs the real engine. const ENVIRONMENT = EnvironmentId.make("471fea73-5365-4bbb-96eb-8e35be50eaec"); const OTHER = "0d9b2f0e-other-environment"; @@ -132,7 +133,10 @@ function service( Effect.provideService(ProjectionStore.ProjectionStoreV2, { getThreadRecords: (threadId: string) => Effect.succeed({ - thread: { lineage: { engineIntake: store.threads.get(threadId)?.marker } }, + thread: { + lineage: { engineIntake: store.threads.get(threadId)?.marker }, + archivedAt: store.threads.get(threadId)?.archivedAt ?? null, + }, }), } as unknown as ProjectionStore.ProjectionStoreV2["Service"]), Effect.provideService(ProjectStore.ProjectStoreV2, { @@ -189,10 +193,13 @@ function board(options: Parameters[0] = {}) { return engine; } -const TASK = { board: "work", id: "task-7" }; +const TASK = boardTaskOf("work", "task-7")!; const THREAD = boardTaskThreadId(TASK); +const THEIRS = "thread:their/board-task:a:b%3Ac"; const creates = (store: ThreadStore) => store.commands.filter((command) => command.type === "thread.create"); +const puts = (engine: ScratchEngine) => + engine.requests.filter((request) => request.method === "PUT"); const linkWrites = (engine: ScratchEngine) => engine.events.filter((event) => event.kind === "task.board-thread-set"); @@ -287,17 +294,23 @@ it.effect("adopts the link another writer set first and never overwrites it", () const store = threadStore(); return Effect.gen(function* () { engine.beforeNextPut(() => { - engine.writeLink("task-7", { environmentId: OTHER, threadId: "their-thread", setBy: OTHER }); + engine.writeLink("task-7", { environmentId: OTHER, threadId: THEIRS, setBy: OTHER }); }); const threads = yield* service(store); yield* threads.reconcile(); - assert.equal(engine.linkOf("task-7")?.threadId, "their-thread"); + // The engine's value is read back after the refusal and stands as it was written: a thread id + // of another environment keeps its colons, slash and percent sign. + assert.deepEqual( + engine.requests.slice(-2).map((request) => `${request.method} ${request.path}`), + ["PUT /api/tasks/task-7/board-thread", "GET /api/tasks/task-7"], + ); + assert.equal(engine.linkOf("task-7")?.threadId, THEIRS); assert.equal(engine.linkOf("task-7")?.setBy, OTHER); // The thread made here holds no task: it is archived, not deleted, and claims nothing. assert.isNotNull(store.threads.get(THREAD)!.archivedAt); assert.isNull(engine.leaseOf("task-7")); yield* threads.reconcile(); - assert.equal(engine.linkOf("task-7")?.threadId, "their-thread"); + assert.equal(engine.linkOf("task-7")?.threadId, THEIRS); assert.equal(linkWrites(engine).length, 1); assert.equal(engine.requests.filter((request) => request.method === "PUT").length, 1); }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-conflict-"))); @@ -322,30 +335,75 @@ it.effect("makes no thread for a moved task, and archives one the engine refuses assert.isNull(engine.leaseOf("task-7")); // The task that had already moved was never given a thread or a write. assert.isFalse(engine.requests.some((request) => request.path.includes("moved-1"))); + // The refusal is final: a later pass that sees the task in work, on this server or on a new + // one after a restart, writes nothing while the thread stays archived. + engine.task("task-7").state = "running"; + assert.deepEqual([...(yield* threads.reconcile())], [["task-7", "archived-thread"]]); + assert.deepEqual( + [...(yield* (yield* service(store)).reconcile())], + [["task-7", "archived-thread"]], + ); + assert.equal(puts(engine).length, 1); + assert.isNull(engine.linkOf("task-7")); }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-moved-"))); }); -it.effect("keeps two tasks apart when a board id carries the separator", () => { +it.effect("archives the thread of a task the engine no longer has, and never asks again", () => { const engine = board(); - engine.setBoard("team:alpha", REPO); - engine.setBoard("team", REPO); - engine.addTask({ id: "t1", set: "team:alpha" }); - engine.addTask({ id: "alpha-t1", set: "team" }); + engine.addTask({ id: "task-7" }); const store = threadStore(); return Effect.gen(function* () { + // The task is deleted after the lanes were read and before the link is written. + store.hooks.afterCreate = () => engine.removeTask("task-7"); const threads = yield* service(store); assert.deepEqual([...(yield* threads.reconcile())], []); - const first = boardTaskThreadId({ board: "team:alpha", id: "t1" }); - const second = boardTaskThreadId({ board: "team", id: "alpha-t1" }); - assert.notEqual(first, second); - assert.deepEqual([...store.threads.keys()].toSorted(), [first, second].toSorted()); - // The engine takes a thread id with a colon and a percent sign as it is. - assert.equal(engine.linkOf("t1")?.threadId, first); - assert.equal(engine.linkOf("alpha-t1")?.threadId, second); - assert.deepEqual(boardTaskOfMarker(store.threads.get(first)!.marker), { - board: "team:alpha", - id: "t1", + assert.isNotNull(store.threads.get(THREAD)!.archivedAt); + assert.equal(puts(engine).length, 1); + engine.addTask({ id: "task-7" }); + assert.deepEqual( + [...(yield* (yield* service(store)).reconcile())], + [["task-7", "archived-thread"]], + ); + assert.equal(puts(engine).length, 1); + assert.isNull(engine.linkOf("task-7")); + assert.equal(store.threads.size, 1); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-not-found-"))); +}); + +it.effect("sends the engine one link write at a time, however many tasks have no link", () => { + const engine = board(); + const ids = Array.from({ length: 12 }, (_, index) => `task-${index}`); + for (const id of ids) engine.addTask({ id }); + const store = threadStore(); + return Effect.gen(function* () { + const threads = yield* service(store); + yield* Effect.all([threads.reconcile(), threads.reconcile(), threads.reconcile()], { + concurrency: "unbounded", }); + assert.equal(engine.linkWrites.most, 1); + assert.equal(puts(engine).length, ids.length); + assert.deepEqual( + ids.map((id) => engine.linkOf(id)?.threadId), + ids.map((id) => boardTaskThreadId(boardTaskOf("work", id)!)), + ); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-queue-"))); +}); + +it.effect("refuses a board id with a colon at write, and links a thread id that has them", () => { + const engine = board(); + engine.setBoard("team:alpha", REPO); + engine.addTask({ id: "t1", set: "team:alpha" }); + engine.addTask({ id: "task-7" }); + const store = threadStore(); + return Effect.gen(function* () { + const threads = yield* service(store); + // No thread, no command and no write for the id the marker cannot carry. + assert.deepEqual([...(yield* threads.reconcile())], [["t1", "unmarkable-id"]]); + assert.deepEqual([...store.threads.keys()], [THREAD]); + assert.isFalse(engine.requests.some((request) => request.path.includes("/t1/"))); + // The thread id T3 writes carries two colons, and the engine takes it as it is. + assert.equal(THREAD.split(":").length, 3); + assert.equal(engine.linkOf("task-7")?.threadId, THREAD); }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-colon-"))); }); @@ -426,7 +484,7 @@ it.effect( return Effect.gen(function* () { const threads = yield* service(store); yield* threads.reconcile(); - const finished = boardTaskThreadId({ board: "work", id: "task-8" }); + const finished = boardTaskThreadId(boardTaskOf("work", "task-8")!); engine.task("task-8").lane = "completed"; engine.task("task-8").state = "completed"; engine.removeTask("task-7"); diff --git a/apps/server/src/delivery/BoardTaskThreads.ts b/apps/server/src/delivery/BoardTaskThreads.ts index 81e68bf43d9f6..539ea04d6fd73 100644 --- a/apps/server/src/delivery/BoardTaskThreads.ts +++ b/apps/server/src/delivery/BoardTaskThreads.ts @@ -28,6 +28,7 @@ import * as ServerSettings from "../serverSettings.ts"; import { forkParked } from "../serverActivation.ts"; import * as BoardThreadRows from "./boardThreadRows.ts"; import { + boardTaskOf, boardTaskOfMarker, boardTaskThreadCommandId, boardTaskThreadId, @@ -87,12 +88,14 @@ const Refusal = Schema.Struct({ current: Schema.optional(Schema.NullOr(BoardThread)), }); const Linked = Schema.Struct({ boardThread: BoardThread }); +const Detail = Schema.Struct({ boardThread: Schema.NullOr(BoardThread) }); const Claimed = Schema.Struct({ holder: Schema.String }); const decodeLanes = Schema.decodeUnknownEffect(Lanes); const decodeTeams = Schema.decodeUnknownEffect(Teams); const decodeRefusal = Schema.decodeUnknownOption(Refusal); const decodeLinked = Schema.decodeUnknownEffect(Linked); +const decodeDetail = Schema.decodeUnknownOption(Detail); const decodeClaimed = Schema.decodeUnknownOption(Claimed); const decodeSelection = Schema.decodeUnknownEffect(ModelSelection); @@ -116,12 +119,14 @@ export const BOARD_THREAD_KEY_VARIABLE = "T3_DELIVERY_BOARD_THREAD_KEY"; /** Why a started task has no conversation of its own yet. Told in the log, never guessed around. */ export type BoardThreadHold = | "no-board" + | "unmarkable-id" | "no-project" | "no-lead" | "no-lead-model" | "no-provider" | "ambiguous-provider" | "foreign-thread" + | "archived-thread" | "no-key" | "refused" | "moved"; @@ -166,6 +171,9 @@ export const make = Effect.gen(function* () { const rows = yield* BoardThreadRows.BoardThreadRows; const hostEnvironment = yield* HostProcess.Environment; const lock = yield* Semaphore.make(1); + // The one queue every `boardThread` write of this server waits in: the engine is sent one link + // write at a time, which also bounds the first run, when every open task shows no link. + const linkWrites = yield* Semaphore.make(1); // The token of each claim this server holds. It is kept in memory only: after a restart the // old lease lapses within its window and the task is claimed again, still by the same thread. const holders = new Map(); @@ -254,6 +262,13 @@ export const make = Effect.gen(function* () { .pipe(Effect.ignore); }); + const writeLink = (taskId: string, body: unknown) => + linkWrites.withPermits(1)( + delivery + .boardThreadAct({ method: "PUT", path: `/api/tasks/${taskId}/board-thread`, body }) + .pipe(Effect.result), + ); + /** A started task with no conversation: make its thread once, and tell the engine. */ const bind = Effect.fn("BoardTaskThreads.bind")(function* ( card: Card, @@ -265,7 +280,8 @@ export const make = Effect.gen(function* () { }, ) { if (!card.set) return "no-board" as const; - const task = { board: card.set, id: card.id }; + const task = boardTaskOf(card.set, card.id); + if (task === null) return "unmarkable-id" as const; const threadId = boardTaskThreadId(task); const folder = context.folders.get(card.set); const project = @@ -300,31 +316,32 @@ export const make = Effect.gen(function* () { const created = yield* local(projections.getThreadRecords(threadId, [])); const stamped = boardTaskOfMarker(created.thread.lineage.engineIntake); if (stamped?.board !== task.board || stamped.id !== task.id) return "foreign-thread" as const; + // An archived thread is never linked: it was displaced, its task was refused for good, or a + // person archived it. Restoring it from the board's archive is what lets it be linked. + if (created.thread.archivedAt !== null) return "archived-thread" as const; if (context.key === undefined) return "no-key" as const; - const put = yield* delivery - .boardThreadAct({ - method: "PUT", - path: `/api/tasks/${card.id}/board-thread`, - body: { - environmentId: context.environmentId, - threadId, - setBy: context.environmentId, - // No link was set when the lanes were read. A writer in between is answered 409. - expect: null, - key: context.key, - }, - }) - .pipe(Effect.result); + const put = yield* writeLink(card.id, { + environmentId: context.environmentId, + threadId, + setBy: context.environmentId, + // No link was set when the lanes were read. A writer in between is answered 409. + expect: null, + key: context.key, + }); if (put._tag === "Success") { yield* engine(decodeLinked(put.success.body)); yield* holdClaim(card, context.environmentId, threadId); return null; } + // The refusal's `code` decides, never its words. const refusal = refusalOf(put.failure); if (refusal.code === "conflict") { - // Another writer set the link first. Its value stands and is never overwritten; the thread - // made here holds no task, so it is archived, where the board still reaches it. - const held = refusal.current; + // Another writer set the link first. The engine's value is read and stands, never + // overwritten; a thread made here that it does not name holds no task and is archived, + // where the board still reaches it. + const read = yield* delivery.read({ path: `/api/tasks/${card.id}` }).pipe(Effect.result); + const detail = read._tag === "Success" ? decodeDetail(read.success.body) : Option.none(); + const held = Option.isSome(detail) ? detail.value.boardThread : refusal.current; if (held?.environmentId === context.environmentId && held.threadId === threadId) { yield* holdClaim(card, context.environmentId, threadId); return null; @@ -332,13 +349,11 @@ export const make = Effect.gen(function* () { yield* archive(task, threadId, "displaced"); return null; } - if (refusal.code === "moved") { - yield* archive(task, threadId, "moved"); - return "moved" as const; - } - if (refusal.code === "not-found") { - yield* archive(task, threadId, "deleted"); - return null; + if (refusal.code === "moved" || refusal.code === "not-found") { + // The task is worked on another machine, or is gone: it is finished for this server. The + // archive is what keeps it so, on every later pass and after a restart. + yield* archive(task, threadId, refusal.code === "moved" ? "moved" : "deleted"); + return refusal.code === "moved" ? ("moved" as const) : null; } if (refusal.code === "refused") return "refused" as const; return yield* new BoardTaskThreadsError({ reason: "engine", cause: put.failure }); diff --git a/apps/server/src/delivery/boardThreadEngine.testkit.ts b/apps/server/src/delivery/boardThreadEngine.testkit.ts index 0c8fef9ddcdf2..37c43087cdc42 100644 --- a/apps/server/src/delivery/boardThreadEngine.testkit.ts +++ b/apps/server/src/delivery/boardThreadEngine.testkit.ts @@ -1,6 +1,6 @@ // A scratch engine serving the frozen task-to-thread contract (BOARD-REVAMP-UI-SPEC.md 6a), with -// the shapes of the unmerged engine half (Operation-PaperClip pull request 167, at 1d8fc1db) and -// the task claim of slice 1. A model, not the engine: what passes here must still pass there. +// the shapes of the merged engine half (Operation-PaperClip main at a658892b) and the task claim +// of slice 1. A model, not the engine: BoardTaskThreads.engine.test.ts runs against the real one. import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -72,6 +72,8 @@ export function scratchEngine( let clock = Date.parse("2026-11-22T10:00:00.000Z"); let holderSeq = 0; let down = false; + /** Link writes the engine is answering now, and the most it ever answered at once. */ + const linkWrites = { inFlight: 0, most: 0 }; /** Runs once, just before the next link write is admitted: another writer getting in first. */ let beforeNextPut: (() => void) | null = null; @@ -318,6 +320,7 @@ export function scratchEngine( down = value; }, isDown: () => down, + linkWrites, }; } @@ -335,13 +338,25 @@ export const scratchEngineHttp = (engine: ScratchEngine) => request.body._tag === "Uint8Array" ? decodeJson(new TextDecoder().decode(request.body.body)) : undefined; - const answer = engine.handle(request.method, url.pathname, body); - return Effect.succeed( - HttpClientResponse.fromWeb( + const answer = () => { + const { status, body: answered } = engine.handle(request.method, url.pathname, body); + return HttpClientResponse.fromWeb( request, - answer.status === 204 + status === 204 ? new Response(null, { status: 204 }) - : Response.json(answer.body, { status: answer.status }), + : Response.json(answered, { status }), + ); + }; + if (request.method !== "PUT") return Effect.sync(answer); + // A link write takes a turn of the scheduler, so two sent at once would be seen together. + engine.linkWrites.inFlight += 1; + engine.linkWrites.most = Math.max(engine.linkWrites.most, engine.linkWrites.inFlight); + return Effect.yieldNow.pipe( + Effect.map(answer), + Effect.ensuring( + Effect.sync(() => { + engine.linkWrites.inFlight -= 1; + }), ), ); }), diff --git a/apps/server/src/delivery/boardThreadMarker.test.ts b/apps/server/src/delivery/boardThreadMarker.test.ts index 380cc10b04b1f..bf80180241297 100644 --- a/apps/server/src/delivery/boardThreadMarker.test.ts +++ b/apps/server/src/delivery/boardThreadMarker.test.ts @@ -6,12 +6,15 @@ import { assert, it } from "@effect/vitest"; import { BOARD_TASK_MARKER_LIKE, + boardTaskOf, boardTaskOfMarker, boardTaskThreadCommandId, boardTaskThreadId, boardTaskThreadMarker, } from "./boardThreadMarker.ts"; +const TASK = boardTaskOf("board-1", "task-7")!; + // A board task's thread reuses `lineage.engineIntake` as its marker, with a value of its own. That // is safe only while every reader but the engine intake asks whether the field is set, never what // it holds: a reader of the value would treat a board thread as an intake, or find a thread from a @@ -107,60 +110,54 @@ it("only the engine intake and the named board task readers read the marker's va }); it("nothing but the marker module knows what a board task's marker looks like", () => { - assert.equal( - boardTaskThreadMarker({ board: "board-1", id: "task-7" }), - "board-task:board-1:task-7", - ); + assert.equal(boardTaskThreadMarker(TASK), "board-task:board-1:task-7"); assert.deepEqual( [...new Set(linesNaming(/board-task:/).map(({ file }) => file))], ["apps/server/src/delivery/boardThreadMarker.ts"], ); }); -it("keeps a colon in a board or task id from making two tasks one marker", () => { - const pairs = [ - [ - { board: "a:b", id: "c" }, - { board: "a", id: "b:c" }, - ], - [ - { board: "a%3Ab", id: "c" }, - { board: "a:b", id: "c" }, - ], - [ - { board: "a", id: "b" }, - { board: "a:", id: "b" }, - ], - ] as const; - for (const [left, right] of pairs) { - assert.notEqual(boardTaskThreadMarker(left), boardTaskThreadMarker(right)); - assert.notEqual(boardTaskThreadCommandId(left), boardTaskThreadCommandId(right)); - assert.notEqual(boardTaskThreadId(left), boardTaskThreadId(right)); +it("refuses an id the marker cannot carry at write, so no two tasks share a marker", () => { + for (const [board, id] of [ + // A colon in a task id, the engine's own separator in neither id. + ["a", "b:c"], + ["a:b", "c"], + ["a", ""], + ["", "b"], + ["a", "b c"], + ["a b", "c"], + ["a", "b/c"], + ["a", "b%3Ac"], + ] as const) { + assert.isNull(boardTaskOf(board, id), `${board} / ${id}`); } + // What the engine writes today passes, and the marker keeps the spelling already stamped. + const task = boardTaskOf("delivery-engine_tasks.and/board", "t_7-a"); + assert.isNotNull(task); + assert.equal(boardTaskThreadMarker(task!), "board-task:delivery-engine_tasks.and/board:t_7-a"); + assert.equal(boardTaskThreadId(task!), boardTaskThreadMarker(task!)); + assert.equal(boardTaskThreadCommandId(task!), `${boardTaskThreadMarker(task!)}:thread`); }); -it("reads the task back out of a marker, and nothing out of any other value", () => { - for (const task of [ - { board: "board-1", id: "task-7" }, - { board: "a:b", id: "c" }, - { board: "a", id: "b:c" }, - { board: "with/slash and space", id: "100%" }, - ]) { - assert.deepEqual(boardTaskOfMarker(boardTaskThreadMarker(task)), task); - } +it("reads the task back out of a marker, and ignores every malformed one", () => { + assert.deepEqual(boardTaskOfMarker(boardTaskThreadMarker(TASK)), TASK); + const prefix = BOARD_TASK_MARKER_LIKE.slice(0, -1); for (const value of [ null, undefined, "", - // An engine intake's admission. + // An engine intake's admission, and another prefix. `intake-${"a".repeat(64)}:0`, - BOARD_TASK_MARKER_LIKE, - `${BOARD_TASK_MARKER_LIKE.slice(0, -1)}only-a-board`, - `${BOARD_TASK_MARKER_LIKE.slice(0, -1)}a:b:c`, - `${BOARD_TASK_MARKER_LIKE.slice(0, -1)}:task`, - // Not the spelling the grammar writes, and a broken escape. - `${BOARD_TASK_MARKER_LIKE.slice(0, -1)}%61:b`, - `${BOARD_TASK_MARKER_LIKE.slice(0, -1)}%zz:b`, + "board-tasks:a:b", + "task:a:b", + // An empty id, and no task id at all. + prefix, + `${prefix}only-a-board`, + `${prefix}:task`, + `${prefix}board:`, + // A colon in the task id reads as a third part, never as board `a` with task `b:c`. + `${prefix}a:b:c`, + `${prefix}a:b c`, ]) { assert.equal(boardTaskOfMarker(value), null, String(value)); } diff --git a/apps/server/src/delivery/boardThreadMarker.ts b/apps/server/src/delivery/boardThreadMarker.ts index b3b4d72cd06b0..ddd8fadfe73ff 100644 --- a/apps/server/src/delivery/boardThreadMarker.ts +++ b/apps/server/src/delivery/boardThreadMarker.ts @@ -1,24 +1,35 @@ import { CommandId, ThreadId } from "@t3tools/contracts"; +declare const BoardTaskBrand: unique symbol; + +/** A board and one of its tasks, with ids the marker can carry. Made only by `boardTaskOf`. */ export interface BoardTask { readonly board: string; readonly id: string; + readonly [BoardTaskBrand]: true; } const PREFIX = "board-task:"; -// Each id is percent-encoded, so the colon that separates them can never come from an id: board -// `a:b` with task `c` and board `a` with task `b:c` are two markers. An id of letters, digits, -// `-` and `_` is spelled as it is, so the markers written before this grammar still read. -const part = (value: string) => encodeURIComponent(value); +// The pin covers the two ids T3 writes into the marker and nothing else. A task id is what the +// engine's routes take (`[\w-]+`); a board id has no colon, whitespace or control character, so +// the colon between them is never an id's and the marker is a thread id the engine accepts. +const BOARD_ID = /^[^\s\p{C}:]{1,256}$/u; +const TASK_ID = /^[\w-]{1,256}$/; + +/** + * The task a marker may be written for, or null for ids it cannot carry. An id with a colon is + * refused here, at write, and never escaped: such a task gets no thread and no link. + */ +export const boardTaskOf = (board: string, id: string): BoardTask | null => + BOARD_ID.test(board) && TASK_ID.test(id) ? ({ board, id } as BoardTask) : null; /** * The lineage marker of a board task's conversation: it keeps the thread out of every list. It is * stamped when the thread is created and never after. The engine holds a task's thread * (`boardThread`); the marker only says which task a thread was made for. */ -export const boardTaskThreadMarker = (task: BoardTask) => - `${PREFIX}${part(task.board)}:${part(task.id)}`; +export const boardTaskThreadMarker = (task: BoardTask) => `${PREFIX}${task.board}:${task.id}`; /** One create command per task, so starting a task twice makes one thread. */ export const boardTaskThreadCommandId = (task: BoardTask) => @@ -32,19 +43,11 @@ export const BOARD_TASK_MARKER_LIKE = `${PREFIX}%`; /** * Thread to task, and never the other way: the task a marker was stamped for, or null for a value - * that is no board task marker (an engine intake's admission, or a spelling this grammar does not - * write). A task's thread is read from the engine, never found by building a marker. + * that is no board task marker (an engine intake's admission, an empty id, a colon in an id). A + * task's thread is read from the engine, never found by building a marker. */ export function boardTaskOfMarker(marker: string | null | undefined): BoardTask | null { if (typeof marker !== "string" || !marker.startsWith(PREFIX)) return null; - const parts = marker.slice(PREFIX.length).split(":"); - if (parts.length !== 2) return null; - try { - const [board, id] = parts.map((value) => decodeURIComponent(value)) as [string, string]; - if (board === "" || id === "") return null; - // Only the spelling the grammar writes resolves, so no two markers name one task. - return boardTaskThreadMarker({ board, id }) === marker ? { board, id } : null; - } catch { - return null; - } + const [board, id, ...more] = marker.slice(PREFIX.length).split(":"); + return board === undefined || id === undefined || more.length > 0 ? null : boardTaskOf(board, id); } diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 1c1afc82e5462..4c5d838a1bdc9 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -10,7 +10,11 @@ import * as Path from "effect/Path"; import * as ServerConfig from "../config.ts"; import { createPendingAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts"; import * as ThreadMessageIntake from "./ThreadMessageIntake.ts"; -import { boardTaskThreadCommandId, boardTaskThreadMarker } from "../delivery/boardThreadMarker.ts"; +import { + boardTaskOf, + boardTaskThreadCommandId, + boardTaskThreadMarker, +} from "../delivery/boardThreadMarker.ts"; import { listBoardThreadRows } from "../delivery/boardThreadRows.ts"; import { assert, it, vi } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; @@ -545,7 +549,7 @@ it.effect("keeps a board task's thread out of both lists, however often it is cr yield* launches.launch( launchInput({ command: "command:top-level", thread: "thread:top-level" }), ); - const task = { board: "board-1", id: "task-7" }; + const task = boardTaskOf("board-1", "task-7")!; const threadId = ThreadId.make("thread:board-task"); const create = threads.dispatch({ type: "thread.create", From 1021e2e549847bb123a10f8312b6e90d888fd08e Mon Sep 17 00:00:00 2001 From: Tevin2119 Date: Sun, 22 Nov 2026 05:27:03 +0000 Subject: [PATCH 07/13] feat: a board task linked to a pull request or an issue shows as its task A board task's conversation is in no thread list, so the linked threads of a pull request or an issue left it out. It now returns as "Board task: " and opens the task view, conversation and engine facts together, never the raw thread: the row carries no thread id. The rows are selected on the board-task: marker prefix, apart from the ordinary list, whose exclusion of server-owned threads is untouched. The title is the engine's when it lists the task. A task it does not list (deleted, moved, or the engine away) keeps the title its thread was made with, and one whose conversation is archived is told as ended and opens the board, where the archive is. Mobile has no board: its issue screen shows the row and says where to open it. The three new strings are in every web and mobile catalog, machine-translated. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../src/features/issues/IssueRouteScreen.tsx | 23 +++++- apps/mobile/src/i18n/translations/de.json | 5 +- apps/mobile/src/i18n/translations/en.json | 5 +- apps/mobile/src/i18n/translations/es.json | 5 +- apps/mobile/src/i18n/translations/fr.json | 5 +- apps/mobile/src/i18n/translations/ja.json | 5 +- apps/mobile/src/i18n/translations/ko.json | 5 +- apps/mobile/src/i18n/translations/pt-BR.json | 5 +- apps/mobile/src/i18n/translations/ru.json | 5 +- apps/mobile/src/i18n/translations/sv.json | 5 +- apps/mobile/src/i18n/translations/zh.json | 5 +- .../src/delivery/BoardTaskThreads.test.ts | 2 + apps/server/src/delivery/boardThreadRows.ts | 9 +++ apps/server/src/delivery/linkedBoardTasks.ts | 80 +++++++++++++++++++ .../ThreadLaunchService.test.ts | 47 +++++++++++ apps/server/src/ws.ts | 25 +++++- apps/web/src/commandPaletteBus.ts | 8 +- .../components/CommandPalette.logic.test.ts | 37 +++++++++ .../src/components/CommandPalette.logic.ts | 51 +++++++++--- apps/web/src/components/CommandPalette.tsx | 11 +++ .../src/components/issue/IssueThreadLinks.tsx | 13 +-- .../pullRequest/PullRequestThreadLinks.tsx | 14 ++-- apps/web/src/i18n/translations/de.json | 5 +- apps/web/src/i18n/translations/en.json | 5 +- apps/web/src/i18n/translations/es.json | 5 +- apps/web/src/i18n/translations/fr.json | 5 +- apps/web/src/i18n/translations/ja.json | 5 +- apps/web/src/i18n/translations/ko.json | 5 +- apps/web/src/i18n/translations/pt-BR.json | 5 +- apps/web/src/i18n/translations/ru.json | 5 +- apps/web/src/i18n/translations/sv.json | 5 +- apps/web/src/i18n/translations/zh.json | 5 +- packages/contracts/src/delivery.ts | 14 ++++ packages/contracts/src/issue.ts | 2 + packages/contracts/src/pullRequest.ts | 2 + 35 files changed, 394 insertions(+), 44 deletions(-) create mode 100644 apps/server/src/delivery/linkedBoardTasks.ts diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx index 2e5354b23f50f..9cd014db5283d 100644 --- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx +++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx @@ -330,12 +330,33 @@ function LinkedThreads(props: { readonly params: IssueParams; readonly host: str hiddenKeys, hidingAnywhere, ); - if (threads.length === 0) return null; + // A board task's conversation is in no list. This app has no board, so its row opens nothing: + // the task view, with the conversation in it, is on the board in the web and desktop apps. + const boardTasks = relations.data?.boardTasks ?? []; + if (threads.length === 0 && boardTasks.length === 0) return null; return ( <View className="gap-2"> <PullRequestSectionHeading> <T>Linked threads</T> </PullRequestSectionHeading> + {boardTasks.map((task) => ( + <View + key={`${task.board}:${task.taskId}`} + className="flex-row items-center gap-2 rounded-2xl bg-grouped-card p-3" + > + <SymbolView name="square.grid.2x2" size={15} tintColorClassName="accent-icon-muted" /> + <View className="min-w-0 flex-1"> + <Text className="text-sm" numberOfLines={2}> + {gt("Board task: {title}", { title: task.title })} + </Text> + <Text className="text-2xs text-foreground-muted" numberOfLines={2}> + {task.ended + ? gt("Task ended. Its conversation is in the board's archive") + : gt("Open it on the board in the web or desktop app")} + </Text> + </View> + </View> + ))} {threads.map((thread) => { const title = thread.title || gt("Untitled thread"); return ( diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 4ff0fc66ebd0d..5bf95933a9d33 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5463,5 +5463,8 @@ "ad208e3e32c85029": "Alle ausblenden", "3328503592789bed": "Zen", "856812e7e1fc445e": "Tool-Aufrufe im Chat", - "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt." + "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt.", + "cdf5dd7d370e594c": "Board-Aufgabe: {title}", + "dae94973cc4ff259": "Aufgabe beendet. Die Unterhaltung liegt im Archiv des Boards", + "afeb354df4c94446": "Öffne sie auf dem Board in der Web- oder Desktop-App" } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index a06071a306274..d59affb600de4 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5465,5 +5465,8 @@ "ad208e3e32c85029": "Hide all", "3328503592789bed": "Zen", "856812e7e1fc445e": "Tool calls in chat", - "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show." + "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show.", + "cdf5dd7d370e594c": "Board task: {title}", + "dae94973cc4ff259": "Task ended. Its conversation is in the board's archive", + "afeb354df4c94446": "Open it on the board in the web or desktop app" } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index c8d7c55fd9f74..f3470416e7b60 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5457,5 +5457,8 @@ "ad208e3e32c85029": "Ocultar todo", "3328503592789bed": "Zen", "856812e7e1fc445e": "Llamadas a herramientas en el chat", - "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran." + "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran.", + "cdf5dd7d370e594c": "Tarea del tablero: {title}", + "dae94973cc4ff259": "Tarea finalizada. Su conversación está en el archivo del tablero", + "afeb354df4c94446": "Ábrela en el tablero desde la app web o de escritorio" } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 10608d4f0f3a9..ed5762c8fe4dc 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5457,5 +5457,8 @@ "ad208e3e32c85029": "Tout masquer", "3328503592789bed": "Zen", "856812e7e1fc445e": "Appels d’outils dans la discussion", - "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours." + "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours.", + "cdf5dd7d370e594c": "Tâche du tableau : {title}", + "dae94973cc4ff259": "Tâche terminée. Sa conversation se trouve dans les archives du tableau", + "afeb354df4c94446": "Ouvrez-la dans le tableau depuis l'application web ou de bureau" } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 104044ec82f75..fd151e9859719 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5438,5 +5438,8 @@ "ad208e3e32c85029": "すべて非表示", "3328503592789bed": "Zen", "856812e7e1fc445e": "チャット内のツール呼び出し", - "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。" + "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。", + "cdf5dd7d370e594c": "ボードのタスク: {title}", + "dae94973cc4ff259": "タスクは終了しました。会話はボードのアーカイブにあります", + "afeb354df4c94446": "Web またはデスクトップアプリのボードで開いてください" } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 3f3ea67c0866f..6966d0383dbbb 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5442,5 +5442,8 @@ "ad208e3e32c85029": "모두 숨기기", "3328503592789bed": "Zen", "856812e7e1fc445e": "채팅의 도구 호출", - "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다." + "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다.", + "cdf5dd7d370e594c": "보드 작업: {title}", + "dae94973cc4ff259": "작업이 종료되었습니다. 대화는 보드의 보관함에 있습니다", + "afeb354df4c94446": "웹 또는 데스크톱 앱의 보드에서 여세요" } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index a9d10383f2e60..2f075fd99f597 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5457,5 +5457,8 @@ "ad208e3e32c85029": "Ocultar todas", "3328503592789bed": "Zen", "856812e7e1fc445e": "Chamadas de ferramentas no chat", - "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem." + "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem.", + "cdf5dd7d370e594c": "Tarefa do quadro: {title}", + "dae94973cc4ff259": "Tarefa encerrada. A conversa está no arquivo do quadro", + "afeb354df4c94446": "Abra-a no quadro pelo app web ou desktop" } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index b7fa18d5f9f0a..90d3f7ab401e0 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5537,5 +5537,8 @@ "ad208e3e32c85029": "Скрывать все", "3328503592789bed": "Дзен", "856812e7e1fc445e": "Вызовы инструментов в чате", - "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда." + "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда.", + "cdf5dd7d370e594c": "Задача доски: {title}", + "dae94973cc4ff259": "Задача завершена. Её обсуждение находится в архиве доски", + "afeb354df4c94446": "Откройте её на доске в веб- или настольном приложении" } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index ddf0ff70712da..29052209f8e49 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5463,5 +5463,8 @@ "ad208e3e32c85029": "Dölj alla", "3328503592789bed": "Zen", "856812e7e1fc445e": "Verktygsanrop i chatten", - "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid." + "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid.", + "cdf5dd7d370e594c": "Tavluppgift: {title}", + "dae94973cc4ff259": "Uppgiften är avslutad. Konversationen finns i tavlans arkiv", + "afeb354df4c94446": "Öppna den på tavlan i webb- eller skrivbordsappen" } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 7782238f3201c..db4252ad32d52 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5448,5 +5448,8 @@ "ad208e3e32c85029": "全部隐藏", "3328503592789bed": "专注模式", "856812e7e1fc445e": "聊天中的工具调用", - "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。" + "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。", + "cdf5dd7d370e594c": "看板任务:{title}", + "dae94973cc4ff259": "任务已结束。其对话位于看板的归档中", + "afeb354df4c94446": "请在网页版或桌面应用的看板中打开" } diff --git a/apps/server/src/delivery/BoardTaskThreads.test.ts b/apps/server/src/delivery/BoardTaskThreads.test.ts index e4c2186813257..fdebe6e928620 100644 --- a/apps/server/src/delivery/BoardTaskThreads.test.ts +++ b/apps/server/src/delivery/BoardTaskThreads.test.ts @@ -164,6 +164,8 @@ function service( title: thread.title, archivedAt: thread.archivedAt, task, + pullRequests: null, + issues: null, }, ]; }), diff --git a/apps/server/src/delivery/boardThreadRows.ts b/apps/server/src/delivery/boardThreadRows.ts index 9b3a18b956752..5c36020d3bec1 100644 --- a/apps/server/src/delivery/boardThreadRows.ts +++ b/apps/server/src/delivery/boardThreadRows.ts @@ -15,6 +15,9 @@ export interface BoardThreadRow { readonly title: string; readonly archivedAt: string | null; readonly task: BoardTask; + /** The thread's pull request and issue links, as stored: JSON arrays, or null for none. */ + readonly pullRequests: string | null; + readonly issues: string | null; } /** @@ -41,9 +44,13 @@ export const listBoardThreadRows = Effect.fn("listBoardThreadRows")(function* (o title: string; archivedAt: string | null; marker: string | null; + pullRequests: string | null; + issues: string | null; }>` SELECT t.thread_id AS id, t.project_id AS "projectId", t.title, t.archived_at AS "archivedAt", + json_extract(t.payload_json, '$.pullRequests') AS "pullRequests", + json_extract(t.payload_json, '$.issues') AS issues, json_extract(t.payload_json, '$.lineage.engineIntake') AS marker FROM orchestration_v2_projection_threads AS t WHERE t.deleted_at IS NULL @@ -61,6 +68,8 @@ export const listBoardThreadRows = Effect.fn("listBoardThreadRows")(function* (o title: row.title, archivedAt: row.archivedAt, task, + pullRequests: row.pullRequests, + issues: row.issues, }, ]; }); diff --git a/apps/server/src/delivery/linkedBoardTasks.ts b/apps/server/src/delivery/linkedBoardTasks.ts new file mode 100644 index 0000000000000..bd92313316120 --- /dev/null +++ b/apps/server/src/delivery/linkedBoardTasks.ts @@ -0,0 +1,80 @@ +import { + ThreadIssueKey, + ThreadPullRequestKey, + threadIssueKeysEqual, + type DeliveryError, + type DeliveryResponse, + type LinkedBoardTask, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import type * as SqlClient from "effect/sql/SqlClient"; + +import { threadPullRequestKeysEqual } from "../sourceControl/threadPullRequests.ts"; +import { listBoardThreadRows, type BoardThreadRow } from "./boardThreadRows.ts"; + +const PullRequestLinks = Schema.fromJsonString( + Schema.Array( + Schema.Struct({ ...ThreadPullRequestKey.fields, source: Schema.optional(Schema.String) }), + ), +); +const IssueLinks = Schema.fromJsonString(Schema.Array(ThreadIssueKey)); +const decodePullRequestLinks = Schema.decodeUnknownOption(PullRequestLinks); +const decodeIssueLinks = Schema.decodeUnknownOption(IssueLinks); +const decodeTitles = Schema.decodeUnknownOption( + Schema.Struct({ + lanes: Schema.Array( + Schema.Struct({ + cards: Schema.Array(Schema.Struct({ id: Schema.String, title: Schema.String })), + }), + ), + }), +); + +const linksPullRequest = (key: ThreadPullRequestKey) => (row: BoardThreadRow) => + Option.getOrElse(decodePullRequestLinks(row.pullRequests), () => []).some( + // A link the stack dismissed is not shown on an ordinary thread either. + (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, key), + ); +const linksIssue = (key: ThreadIssueKey) => (row: BoardThreadRow) => + Option.getOrElse(decodeIssueLinks(row.issues), () => []).some((link) => + threadIssueKeysEqual(link, key), + ); + +/** + * The board task conversations linked to a pull request or an issue, found by their marker and + * named by their task. A task the engine does not list (deleted, moved, or the engine away) keeps + * the title its thread was made with; an archived conversation is told as ended. Never an error. + */ +export const linkedBoardTasks = Effect.fn("linkedBoardTasks")(function* ( + link: { readonly pullRequest: ThreadPullRequestKey } | { readonly issue: ThreadIssueKey }, + readLanes: Effect.Effect<DeliveryResponse, DeliveryError> | null, +): Effect.fn.Return<ReadonlyArray<LinkedBoardTask>, never, SqlClient.SqlClient> { + const linked = + "pullRequest" in link ? linksPullRequest(link.pullRequest) : linksIssue(link.issue); + const list = (archived: boolean) => + listBoardThreadRows({ archived }).pipe( + Effect.orElseSucceed((): ReadonlyArray<BoardThreadRow> => []), + ); + const rows = [...(yield* list(false)), ...(yield* list(true))].filter(linked); + if (rows.length === 0) return []; + const lanes = + readLanes === null + ? Option.none() + : yield* readLanes.pipe( + Effect.map((response) => decodeTitles(response.body)), + Effect.orElseSucceed(() => Option.none()), + ); + const titles = new Map( + Option.isSome(lanes) + ? lanes.value.lanes.flatMap((lane) => lane.cards.map((card) => [card.id, card.title])) + : [], + ); + return rows.map((row) => ({ + board: row.task.board, + taskId: row.task.id, + title: titles.get(row.task.id) ?? row.title, + ended: row.archivedAt !== null, + })); +}); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 4c5d838a1bdc9..fa6410ab8cfe6 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -16,6 +16,8 @@ import { boardTaskThreadMarker, } from "../delivery/boardThreadMarker.ts"; import { listBoardThreadRows } from "../delivery/boardThreadRows.ts"; +import { linkedBoardTasks } from "../delivery/linkedBoardTasks.ts"; +import { listLinkedPullRequestThreads } from "../pullRequest/linkedThreads.ts"; import { assert, it, vi } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { @@ -26,6 +28,7 @@ import { DEFAULT_SERVER_SETTINGS, EnvironmentId, GitCommandError, + IssueTrackerKind, MessageId, RunId, ProjectId, @@ -589,6 +592,48 @@ it.effect("keeps a board task's thread out of both lists, however often it is cr ); assert.deepEqual(yield* rows(false), [{ threadId, task }]); assert.deepEqual(yield* rows(true), []); + // Linked to a pull request and an issue, it shows as its task: by the engine's title when the + // engine answers, by the thread's own when it does not. The list of linked threads leaves it out. + const pullRequest = { host: "github.com", repository: "acme/api", number: 7 }; + const issue = { + tracker: IssueTrackerKind.make("github"), + host: "github.com", + scope: "acme/api", + key: "42", + }; + yield* threads.dispatch({ + type: "thread.pull-request.link", + commandId: CommandId.make("command:board-task-pr"), + threadId, + ...pullRequest, + url: "https://github.com/acme/api/pull/7", + source: "created", + }); + yield* threads.dispatch({ + type: "thread.issue.link", + commandId: CommandId.make("command:board-task-issue"), + threadId, + ...issue, + projectId, + url: "https://github.com/acme/api/issues/42", + displayKey: "#42", + title: "Issue", + source: "manual", + }); + const lanes = Effect.succeed({ + readAt: "2026-11-22T10:00:00.000Z", + body: { lanes: [{ cards: [{ id: "task-7", title: "The engine's title" }] }] }, + }); + const asTask = (title: string, ended = false) => [ + { board: "board-1", taskId: "task-7", title, ended }, + ]; + assert.deepEqual(yield* linkedBoardTasks({ pullRequest }, lanes), asTask("The engine's title")); + assert.deepEqual(yield* linkedBoardTasks({ issue }, null), asTask("Task 7")); + assert.deepEqual( + yield* linkedBoardTasks({ pullRequest: { ...pullRequest, number: 8 } }, lanes), + [], + ); + assert.deepEqual((yield* listLinkedPullRequestThreads(pullRequest)).threads, []); yield* threads.dispatch({ type: "thread.archive", commandId: CommandId.make("command:archive-board-task"), @@ -596,6 +641,8 @@ it.effect("keeps a board task's thread out of both lists, however often it is cr }); assert.deepEqual(yield* rows(false), []); assert.deepEqual(yield* rows(true), [{ threadId, task }]); + // The task ended and its conversation is archived: the row stays, told as ended. + assert.deepEqual(yield* linkedBoardTasks({ pullRequest }, null), asTask("Task 7", true)); }).pipe(Effect.provide(harness.layer)); }); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 73f77416c9613..312b79f9b839a 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -268,6 +268,7 @@ import * as IssueTrackerConnections from "./issue/IssueTrackerConnections.ts"; import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts"; import { listLinkedPullRequestThreads } from "./pullRequest/linkedThreads.ts"; import { listBoardThreadRows } from "./delivery/boardThreadRows.ts"; +import { linkedBoardTasks } from "./delivery/linkedBoardTasks.ts"; import { pullRequestSyncKey } from "./pullRequest/pullRequestSyncKey.ts"; import * as SqlClient from "effect/sql/SqlClient"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; @@ -1996,13 +1997,34 @@ export const layerWsRpc = ( return yield* mutateProjectWithClone(projectService, projectCloneTracker, mutation); }); + // A board task's conversation is in no thread list: where it is linked, it shows as its task. + const boardDelivery = yield* Effect.serviceOption(DeliveryService.DeliveryService); + const withBoardTasks = <A extends object>( + result: A, + link: Parameters<typeof linkedBoardTasks>[0], + ) => + linkedBoardTasks( + link, + Option.isSome(boardDelivery) + ? boardDelivery.value.read({ path: "/api/lanes?view=development&set=all" }) + : null, + ).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + Effect.map((boardTasks) => + boardTasks.length === 0 ? result : { ...result, boardTasks }, + ), + ); + const handlers = CoreServerWsRpcGroup.of({ [WS_METHODS.issuesList]: (input) => issues.list(input), [WS_METHODS.issuesDetail]: (input) => issues.detail(input), [WS_METHODS.issuesComments]: (input) => issues.comments(input), [WS_METHODS.issuesTemplates]: (input) => issues.templates(input), [WS_METHODS.issuesCandidates]: (input) => issues.candidates(input), - [WS_METHODS.issuesLinkedThreads]: (input) => threadIssues.linkedThreads(input), + [WS_METHODS.issuesLinkedThreads]: (input) => + threadIssues + .linkedThreads(input) + .pipe(Effect.flatMap((result) => withBoardTasks(result, { issue: input }))), [WS_METHODS.issuesCreate]: (input) => issues.create(input), [WS_METHODS.issuesComment]: (input) => issues.comment(input), [WS_METHODS.issuesUpdate]: (input) => issues.update(input), @@ -2848,6 +2870,7 @@ export const layerWsRpc = ( ? Effect.succeed({ threads: [] }) : listLinkedPullRequestThreads(key).pipe( Effect.provideService(SqlClient.SqlClient, sql), + Effect.flatMap((result) => withBoardTasks(result, { pullRequest: key })), ), ), ), diff --git a/apps/web/src/commandPaletteBus.ts b/apps/web/src/commandPaletteBus.ts index 2766f6db6b391..c28a5f26d2100 100644 --- a/apps/web/src/commandPaletteBus.ts +++ b/apps/web/src/commandPaletteBus.ts @@ -1,10 +1,16 @@ -import type { EnvironmentId, PullRequestLinkedThreadsResult } from "@t3tools/contracts"; +import type { + EnvironmentId, + LinkedBoardTask, + PullRequestLinkedThreadsResult, +} from "@t3tools/contracts"; import { dispatchCommandPalette, isCommandPaletteMounted } from "./commandPaletteStore"; export interface CommandPaletteLinkedThreads { readonly environmentId: EnvironmentId; readonly threads: PullRequestLinkedThreadsResult["threads"]; + /** Board tasks whose conversation is linked. Each opens its task view, never its thread. */ + readonly boardTasks?: ReadonlyArray<LinkedBoardTask>; } export interface CommandPaletteOpenDetail { diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts index 8ba78e2639fdc..afb68b299a692 100644 --- a/apps/web/src/components/CommandPalette.logic.test.ts +++ b/apps/web/src/components/CommandPalette.logic.test.ts @@ -58,6 +58,43 @@ describe("linked pull request thread navigation", () => { await items[0]?.run(); expect(runThread).toHaveBeenCalledWith({ environmentId, id }); }); + + it("lists a linked board task by its task, and opens the task and never its thread", async () => { + const environmentId = EnvironmentId.make("remote"); + const runThread = vi.fn(async () => {}); + const runBoardTask = vi.fn(async () => {}); + const linkedThreads = { + environmentId, + threads: [], + boardTasks: [ + { board: "work", taskId: "task-7", title: "Ship the thing", ended: false }, + // Deleted or moved for good: still a row, by the title its thread kept. + { board: "work", taskId: "task-8", title: "Gone", ended: true }, + ], + }; + const query = "https://github.com/acme/web/pull/42"; + const [item, ended, ...rest] = buildLinkedThreadActionItems({ + ...linkedThreads, + query, + icon: null, + runThread, + runBoardTask, + }); + expect(rest).toEqual([]); + expect(item?.title).toBe("Board task: Ship the thing"); + expect(item?.threadRef).toBeUndefined(); + await item?.run(); + expect(runBoardTask).toHaveBeenCalledWith({ environmentId, taskId: "task-7" }); + // An ended task opens the board, where its archived conversation is listed. + expect(ended?.title).toBe("Board task: Gone"); + await ended?.run(); + expect(runBoardTask).toHaveBeenLastCalledWith({ environmentId, taskId: null }); + expect(runThread).not.toHaveBeenCalled(); + // A surface that cannot open a task view lists no row that would open the thread instead. + expect( + buildLinkedThreadActionItems({ ...linkedThreads, query, icon: null, runThread }), + ).toEqual([]); + }); }); describe("reduceCommandPaletteUiState", () => { diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index 8fc6f18fa4bd2..2d6415ff22975 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -48,20 +48,49 @@ export function buildLinkedThreadActionItems( query: string; icon: ReactNode; runThread: (thread: Pick<SidebarThreadSummary, "environmentId" | "id">) => Promise<void>; + /** + * Opens a board task's view, or the board for a task that ended (`taskId` null), where its + * archived conversation is listed. Without it, linked board tasks are not listed. + */ + runBoardTask?: (task: { environmentId: EnvironmentId; taskId: string | null }) => Promise<void>; + boardTaskIcon?: ReactNode; }, resolve: MessageResolver = m, ): CommandPaletteActionItem[] { - return input.threads.map((thread) => ({ - kind: "action", - value: `thread:${input.environmentId}:${thread.id}`, - threadRef: { environmentId: input.environmentId, threadId: thread.id }, - title: thread.title || resolve(msg("Untitled thread")), - description: - thread.archivedAt === null ? resolve(msg("Linked thread")) : resolve(msg("Archived thread")), - searchTerms: [input.query, thread.title], - icon: input.icon, - run: () => input.runThread({ environmentId: input.environmentId, id: thread.id }), - })); + const { runBoardTask } = input; + return [ + ...input.threads.map((thread): CommandPaletteActionItem => ({ + kind: "action", + value: `thread:${input.environmentId}:${thread.id}`, + threadRef: { environmentId: input.environmentId, threadId: thread.id }, + title: thread.title || resolve(msg("Untitled thread")), + description: + thread.archivedAt === null + ? resolve(msg("Linked thread")) + : resolve(msg("Archived thread")), + searchTerms: [input.query, thread.title], + icon: input.icon, + run: () => input.runThread({ environmentId: input.environmentId, id: thread.id }), + })), + // A board task's row carries no thread: it opens the task, with its conversation in it. + ...(runBoardTask === undefined + ? [] + : (input.boardTasks ?? []).map((task): CommandPaletteActionItem => ({ + kind: "action", + value: `linked-task:${input.environmentId}:${task.taskId}`, + title: resolve(msg("Board task: {title}", { title: task.title })), + description: task.ended + ? resolve(msg("Task ended. Its conversation is in the board's archive")) + : resolve(msg("Opens the task on the board")), + searchTerms: [input.query, task.title], + icon: input.boardTaskIcon ?? input.icon, + run: () => + runBoardTask({ + environmentId: input.environmentId, + taskId: task.ended ? null : task.taskId, + }), + }))), + ]; } export function browseInputEndPaddingClass(input: { diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index cce4f68e10f9f..6e3fc7c646003 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -73,6 +73,7 @@ import { MessageSquareDashedIcon, LinkIcon, MessageSquareIcon, + SquareKanbanIcon, PaletteIcon, RotateCcwIcon, SettingsIcon, @@ -1966,6 +1967,16 @@ function OpenCommandPaletteDialog(props: { params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)), }); }, + boardTaskIcon: <SquareKanbanIcon className={ITEM_ICON_CLASS} />, + runBoardTask: async (task) => { + await navigate({ + to: "/board", + search: { + environment: task.environmentId, + ...(task.taskId === null ? {} : { task: task.taskId }), + }, + }); + }, }, messages, ) diff --git a/apps/web/src/components/issue/IssueThreadLinks.tsx b/apps/web/src/components/issue/IssueThreadLinks.tsx index e9d54ba19a7bf..caa26330a9948 100644 --- a/apps/web/src/components/issue/IssueThreadLinks.tsx +++ b/apps/web/src/components/issue/IssueThreadLinks.tsx @@ -117,18 +117,21 @@ export function IssueThreadLinks({ hiddenKeys, hidingAnywhere, ); + // A board task's conversation is in no list: it counts, and opens, as the task. + const boardTasks = (relations.data ?? lastRelations)?.boardTasks ?? []; + const linkedCount = linkedThreads.length + boardTasks.length; const linkedThreadsLabel = - linkedThreads.length > 0 + linkedCount > 0 ? gt( "{count, plural, one {Linked from {count} thread} other {Linked from {count} threads}}", - { count: linkedThreads.length }, + { count: linkedCount }, ) : gt("Linked threads"); // A failed read shows "?" and falls back to searching threads for the issue's link. const relationsKnown = (relations.data ?? lastRelations) !== null; return ( <> - {linkedThreads.length > 0 || (!relationsKnown && relations.error !== null) ? ( + {linkedCount > 0 || (!relationsKnown && relations.error !== null) ? ( <Tooltip> <TooltipTrigger render={ @@ -140,13 +143,13 @@ export function IssueThreadLinks({ openCommandPalette({ query: issue.url, ...(relationsKnown - ? { linkedThreads: { environmentId, threads: linkedThreads } } + ? { linkedThreads: { environmentId, threads: linkedThreads, boardTasks } } : {}), }) } > <MessageSquareIcon aria-hidden className="size-3.5" /> - <span aria-hidden>{linkedThreads.length || "?"}</span> + <span aria-hidden>{linkedCount || "?"}</span> </Button> } /> diff --git a/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx b/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx index 66c43846031da..5a1d90c511a54 100644 --- a/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx +++ b/apps/web/src/components/pullRequest/PullRequestThreadLinks.tsx @@ -141,18 +141,22 @@ function EnabledPullRequestThreadLinks({ hiddenKeys, hidingAnywhere, ); + // A board task's conversation is in no list: it counts, and opens, as the task. + const boardTasks = + linking.mode === "multiple" ? ((relations.data ?? lastRelations)?.boardTasks ?? []) : []; + const linkedCount = linkedThreads.length + boardTasks.length; const linkedThreadsLabel = - linkedThreads.length > 0 + linkedCount > 0 ? gt( "{count, plural, one {Linked from {count} thread} other {Linked from {count} threads}}", { - count: linkedThreads.length, + count: linkedCount, }, ) : gt("Linked threads"); return ( <> - {display === "count" && (linkedThreads.length > 0 || relations.error !== null) ? ( + {display === "count" && (linkedCount > 0 || relations.error !== null) ? ( <Tooltip> <TooltipTrigger render={ @@ -165,12 +169,12 @@ function EnabledPullRequestThreadLinks({ query: url, ...((relations.data ?? lastRelations) === null ? {} - : { linkedThreads: { environmentId, threads: linkedThreads } }), + : { linkedThreads: { environmentId, threads: linkedThreads, boardTasks } }), }) } > <MessageSquareIcon aria-hidden className="size-3.5" /> - <span aria-hidden>{linkedThreads.length || "?"}</span> + <span aria-hidden>{linkedCount || "?"}</span> </Button> } /> diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 30024c0ab6878..133f09a4fe583 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12568,5 +12568,8 @@ "27d76249d09eb69f": "Review-Leitfaden bereit", "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", - "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden" + "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", + "cdf5dd7d370e594c": "Board-Aufgabe: {title}", + "dae94973cc4ff259": "Aufgabe beendet. Die Unterhaltung liegt im Archiv des Boards", + "1f8f11ca7798711e": "Öffnet die Aufgabe auf dem Board" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2095bc47dd869..73485c4ce3097 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12577,5 +12577,8 @@ "27d76249d09eb69f": "Review guide ready", "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", - "9e91e9a77b664e4e": "Could not start a review guide" + "9e91e9a77b664e4e": "Could not start a review guide", + "cdf5dd7d370e594c": "Board task: {title}", + "dae94973cc4ff259": "Task ended. Its conversation is in the board's archive", + "1f8f11ca7798711e": "Opens the task on the board" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index d218ae0c8e7a2..24f2c22d8d4db 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12563,5 +12563,8 @@ "27d76249d09eb69f": "Guía de revisión lista", "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", - "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión" + "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", + "cdf5dd7d370e594c": "Tarea del tablero: {title}", + "dae94973cc4ff259": "Tarea finalizada. Su conversación está en el archivo del tablero", + "1f8f11ca7798711e": "Abre la tarea en el tablero" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index f31663a1a3dd4..ad632889105c9 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12568,5 +12568,8 @@ "27d76249d09eb69f": "Guide de revue prêt", "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", - "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue" + "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", + "cdf5dd7d370e594c": "Tâche du tableau : {title}", + "dae94973cc4ff259": "Tâche terminée. Sa conversation se trouve dans les archives du tableau", + "1f8f11ca7798711e": "Ouvre la tâche dans le tableau" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 820a982d50bef..01f34bbbc2b3d 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12517,5 +12517,8 @@ "27d76249d09eb69f": "レビューガイドの準備ができました", "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", - "9e91e9a77b664e4e": "レビューガイドを開始できませんでした" + "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", + "cdf5dd7d370e594c": "ボードのタスク: {title}", + "dae94973cc4ff259": "タスクは終了しました。会話はボードのアーカイブにあります", + "1f8f11ca7798711e": "ボードでタスクを開きます" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index a306c623bdf79..5174660f092d0 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12512,5 +12512,8 @@ "27d76249d09eb69f": "검토 가이드 준비됨", "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", - "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다" + "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", + "cdf5dd7d370e594c": "보드 작업: {title}", + "dae94973cc4ff259": "작업이 종료되었습니다. 대화는 보드의 보관함에 있습니다", + "1f8f11ca7798711e": "보드에서 작업을 엽니다" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 2de1ad07f4c01..fa8decadfa0e1 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12568,5 +12568,8 @@ "27d76249d09eb69f": "Guia de revisão pronto", "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", - "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão" + "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", + "cdf5dd7d370e594c": "Tarefa do quadro: {title}", + "dae94973cc4ff259": "Tarefa encerrada. A conversa está no arquivo do quadro", + "1f8f11ca7798711e": "Abre a tarefa no quadro" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 8f04340a85b4d..f03101d1b1bda 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12568,5 +12568,8 @@ "27d76249d09eb69f": "Гид по ревью готов", "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", - "9e91e9a77b664e4e": "Не удалось запустить гид по ревью" + "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", + "cdf5dd7d370e594c": "Задача доски: {title}", + "dae94973cc4ff259": "Задача завершена. Её обсуждение находится в архиве доски", + "1f8f11ca7798711e": "Открывает задачу на доске" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 800d80600ef89..df3bba9882395 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12575,5 +12575,8 @@ "27d76249d09eb69f": "Granskningsguiden är klar", "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", - "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide" + "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", + "cdf5dd7d370e594c": "Tavluppgift: {title}", + "dae94973cc4ff259": "Uppgiften är avslutad. Konversationen finns i tavlans arkiv", + "1f8f11ca7798711e": "Öppnar uppgiften på tavlan" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index cc520fc7383cf..2f907a52dccb6 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12594,5 +12594,8 @@ "27d76249d09eb69f": "审查导览已就绪", "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", - "9e91e9a77b664e4e": "无法开始生成审查导览" + "9e91e9a77b664e4e": "无法开始生成审查导览", + "cdf5dd7d370e594c": "看板任务:{title}", + "dae94973cc4ff259": "任务已结束。其对话位于看板的归档中", + "1f8f11ca7798711e": "在看板上打开该任务" } diff --git a/packages/contracts/src/delivery.ts b/packages/contracts/src/delivery.ts index 07a5724db3e49..c2ba039c5e6e0 100644 --- a/packages/contracts/src/delivery.ts +++ b/packages/contracts/src/delivery.ts @@ -240,6 +240,20 @@ export const DeliveryArchivedBoardThreads = Schema.Struct({ }); export type DeliveryArchivedBoardThreads = typeof DeliveryArchivedBoardThreads.Type; +/** + * A board task whose conversation is linked to a pull request or an issue. Its thread is in no + * list, so it is shown as the task and opens the task view: the row carries no thread id. + */ +export const LinkedBoardTask = Schema.Struct({ + board: Schema.String, + taskId: Schema.String, + /** The engine's title, or the one the thread was made with when the engine has no such task. */ + title: Schema.String, + /** The task ended (deleted, moved for good, its project removed): its conversation is archived. */ + ended: Schema.Boolean, +}); +export type LinkedBoardTask = typeof LinkedBoardTask.Type; + /** Replaces who joins a conversation from its next message on; null makes it an ordinary one. */ export const DeliverySetThreadLineupInput = Schema.Struct({ threadId: ThreadId, diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 78b0cbb04b852..15cfe38ad6832 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -10,6 +10,7 @@ import { ThreadId, TrimmedNonEmptyString, } from "./baseSchemas.ts"; +import { LinkedBoardTask } from "./delivery.ts"; import { PullRequestActor, PullRequestLabel, @@ -548,6 +549,7 @@ export const IssueLinkedThreadsResult = Schema.Struct({ settled: Schema.Boolean, }), ), + boardTasks: Schema.optionalKey(Schema.Array(LinkedBoardTask)), }); export type IssueLinkedThreadsResult = typeof IssueLinkedThreadsResult.Type; diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 63087b6b253e1..b1584e93dbae1 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -12,6 +12,7 @@ import { ThreadId, TrimmedNonEmptyString, } from "./baseSchemas.ts"; +import { LinkedBoardTask } from "./delivery.ts"; import { SourceControlProviderKind } from "./sourceControl.ts"; export const PullRequestInvolvement = Schema.Literals(["all", "reviewing", "authored"]); @@ -491,6 +492,7 @@ export const PullRequestLinkedThreadsResult = Schema.Struct({ settled: Schema.optionalKey(Schema.Boolean), }), ), + boardTasks: Schema.optionalKey(Schema.Array(LinkedBoardTask)), }); export type PullRequestLinkedThreadsResult = typeof PullRequestLinkedThreadsResult.Type; From 2902be8cbb406356ca8b605c43f096812caa5543 Mon Sep 17 00:00:00 2001 From: Tevin2119 <tmuparadzi@hotmail.com> Date: Sun, 22 Nov 2026 13:57:47 +0000 Subject: [PATCH 08/13] test(server): the real-engine run of board task threads is in the repository BoardTaskThreads.engine.test.ts was named by two comments and lived only in a scratch folder. It is now a test that skips unless T3_BOARD_THREAD_ENGINE_ROOT names an engine checkout, and scripts/board-thread-engine.ts is the engine it starts: the real engine on a temp home, one bound repository and one board, stopped when the test ends. The lead's model is read from the engine's own team file, not written into the test. Also, after the merge of master: the archived-send test made its markers from an unbranded task, which this branch's marker no longer takes. It uses boardTaskOf. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- apps/server/scripts/board-thread-engine.ts | 131 +++++++ .../delivery/BoardTaskThreads.engine.test.ts | 370 ++++++++++++++++++ .../ThreadLaunchService.test.ts | 4 +- knip.jsonc | 2 + 4 files changed, 505 insertions(+), 2 deletions(-) create mode 100644 apps/server/scripts/board-thread-engine.ts create mode 100644 apps/server/src/delivery/BoardTaskThreads.engine.test.ts diff --git a/apps/server/scripts/board-thread-engine.ts b/apps/server/scripts/board-thread-engine.ts new file mode 100644 index 0000000000000..33150b3117fe9 --- /dev/null +++ b/apps/server/scripts/board-thread-engine.ts @@ -0,0 +1,131 @@ +#!/usr/bin/env node +// @effect-diagnostics nodeBuiltinImport:off globalConsole:off globalTimers:off globalJsonInEffect:off - A host-side helper process for one test; plain Node keeps it readable beside the engine's own code. +// Runs a real delivery engine (a checkout of Operation-PaperClip) for +// src/delivery/BoardTaskThreads.engine.test.ts, which starts it. Everything it writes is under a +// temp folder: a home, a git repository bound as "app", and one board, "work". No worker ever +// runs. It prints one JSON line, {engine, control, repo}, then serves until POST /stop. +// +// node scripts/board-thread-engine.ts <engine checkout> +// +// T3_BOARD_THREAD_ENGINE_PHRASE is the approval passphrase the engine is seeded with; the board +// thread write is refused without it. The control port does what the engine's API does not offer +// a test: adding a task in a chosen state, moving one, deleting one, and reading its events. +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeHttp from "node:http"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeURL from "node:url"; + +const engineRoot = NodePath.resolve(process.argv[2] ?? ""); +const phrase = process.env.T3_BOARD_THREAD_ENGINE_PHRASE ?? ""; +if (!NodeFS.existsSync(NodePath.join(engineRoot, "delivery/lib/api.mjs")) || phrase === "") { + console.error( + "usage: T3_BOARD_THREAD_ENGINE_PHRASE=<phrase> board-thread-engine.ts <engine checkout>", + ); + process.exit(2); +} +const load = (file: string) => import(NodeURL.pathToFileURL(NodePath.join(engineRoot, file)).href); +const { createApi } = await load("delivery/lib/api.mjs"); +const { createEngine } = await load("delivery/test/fixtures/engine.mjs"); +const { writeApproval } = await load("delivery/lib/approval.mjs"); +const { placeTask, saveSets } = await load("delivery/lib/sets.mjs"); + +// A git hook's variables would point the scratch repository at the caller's. +const env = Object.fromEntries( + Object.entries(process.env).filter(([name]) => !/^GIT_/i.test(name)), +); +const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-bt-")); +const home = NodePath.join(root, "home"); +const repo = NodePath.join(root, "repo"); +NodeFS.mkdirSync(home); +NodeFS.mkdirSync(repo); +for (const args of [ + ["init", "-b", "main"], + [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "commit", + "--allow-empty", + "-m", + "base", + ], +]) { + NodeChildProcess.execFileSync("git", args, { cwd: repo, stdio: "ignore", env }); +} +NodeFS.writeFileSync( + NodePath.join(home, "repositories.json"), + JSON.stringify({ repositories: { app: { path: repo, title: "App", defaultBase: "main" } } }), +); +saveSets(home, { + sets: { work: { title: "Work", repository: "app", base: "main", tasks: [] } }, + views: {}, +}); +await writeApproval(home, phrase); + +const engine = createEngine({ + home, + repoRoot: repo, + teamsFolder: NodePath.join(engineRoot, "teams"), + options: { freeMemoryMb: () => 8000 }, + runWorker: async () => { + throw new Error("no runs expected"); + }, +}); +const api = createApi(engine); +await api.ready; +await new Promise<void>((resolve) => api.server.listen(0, "127.0.0.1", resolve)); + +const control = NodeHttp.createServer(async (request, response) => { + let text = ""; + for await (const chunk of request) text += chunk; + const body = text ? JSON.parse(text) : {}; + let out: unknown = {}; + try { + if (request.url === "/add") { + const { board = "work", ...rest } = body; + const task = engine.store.addTask({ + title: "Task", + body: "Body", + team: "development", + ...rest, + }); + if (board) placeTask(home, engine.store, task.id, board, { by: "scratch" }); + out = task; + } else if (request.url === "/move") { + out = engine.store.moveTask(body.id, body.state); + } else if (request.url === "/delete") { + // The engine has no delete on its API; these are the rows a task owns. + engine.store.write("delete from task_board_threads where task = ?", body.id); + engine.store.write("delete from orchestration_leases where task = ?", body.id); + engine.store.write("delete from tasks where id = ?", body.id); + } else if (request.url === "/events") { + out = engine.store + .events({ task: body.id }) + .map((event: { kind: string; data: unknown }) => ({ kind: event.kind, data: event.data })); + } else if (request.url === "/stop") { + response.end("{}"); + api.beginShutdown(); + await new Promise((resolve) => api.server.close(resolve)); + await engine.interrupt(); + engine.store.close(); + NodeFS.rmSync(root, { recursive: true, force: true }); + process.exit(0); + } + response.end(JSON.stringify(out ?? {})); + } catch (error) { + response.statusCode = 500; + response.end(JSON.stringify({ error: String(error) })); + } +}); +await new Promise<void>((resolve) => control.listen(0, "127.0.0.1", resolve)); +const port = (server: NodeHttp.Server) => (server.address() as { port: number }).port; +console.log( + JSON.stringify({ + engine: `http://127.0.0.1:${port(api.server)}`, + control: `http://127.0.0.1:${port(control)}`, + repo, + }), +); diff --git a/apps/server/src/delivery/BoardTaskThreads.engine.test.ts b/apps/server/src/delivery/BoardTaskThreads.engine.test.ts new file mode 100644 index 0000000000000..cf3937762876e --- /dev/null +++ b/apps/server/src/delivery/BoardTaskThreads.engine.test.ts @@ -0,0 +1,370 @@ +// @effect-diagnostics nodeBuiltinImport:off globalFetch:off globalFetchInEffect:off globalJsonInEffect:off - Drives a real engine process over HTTP; the raw calls are the evidence. +// BoardTaskThreads against a real delivery engine, not the scratch one of +// boardThreadEngine.testkit.ts. Skipped unless T3_BOARD_THREAD_ENGINE_ROOT names a checkout of +// the engine (Operation-PaperClip) that serves the task-to-thread contract; last validated at +// its commit a658892b: +// +// mkdir /tmp/engine-a658892b +// git -C <Operation-PaperClip> archive a658892b delivery teams | tar -x -C /tmp/engine-a658892b +// cd apps/server && T3_BOARD_THREAD_ENGINE_ROOT=/tmp/engine-a658892b \ +// vp test run src/delivery/BoardTaskThreads.engine.test.ts +// +// The test starts scripts/board-thread-engine.ts, which serves that engine from a temp home with +// one bound repository and one board, and stops it at the end. Real: the engine, its store, its +// HTTP API, the delivery service's request path, and BoardTaskThreads. Stubbed: T3's own thread +// store (commands are kept in memory, with command receipts), the project lookup, the provider +// registry (codex and claudeAgent enabled), and the board thread rows read. No provider runs. +import * as NodeChildProcess from "node:child_process"; +import * as NodeCrypto from "node:crypto"; +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + EnvironmentId, + ProviderInstanceId, + ProjectId, + ThreadId, + type OrchestrationV2ServerCommand, +} from "@t3tools/contracts"; +import { assert, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { HttpClient, HttpClientResponse } from "effect/http"; + +import * as ServerConfig from "../config.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; +import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as BoardTaskThreads from "./BoardTaskThreads.ts"; +import * as BoardThreadRows from "./boardThreadRows.ts"; +import { boardTaskOf, boardTaskOfMarker, boardTaskThreadId } from "./boardThreadMarker.ts"; +import * as DeliveryService from "./DeliveryService.ts"; + +const ENGINE_ROOT = process.env.T3_BOARD_THREAD_ENGINE_ROOT ?? ""; +// Scratch values: the engine is seeded with this passphrase and nothing else knows it. +const PHRASE = NodeCrypto.randomBytes(24).toString("hex"); +const ENVIRONMENT = EnvironmentId.make("8f6f2c1e-0000-4000-8000-this-environment"); +const OTHER = "0d9b2f0e-other-environment"; +const PROJECT = ProjectId.make("project:repo"); +const SUBMITTED = "2026-11-22T05:00:00.000Z"; + +interface Engine { + readonly engine: string; + readonly control: string; + readonly repo: string; +} + +/** The real engine, started for this test and stopped with its temp folder when the scope ends. */ +const startEngine = Effect.acquireRelease( + Effect.promise( + () => + new Promise<Engine & { readonly child: NodeChildProcess.ChildProcess }>((resolve, reject) => { + const child = NodeChildProcess.spawn( + process.execPath, + [ + NodePath.resolve(import.meta.dirname, "../../scripts/board-thread-engine.ts"), + ENGINE_ROOT, + ], + { + env: { ...process.env, T3_BOARD_THREAD_ENGINE_PHRASE: PHRASE }, + stdio: ["ignore", "pipe", "inherit"], + }, + ); + let out = ""; + child.stdout!.on("data", (chunk) => { + out += String(chunk); + const line = out.split("\n").find((entry) => entry.startsWith("{")); + if (line && out.includes("\n")) resolve({ ...(JSON.parse(line) as Engine), child }); + }); + child.once("exit", (code) => reject(new Error(`the engine exited with ${code}`))); + child.once("error", reject); + }), + ), + (engine) => + Effect.promise(async () => { + await fetch(`${engine.control}/stop`, { method: "POST" }).catch(() => undefined); + engine.child.kill(); + }), +); + +/** The model the engine's team configuration gives the development team's lead seat. */ +const leadModel = (): string => { + const team = JSON.parse( + NodeFS.readFileSync(NodePath.join(ENGINE_ROOT, "teams/development/team.json"), "utf8"), + ) as { seats: ReadonlyArray<{ id: string; model: string }> }; + return team.seats.find((seat) => seat.id === "lead")!.model; +}; + +// Set once the engine is up; every helper below reads them when called. +let ENGINE = ""; +let CONTROL = ""; +let REPO = ""; + +const json = (url: string, init?: RequestInit) => + Effect.promise(async () => { + const response = await fetch(url, init); + const text = await response.text(); + return { status: response.status, body: text ? JSON.parse(text) : null } as { + status: number; + body: any; + }; + }); +const control = (path: string, body: unknown) => + json(`${CONTROL}${path}`, { method: "POST", body: JSON.stringify(body) }).pipe( + Effect.map((answer) => answer.body), + ); +const engineGet = (path: string) => json(`${ENGINE}${path}`).pipe(Effect.map((a) => a.body)); +const enginePut = (path: string, body: unknown) => + json(`${ENGINE}${path}`, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), + }); +const add = (over: Record<string, unknown> = {}) => + control("/add", { state: "triage", submitted: SUBMITTED, ...over }).pipe( + Effect.map((task) => task.id as string), + ); +const linkOf = (id: string) => engineGet(`/api/tasks/${id}`).pipe(Effect.map((t) => t.boardThread)); +const setEvents = (id: string) => + control("/events", { id }).pipe( + Effect.map((events: Array<{ kind: string }>) => + events.filter((event) => event.kind === "task.board-thread-set"), + ), + ); +const leaseOf = (id: string) => + engineGet("/api/orchestration").pipe( + Effect.map((snapshot) => snapshot.holders.find((holder: any) => holder.task === id) ?? null), + ); + +function threadStore() { + const threads = new Map< + string, + { + marker: string | undefined; + title: string; + modelSelection: unknown; + archivedAt: string | null; + } + >(); + const receipts = new Set<string>(); + const commands: Array<OrchestrationV2ServerCommand> = []; + const hooks: { afterCreate: ((threadId: string) => Effect.Effect<unknown>) | null } = { + afterCreate: null, + }; + const dispatch = (command: OrchestrationV2ServerCommand) => + Effect.gen(function* () { + commands.push(command); + if (receipts.has(command.commandId)) return { storedEvents: [] }; + receipts.add(command.commandId); + if (command.type === "thread.create") { + threads.set(command.threadId, { + marker: command.engineIntake, + title: command.title, + modelSelection: command.modelSelection, + archivedAt: null, + }); + const after = hooks.afterCreate; + if (after) yield* after(command.threadId); + } + if (command.type === "thread.archive") threads.get(command.threadId)!.archivedAt = "archived"; + return { storedEvents: [] }; + }); + return { threads, commands, hooks, dispatch }; +} + +function service(store: ReturnType<typeof threadStore>, key: string = PHRASE) { + return BoardTaskThreads.make.pipe( + Effect.provideService(HostProcess.Environment, { + [BoardTaskThreads.BOARD_THREAD_KEY_VARIABLE]: key, + }), + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(ENVIRONMENT), + }), + Effect.provideService(ThreadManagementService.ThreadManagementService, { + dispatch: store.dispatch, + } as unknown as ThreadManagementService.ThreadManagementService["Service"]), + Effect.provideService(ProjectionStore.ProjectionStoreV2, { + getThreadRecords: (threadId: string) => + Effect.succeed({ + thread: { + lineage: { engineIntake: store.threads.get(threadId)?.marker }, + archivedAt: store.threads.get(threadId)?.archivedAt ?? null, + }, + }), + } as unknown as ProjectionStore.ProjectionStoreV2["Service"]), + Effect.provideService(ProjectStore.ProjectStoreV2, { + findActiveByWorkspaceRoot: (root: string) => + Effect.succeed(root === REPO ? Option.some({ projectId: PROJECT }) : Option.none()), + } as unknown as ProjectStore.ProjectStoreV2["Service"]), + Effect.provideService(ProviderInstanceRegistry.ProviderInstanceRegistry, { + listInstances: Effect.succeed([ + { instanceId: "codex", driverKind: "codex", enabled: true }, + { instanceId: "claudeAgent", driverKind: "claudeAgent", enabled: true }, + ]), + } as unknown as ProviderInstanceRegistry.ProviderInstanceRegistry["Service"]), + Effect.provideService(BoardThreadRows.BoardThreadRows, { + list: ({ archived }: { readonly archived: boolean }) => + Effect.succeed( + [...store.threads].flatMap(([threadId, thread]) => { + const task = boardTaskOfMarker(thread.marker); + return task === null || (thread.archivedAt !== null) !== archived + ? [] + : [ + { + threadId: ThreadId.make(threadId), + projectId: PROJECT, + title: thread.title, + archivedAt: thread.archivedAt, + task, + pullRequests: null, + issues: null, + }, + ]; + }), + ), + } as unknown as BoardThreadRows.BoardThreadRows["Service"]), + ); +} + +const realHttp = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.promise(async () => { + const body = + request.body._tag === "Uint8Array" + ? new TextDecoder().decode(request.body.body) + : undefined; + const response = await fetch(request.url, { + method: request.method, + ...(body === undefined ? {} : { body, headers: { "content-type": "application/json" } }), + }); + return HttpClientResponse.fromWeb(request, response); + }), + ), +); +const deliveryLayer = (engineUrl: string) => + Layer.fresh(DeliveryService.layer(deriveProviderInstanceConfigMap)).pipe( + Layer.provideMerge(Layer.succeed(HostProcess.Environment, {})), + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "board-threads-real-" })), + Layer.provideMerge(NodeServices.layer), + Layer.provideMerge(ServerSettings.layerTest({ delivery: { enabled: true, engineUrl } })), + Layer.provideMerge(realHttp), + ); +const threadOf = (id: string) => boardTaskThreadId(boardTaskOf("work", id)!); + +const linkLife = Effect.gen(function* () { + const started = yield* add({ title: "Ship the thing" }); + const draft = yield* add({ state: "draft", submitted: null }); + const queued = yield* add({ state: "ready" }); + const done = yield* add({ state: "merged" }); + const store = threadStore(); + const threads = yield* service(store); + assert.deepEqual([...(yield* threads.reconcile())], []); + assert.deepEqual([...store.threads.keys()], [threadOf(started)]); + const create = store.commands.find((command) => command.type === "thread.create"); + assert.deepEqual(create?.type === "thread.create" ? { ...create.modelSelection } : null, { + instanceId: ProviderInstanceId.make("codex"), + model: leadModel(), + }); + const link = yield* linkOf(started); + assert.deepEqual( + { environmentId: link.environmentId, threadId: link.threadId, setBy: link.setBy }, + { environmentId: ENVIRONMENT, threadId: threadOf(started), setBy: ENVIRONMENT }, + ); + assert.equal((threadOf(started) as string).split(":").length, 3); + for (const id of [draft, queued, done]) assert.isNull(yield* linkOf(id)); + const lease = yield* leaseOf(started); + assert.equal(lease.origin, `thread:${ENVIRONMENT}/${threadOf(started)}`); + yield* threads.reconcile(); + const renewed = yield* leaseOf(started); + assert.equal(renewed.claimed, lease.claimed); + assert.isTrue(renewed.heartbeat >= lease.heartbeat); + assert.equal((yield* setEvents(started)).length, 1); + assert.equal(store.commands.filter((command) => command.type === "thread.create").length, 1); + + // Two passes at once and a second server: one thread, one write. + const twice = yield* add(); + const second = yield* service(store); + yield* Effect.all([threads.reconcile(), threads.reconcile(), second.reconcile()], { + concurrency: "unbounded", + }); + assert.equal((yield* setEvents(twice)).length, 1); + assert.equal((yield* linkOf(twice)).threadId, threadOf(twice)); + assert.isNull(store.threads.get(threadOf(twice))!.archivedAt); + + // Conflict: another writer links first, with a thread id carrying : / and %. + const contested = yield* add(); + const theirs = "thread:their/board-task:a:b%3Ac"; + store.hooks.afterCreate = () => + enginePut(`/api/tasks/${contested}/board-thread`, { + environmentId: OTHER, + threadId: theirs, + setBy: OTHER, + key: PHRASE, + }).pipe(Effect.tap((answer) => Effect.sync(() => assert.equal(answer.status, 200)))); + assert.deepEqual([...(yield* threads.reconcile())], []); + store.hooks.afterCreate = null; + const held = yield* linkOf(contested); + assert.deepEqual([held.environmentId, held.threadId, held.setBy], [OTHER, theirs, OTHER]); + assert.isNotNull(store.threads.get(threadOf(contested))!.archivedAt); + assert.equal((yield* setEvents(contested)).length, 1); + assert.isNull(yield* leaseOf(contested)); + yield* threads.reconcile(); + assert.equal((yield* linkOf(contested)).threadId, theirs); + + // Moved between the lanes read and the write: code moved, archived, never retried. + const moving = yield* add(); + store.hooks.afterCreate = () => control("/move", { id: moving, state: "moved" }); + assert.deepEqual([...(yield* threads.reconcile())], [[moving, "moved"]]); + store.hooks.afterCreate = null; + assert.isNotNull(store.threads.get(threadOf(moving))!.archivedAt); + assert.isNull(yield* linkOf(moving)); + yield* control("/move", { id: moving, state: "triage" }); + assert.deepEqual([...(yield* threads.reconcile())], [[moving, "archived-thread"]]); + assert.isNull(yield* linkOf(moving)); + assert.equal((yield* setEvents(moving)).length, 0); + + // Deleted between the lanes read and the write: code not-found, archived. + const vanishing = yield* add(); + store.hooks.afterCreate = () => control("/delete", { id: vanishing }); + assert.deepEqual([...(yield* threads.reconcile())], [[moving, "archived-thread"]]); + store.hooks.afterCreate = null; + assert.isNotNull(store.threads.get(threadOf(vanishing))!.archivedAt); + + // A wrong key is refused by code, and nothing is written or archived. + const locked = yield* add(); + const wrong = yield* service(store, "not the passphrase at all"); + assert.deepEqual( + [...(yield* wrong.reconcile())].toSorted(), + [ + [locked, "refused"], + [moving, "archived-thread"], + ].toSorted(), + ); + assert.isNull(yield* linkOf(locked)); + assert.isNull(store.threads.get(threadOf(locked))!.archivedAt); + assert.deepEqual([...(yield* threads.reconcile())], [[moving, "archived-thread"]]); + assert.equal((yield* linkOf(locked)).threadId, threadOf(locked)); + + // A linked task that is deleted leaves its thread archived. + yield* control("/delete", { id: started }); + yield* threads.reconcile(); + assert.isNotNull(store.threads.get(threadOf(started))!.archivedAt); + assert.isNull(store.threads.get(threadOf(twice))!.archivedAt); +}); + +it.live.skipIf(ENGINE_ROOT === "")("runs the whole link life against the real engine", () => + Effect.gen(function* () { + const engine = yield* startEngine; + ENGINE = engine.engine; + CONTROL = engine.control; + REPO = engine.repo; + yield* linkLife.pipe(Effect.provide(deliveryLayer(engine.engine))); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index fefc280e92c1a..7d015ad7bdf8c 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -686,10 +686,10 @@ it.effect("an archived thread receives no message, a board task's or any other", "messages", ]) .pipe(Effect.map((records) => [records.runs.length, records.messages.length])); - const marker = boardTaskThreadMarker({ board: "board-1", id: "task-9" }); + const marker = boardTaskThreadMarker(boardTaskOf("board-1", "task-9")!); yield* create("archived-board", marker); yield* create("archived-ordinary"); - yield* create("live-board", boardTaskThreadMarker({ board: "board-1", id: "task-10" })); + yield* create("live-board", boardTaskThreadMarker(boardTaskOf("board-1", "task-10")!)); for (const name of ["archived-board", "archived-ordinary"]) { yield* threads.dispatch({ type: "thread.archive", diff --git a/knip.jsonc b/knip.jsonc index 4f9b949465c50..5ee8c4730ac5b 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -57,6 +57,8 @@ "entry": [ "src/bin.ts!", "src/claude-history-worker.ts!", + // Started by src/delivery/BoardTaskThreads.engine.test.ts as its own process. + "scripts/board-thread-engine.ts", "scripts/cli.ts", "scripts/fetch-expo-schema.ts", "scripts/probe-claude-fork-local-rollback-replay.ts", From 86649550213e9a0a4af988fd1849d500e889f3a1 Mon Sep 17 00:00:00 2001 From: Tevin2119 <tmuparadzi@hotmail.com> Date: Sun, 22 Nov 2026 13:59:45 +0000 Subject: [PATCH 09/13] fix: removing a project says its archived board conversations are kept The shell counts only a project's active board conversations, so a project whose board conversations were all archived got no line about them and was told only that any archived threads are deleted. Those are kept. The confirmation now asks each environment for its archived board conversations (the read the board's archive list uses, once, with a two second deadline) and says how many are kept when none is active. With an active one the existing line already says so. An environment that does not answer, or has no such read, counts as none and the confirmation is what it was. The new string is in every web and mobile catalog, machine-translated. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../SettingsProjectOverviewRouteScreen.tsx | 25 +++++- apps/mobile/src/i18n/translations/de.json | 3 +- apps/mobile/src/i18n/translations/en.json | 3 +- apps/mobile/src/i18n/translations/es.json | 3 +- apps/mobile/src/i18n/translations/fr.json | 3 +- apps/mobile/src/i18n/translations/ja.json | 3 +- apps/mobile/src/i18n/translations/ko.json | 3 +- apps/mobile/src/i18n/translations/pt-BR.json | 3 +- apps/mobile/src/i18n/translations/ru.json | 3 +- apps/mobile/src/i18n/translations/sv.json | 3 +- apps/mobile/src/i18n/translations/zh.json | 3 +- .../ProjectSettingsPanel.logic.test.ts | 84 ++++++++++++++++++- .../settings/ProjectSettingsPanel.tsx | 19 ++++- apps/web/src/i18n/translations/de.json | 3 +- apps/web/src/i18n/translations/en.json | 3 +- apps/web/src/i18n/translations/es.json | 3 +- apps/web/src/i18n/translations/fr.json | 3 +- apps/web/src/i18n/translations/ja.json | 3 +- apps/web/src/i18n/translations/ko.json | 3 +- apps/web/src/i18n/translations/pt-BR.json | 3 +- apps/web/src/i18n/translations/ru.json | 3 +- apps/web/src/i18n/translations/sv.json | 3 +- apps/web/src/i18n/translations/zh.json | 3 +- packages/client-runtime/src/state/delivery.ts | 5 ++ .../src/state/projectRemoval.ts | 58 ++++++++++++- 25 files changed, 224 insertions(+), 27 deletions(-) diff --git a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx index 71d814b302b16..275ffbc116046 100644 --- a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx @@ -6,7 +6,10 @@ import { Button } from "../../components/ui/Button"; import { ProjectFavicon } from "../../components/ProjectFavicon"; import * as Dialog from "../../components/ui/Dialog"; import { AuthOrchestrationOperateScope } from "@t3tools/contracts"; -import { planProjectRemoval } from "@t3tools/client-runtime/state/projects"; +import { + archivedServerOwnedThreadCount, + planProjectRemoval, +} from "@t3tools/client-runtime/state/projects"; import { isAtomCommandInterrupted, squashAtomCommandFailure, @@ -22,6 +25,7 @@ import { Platform, Pressable, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { projectEnvironment } from "../../state/projects"; +import { deliveryEnvironment } from "../../state/delivery"; import { useThreadShells } from "../../state/entities"; import { appAtomRegistry } from "../../state/atom-registry"; import { @@ -160,6 +164,9 @@ function ProjectOverviewContent(props: { removableEnvironments.has(member.environmentId), ); const deleteProject = useAtomCommand(projectEnvironment.delete, { reportFailure: false }); + const fetchArchivedBoardThreads = useAtomCommand(deliveryEnvironment.fetchArchivedBoardThreads, { + reportFailure: false, + }); const updateProject = useAtomCommand(projectEnvironment.update, { label: "project name update", reportFailure: true, @@ -237,9 +244,18 @@ function ProjectOverviewContent(props: { return false; }; - const removeMembers = (members: readonly EnvironmentProject[]) => { + const removeMembers = async (members: readonly EnvironmentProject[]) => { if (!checkRemovalAccess(members) || !startRemoval()) return; const projectKey = props.projectKey; + // The shell counts only the active board conversations; the archived ones are kept. This + // settles on its own deadline and never rejects, so the removal guard is always released. + const archivedKept = await archivedServerOwnedThreadCount({ + members, + read: async (environmentId) => { + const result = await fetchArchivedBoardThreads({ environmentId, input: {} }); + return result._tag === "Success" ? result.value.threads : null; + }, + }); const plan = planProjectRemoval( { members: members.map((member) => ({ @@ -254,6 +270,7 @@ function ProjectOverviewContent(props: { threads, unloadedThreadCount: readUnloadedThreadCount(members, threads), serverOwnedThreadCount: readServerOwnedThreadCount(members, threads), + archivedServerOwnedThreadCount: archivedKept, }, m, ); @@ -434,7 +451,7 @@ function ProjectOverviewContent(props: { <RemoveCheckoutAction member={member} disabled={isRemoving} - onPress={() => removeMembers([member])} + onPress={() => void removeMembers([member])} /> ) : null} </View> @@ -486,7 +503,7 @@ function ProjectOverviewContent(props: { tone="danger" disabled={!canRemoveGroup || isRemoving} loading={isRemoving} - onPress={() => removeMembers(props.members)} + onPress={() => void removeMembers(props.members)} /> </SettingsSection> </> diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index df792dec8fe0f..db34830fff7cd 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5466,5 +5466,6 @@ "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt.", "cdf5dd7d370e594c": "Board-Aufgabe: {title}", "dae94973cc4ff259": "Aufgabe beendet. Die Unterhaltung liegt im Archiv des Boards", - "afeb354df4c94446": "Öffne sie auf dem Board in der Web- oder Desktop-App" + "afeb354df4c94446": "Öffne sie auf dem Board in der Web- oder Desktop-App", + "a65acdb87eac322b": "{count, plural, one {{count} archiviertes, von einem Board gestartetes Gespräch bleibt erhalten und wird nicht gelöscht.} other {{count} archivierte, von einem Board gestartete Gespräche bleiben erhalten und werden nicht gelöscht.}}" } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index bc56e80a804f3..04ba1477f4016 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5468,5 +5468,6 @@ "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show.", "cdf5dd7d370e594c": "Board task: {title}", "dae94973cc4ff259": "Task ended. Its conversation is in the board's archive", - "afeb354df4c94446": "Open it on the board in the web or desktop app" + "afeb354df4c94446": "Open it on the board in the web or desktop app", + "a65acdb87eac322b": "{count, plural, one {{count} archived conversation started by a board is kept, not deleted.} other {{count} archived conversations started by a board are kept, not deleted.}}" } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index a3495ad249d50..2e3e2af7aa351 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5460,5 +5460,6 @@ "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran.", "cdf5dd7d370e594c": "Tarea del tablero: {title}", "dae94973cc4ff259": "Tarea finalizada. Su conversación está en el archivo del tablero", - "afeb354df4c94446": "Ábrela en el tablero desde la app web o de escritorio" + "afeb354df4c94446": "Ábrela en el tablero desde la app web o de escritorio", + "a65acdb87eac322b": "{count, plural, one {{count} conversación archivada iniciada por un tablero se conserva, no se elimina.} other {{count} conversaciones archivadas iniciadas por un tablero se conservan, no se eliminan.}}" } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index a6cf8a8684f2e..3c32856a6cdc9 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5460,5 +5460,6 @@ "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours.", "cdf5dd7d370e594c": "Tâche du tableau : {title}", "dae94973cc4ff259": "Tâche terminée. Sa conversation se trouve dans les archives du tableau", - "afeb354df4c94446": "Ouvrez-la dans le tableau depuis l'application web ou de bureau" + "afeb354df4c94446": "Ouvrez-la dans le tableau depuis l'application web ou de bureau", + "a65acdb87eac322b": "{count, plural, one {{count} conversation archivée lancée par un tableau est conservée, pas supprimée.} other {{count} conversations archivées lancées par un tableau sont conservées, pas supprimées.}}" } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 3187c067b0dc9..aa3af10b65dfc 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5441,5 +5441,6 @@ "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。", "cdf5dd7d370e594c": "ボードのタスク: {title}", "dae94973cc4ff259": "タスクは終了しました。会話はボードのアーカイブにあります", - "afeb354df4c94446": "Web またはデスクトップアプリのボードで開いてください" + "afeb354df4c94446": "Web またはデスクトップアプリのボードで開いてください", + "a65acdb87eac322b": "{count, plural, other {ボードが開始したアーカイブ済みの会話 {count} 件は保持され、削除されません。}}" } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 57e07ebf1ab98..ffdf2e31dedcf 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5445,5 +5445,6 @@ "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다.", "cdf5dd7d370e594c": "보드 작업: {title}", "dae94973cc4ff259": "작업이 종료되었습니다. 대화는 보드의 보관함에 있습니다", - "afeb354df4c94446": "웹 또는 데스크톱 앱의 보드에서 여세요" + "afeb354df4c94446": "웹 또는 데스크톱 앱의 보드에서 여세요", + "a65acdb87eac322b": "{count, plural, other {보드가 시작한 보관된 대화 {count}개는 삭제되지 않고 유지됩니다.}}" } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 8e0d7f2984138..497666749800d 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5460,5 +5460,6 @@ "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem.", "cdf5dd7d370e594c": "Tarefa do quadro: {title}", "dae94973cc4ff259": "Tarefa encerrada. A conversa está no arquivo do quadro", - "afeb354df4c94446": "Abra-a no quadro pelo app web ou desktop" + "afeb354df4c94446": "Abra-a no quadro pelo app web ou desktop", + "a65acdb87eac322b": "{count, plural, one {{count} conversa arquivada iniciada por um quadro é mantida, não excluída.} other {{count} conversas arquivadas iniciadas por um quadro são mantidas, não excluídas.}}" } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index e38f31b9874a5..24fb4ac8d2b19 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5540,5 +5540,6 @@ "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда.", "cdf5dd7d370e594c": "Задача доски: {title}", "dae94973cc4ff259": "Задача завершена. Её обсуждение находится в архиве доски", - "afeb354df4c94446": "Откройте её на доске в веб- или настольном приложении" + "afeb354df4c94446": "Откройте её на доске в веб- или настольном приложении", + "a65acdb87eac322b": "{count, plural, one {{count} архивированный разговор, начатый доской, сохранится и не будет удалён.} few {{count} архивированных разговора, начатых доской, сохранятся и не будут удалены.} many {{count} архивированных разговоров, начатых доской, сохранятся и не будут удалены.} other {{count} архивированного разговора, начатых доской, сохранятся и не будут удалены.}}" } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index a5279b54539fd..b80843748c3ba 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5466,5 +5466,6 @@ "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid.", "cdf5dd7d370e594c": "Tavluppgift: {title}", "dae94973cc4ff259": "Uppgiften är avslutad. Konversationen finns i tavlans arkiv", - "afeb354df4c94446": "Öppna den på tavlan i webb- eller skrivbordsappen" + "afeb354df4c94446": "Öppna den på tavlan i webb- eller skrivbordsappen", + "a65acdb87eac322b": "{count, plural, one {{count} arkiverad konversation som startats av en tavla behålls, den tas inte bort.} other {{count} arkiverade konversationer som startats av en tavla behålls, de tas inte bort.}}" } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 80492fe40c22f..4b9be3ca97195 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5451,5 +5451,6 @@ "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。", "cdf5dd7d370e594c": "看板任务:{title}", "dae94973cc4ff259": "任务已结束。其对话位于看板的归档中", - "afeb354df4c94446": "请在网页版或桌面应用的看板中打开" + "afeb354df4c94446": "请在网页版或桌面应用的看板中打开", + "a65acdb87eac322b": "{count, plural, other {由看板发起的 {count} 个已归档对话会保留,不会删除。}}" } diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts b/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts index 9342e8458c476..da384abe8d19f 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts +++ b/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vite-plus/test"; import { EnvironmentId, ProjectId, SourceControlProviderKind, ThreadId } from "@t3tools/contracts"; -import { planProjectRemoval, serverOwnedThreadCount } from "@t3tools/client-runtime/state/projects"; +import { + archivedServerOwnedThreadCount, + planProjectRemoval, + serverOwnedThreadCount, +} from "@t3tools/client-runtime/state/projects"; import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping"; import type { Project } from "../../types"; @@ -185,6 +189,84 @@ describe("project removal confirmation", () => { ).toContain("1 conversation started by a board or the engine is archived, not deleted."); }); + it("says a project's already archived board conversations are kept when none is active", async () => { + const other = ProjectId.make("other-project"); + const rows = [{ projectId: local.id }, { projectId: local.id }, { projectId: other }]; + // Each environment is asked once, and only the members' projects are counted. + const asked: EnvironmentId[] = []; + const read = async (environmentId: EnvironmentId) => { + asked.push(environmentId); + return environmentId === local.environmentId ? rows : [{ projectId: local.id }]; + }; + expect(await archivedServerOwnedThreadCount({ members: [local], read })).toBe(2); + expect(await archivedServerOwnedThreadCount({ members: [local, remote], read })).toBe(3); + expect(asked).toEqual([local.environmentId, local.environmentId, remote.environmentId]); + // A server without the list, a failed read and a read that never answers all count as none. + expect(await archivedServerOwnedThreadCount({ members: [local], read: async () => null })).toBe( + 0, + ); + expect( + await archivedServerOwnedThreadCount({ + members: [local], + read: () => Promise.reject(new Error("offline")), + }), + ).toBe(0); + expect( + await archivedServerOwnedThreadCount({ + members: [local], + read: () => new Promise(() => {}), + timeoutMs: 5, + }), + ).toBe(0); + + // Every board conversation of the project is archived: the shell counts none. + const plan = planProjectRemoval({ + members: [local], + groupMemberCount: 1, + hasOtherMembers: false, + displayName: "Repo", + threads: [], + serverOwnedThreadCount: 0, + archivedServerOwnedThreadCount: 2, + }); + expect(plan.confirmationMessage).toBe( + 'Remove project "Repo"?\nPath: /work/repo\nEnvironment: Local\nAny archived threads are deleted from T3 Code. Provider sessions are kept.\n2 archived conversations started by a board are kept, not deleted.\nThis removes only the project entries, not the files on disk.\nThis action cannot be undone.', + ); + expect( + planProjectRemoval({ + members: [local], + groupMemberCount: 1, + hasOtherMembers: false, + displayName: "Repo", + threads: [], + archivedServerOwnedThreadCount: 1, + }).confirmationMessage, + ).toContain("1 archived conversation started by a board is kept, not deleted."); + // With an active one the archive line already says the archived are kept: one line, not two. + const both = planProjectRemoval({ + members: [local], + groupMemberCount: 1, + hasOtherMembers: false, + displayName: "Repo", + threads: [], + serverOwnedThreadCount: 1, + archivedServerOwnedThreadCount: 2, + }).confirmationMessage; + expect(both).toContain("Board and engine conversations already archived are kept."); + expect(both).not.toContain("archived conversations started by a board are kept"); + // No board conversation at all: the dialog is what it was. + expect( + planProjectRemoval({ + members: [local], + groupMemberCount: 1, + hasOtherMembers: false, + displayName: "Repo", + threads: [], + archivedServerOwnedThreadCount: 0, + }).confirmationMessage, + ).not.toContain("started by a board"); + }); + it("keeps an environment-filtered group scoped to its selected checkout", () => { const plan = planProjectRemoval({ members: [remote], diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx index c72347248acc3..e9d8f6725f904 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx @@ -6,7 +6,10 @@ import { AuthOrchestrationOperateScope } from "@t3tools/contracts"; import { useEnvironmentsWithScope } from "../../state/session"; import { mapAtomCommandResult, settlePromise } from "@t3tools/client-runtime/state/runtime"; import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { planProjectRemoval } from "@t3tools/client-runtime/state/projects"; +import { + archivedServerOwnedThreadCount, + planProjectRemoval, +} from "@t3tools/client-runtime/state/projects"; import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts"; import { checkProjectAccess, @@ -34,6 +37,8 @@ import { useEnvironments, usePrimaryEnvironmentId } from "../../state/environmen import { useThreadShells, waitForProjectRemoval } from "../../state/entities"; import { refreshProjectFaviconUrl } from "../../state/assets"; import { projectEnvironment } from "../../state/projects"; +import { deliveryEnvironment } from "../../state/delivery"; +import { useAtomCommand } from "../../state/use-atom-command"; import { ProjectFavicon } from "../ProjectFavicon"; import { Alert, AlertDescription } from "../ui/alert"; import { Button } from "../ui/button"; @@ -288,6 +293,9 @@ function ProjectDetail({ const deleteProject = useOrchestrationCommand(projectEnvironment.delete, { reportFailure: false, }); + const fetchArchivedBoardThreads = useAtomCommand(deliveryEnvironment.fetchArchivedBoardThreads, { + reportFailure: false, + }); const projectNameEditedRef = useRef(false); const faviconPath = group.faviconPath ?? null; @@ -359,6 +367,14 @@ function ProjectDetail({ const api = readLocalApi(); if (!api) return; + // The shell counts only the active board conversations; the archived ones are kept. + const archivedKept = await archivedServerOwnedThreadCount({ + members, + read: async (environmentId) => { + const result = await fetchArchivedBoardThreads({ environmentId, input: {} }); + return result._tag === "Success" ? result.value.threads : null; + }, + }); const { projectThreads, isWholeGroup, confirmationMessage } = planProjectRemoval( { members, @@ -368,6 +384,7 @@ function ProjectDetail({ threads, unloadedThreadCount: readUnloadedThreadCount(members, threads), serverOwnedThreadCount: readServerOwnedThreadCount(members, threads), + archivedServerOwnedThreadCount: archivedKept, }, resolveMessage, ); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index bcbb008bb7329..edf4b2429baa2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12572,5 +12572,6 @@ "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", "cdf5dd7d370e594c": "Board-Aufgabe: {title}", "dae94973cc4ff259": "Aufgabe beendet. Die Unterhaltung liegt im Archiv des Boards", - "1f8f11ca7798711e": "Öffnet die Aufgabe auf dem Board" + "1f8f11ca7798711e": "Öffnet die Aufgabe auf dem Board", + "a65acdb87eac322b": "{count, plural, one {{count} archiviertes, von einem Board gestartetes Gespräch bleibt erhalten und wird nicht gelöscht.} other {{count} archivierte, von einem Board gestartete Gespräche bleiben erhalten und werden nicht gelöscht.}}" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index eb77883a8b900..036a20f29b85d 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12581,5 +12581,6 @@ "9e91e9a77b664e4e": "Could not start a review guide", "cdf5dd7d370e594c": "Board task: {title}", "dae94973cc4ff259": "Task ended. Its conversation is in the board's archive", - "1f8f11ca7798711e": "Opens the task on the board" + "1f8f11ca7798711e": "Opens the task on the board", + "a65acdb87eac322b": "{count, plural, one {{count} archived conversation started by a board is kept, not deleted.} other {{count} archived conversations started by a board are kept, not deleted.}}" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 5c67eaeb1f54c..9c085522977c0 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12567,5 +12567,6 @@ "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", "cdf5dd7d370e594c": "Tarea del tablero: {title}", "dae94973cc4ff259": "Tarea finalizada. Su conversación está en el archivo del tablero", - "1f8f11ca7798711e": "Abre la tarea en el tablero" + "1f8f11ca7798711e": "Abre la tarea en el tablero", + "a65acdb87eac322b": "{count, plural, one {{count} conversación archivada iniciada por un tablero se conserva, no se elimina.} other {{count} conversaciones archivadas iniciadas por un tablero se conservan, no se eliminan.}}" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 9969ff1ae216b..6e81a78e7b966 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12572,5 +12572,6 @@ "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", "cdf5dd7d370e594c": "Tâche du tableau : {title}", "dae94973cc4ff259": "Tâche terminée. Sa conversation se trouve dans les archives du tableau", - "1f8f11ca7798711e": "Ouvre la tâche dans le tableau" + "1f8f11ca7798711e": "Ouvre la tâche dans le tableau", + "a65acdb87eac322b": "{count, plural, one {{count} conversation archivée lancée par un tableau est conservée, pas supprimée.} other {{count} conversations archivées lancées par un tableau sont conservées, pas supprimées.}}" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 8b4e4348f0065..a2b5eb2d9d1c4 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12521,5 +12521,6 @@ "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", "cdf5dd7d370e594c": "ボードのタスク: {title}", "dae94973cc4ff259": "タスクは終了しました。会話はボードのアーカイブにあります", - "1f8f11ca7798711e": "ボードでタスクを開きます" + "1f8f11ca7798711e": "ボードでタスクを開きます", + "a65acdb87eac322b": "{count, plural, other {ボードが開始したアーカイブ済みの会話 {count} 件は保持され、削除されません。}}" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index f428dcd7d8e3a..440600c7b8b77 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12516,5 +12516,6 @@ "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", "cdf5dd7d370e594c": "보드 작업: {title}", "dae94973cc4ff259": "작업이 종료되었습니다. 대화는 보드의 보관함에 있습니다", - "1f8f11ca7798711e": "보드에서 작업을 엽니다" + "1f8f11ca7798711e": "보드에서 작업을 엽니다", + "a65acdb87eac322b": "{count, plural, other {보드가 시작한 보관된 대화 {count}개는 삭제되지 않고 유지됩니다.}}" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 9abcd5972d202..28c644480f68a 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12572,5 +12572,6 @@ "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", "cdf5dd7d370e594c": "Tarefa do quadro: {title}", "dae94973cc4ff259": "Tarefa encerrada. A conversa está no arquivo do quadro", - "1f8f11ca7798711e": "Abre a tarefa no quadro" + "1f8f11ca7798711e": "Abre a tarefa no quadro", + "a65acdb87eac322b": "{count, plural, one {{count} conversa arquivada iniciada por um quadro é mantida, não excluída.} other {{count} conversas arquivadas iniciadas por um quadro são mantidas, não excluídas.}}" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index dd80fb1ba9955..8a441652f5dd5 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12572,5 +12572,6 @@ "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", "cdf5dd7d370e594c": "Задача доски: {title}", "dae94973cc4ff259": "Задача завершена. Её обсуждение находится в архиве доски", - "1f8f11ca7798711e": "Открывает задачу на доске" + "1f8f11ca7798711e": "Открывает задачу на доске", + "a65acdb87eac322b": "{count, plural, one {{count} архивированный разговор, начатый доской, сохранится и не будет удалён.} few {{count} архивированных разговора, начатых доской, сохранятся и не будут удалены.} many {{count} архивированных разговоров, начатых доской, сохранятся и не будут удалены.} other {{count} архивированного разговора, начатых доской, сохранятся и не будут удалены.}}" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index b6c87f834b230..a17857f305b1b 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12579,5 +12579,6 @@ "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", "cdf5dd7d370e594c": "Tavluppgift: {title}", "dae94973cc4ff259": "Uppgiften är avslutad. Konversationen finns i tavlans arkiv", - "1f8f11ca7798711e": "Öppnar uppgiften på tavlan" + "1f8f11ca7798711e": "Öppnar uppgiften på tavlan", + "a65acdb87eac322b": "{count, plural, one {{count} arkiverad konversation som startats av en tavla behålls, den tas inte bort.} other {{count} arkiverade konversationer som startats av en tavla behålls, de tas inte bort.}}" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 8191b5c3c050c..cc2731649de17 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12598,5 +12598,6 @@ "9e91e9a77b664e4e": "无法开始生成审查导览", "cdf5dd7d370e594c": "看板任务:{title}", "dae94973cc4ff259": "任务已结束。其对话位于看板的归档中", - "1f8f11ca7798711e": "在看板上打开该任务" + "1f8f11ca7798711e": "在看板上打开该任务", + "a65acdb87eac322b": "{count, plural, other {由看板发起的 {count} 个已归档对话会保留,不会删除。}}" } diff --git a/packages/client-runtime/src/state/delivery.ts b/packages/client-runtime/src/state/delivery.ts index 87577dd3b3d59..d26ca83a8d833 100644 --- a/packages/client-runtime/src/state/delivery.ts +++ b/packages/client-runtime/src/state/delivery.ts @@ -29,6 +29,11 @@ export function createDeliveryEnvironmentAtoms<R, E>( tag: WS_METHODS.deliveryArchivedBoardThreads, staleTimeMs: 2_000, }), + /** The same list read once by hand, for a project removal to count what it keeps. */ + fetchArchivedBoardThreads: createEnvironmentRpcCommand(runtime, { + label: "environment-data:delivery:fetch-archived-board-threads", + tag: WS_METHODS.deliveryArchivedBoardThreads, + }), /** A thread's team, or the team choice that is still held. Cheap, and read often. */ threadBinding, /** Query families include the environment and thread; previous query values never carry over. */ diff --git a/packages/client-runtime/src/state/projectRemoval.ts b/packages/client-runtime/src/state/projectRemoval.ts index d8e0b473ea341..8e5daaa2c102d 100644 --- a/packages/client-runtime/src/state/projectRemoval.ts +++ b/packages/client-runtime/src/state/projectRemoval.ts @@ -9,6 +9,8 @@ import { import type { EnvironmentProject, EnvironmentThreadShell } from "./models.ts"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; /** * The threads of these projects that the server started for itself, such as a board task's @@ -44,6 +46,46 @@ export function serverOwnedThreadCount(input: { return total; } +/** An archived board task conversation, as `delivery.archivedBoardThreads` lists it. */ +type ArchivedServerOwnedThread = { readonly projectId: ProjectId }; + +/** + * The archived board task conversations of these projects. The shell's count covers only the + * active ones, and a removal keeps the archived ones, so each environment is asked for its list. + * An environment that does not answer in time, or has no such list, counts as none: the + * confirmation must not wait on it. + */ +export async function archivedServerOwnedThreadCount(input: { + readonly members: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly id: ProjectId; + }>; + readonly read: ( + environmentId: EnvironmentId, + ) => Promise<ReadonlyArray<ArchivedServerOwnedThread> | null>; + readonly timeoutMs?: number; +}): Promise<number> { + const environmentIds = [...new Set(input.members.map((member) => member.environmentId))]; + const counts = await Promise.all( + environmentIds.map(async (environmentId) => { + const rows = await Effect.runPromise( + Effect.tryPromise({ try: () => input.read(environmentId), catch: () => null }).pipe( + Effect.timeoutOption(input.timeoutMs ?? 2_000), + Effect.map(Option.getOrNull), + Effect.orElseSucceed(() => null), + ), + ); + const projectIds = new Set( + input.members + .filter((member) => member.environmentId === environmentId) + .map((member) => member.id), + ); + return (rows ?? []).filter((row) => projectIds.has(row.projectId)).length; + }), + ); + return counts.reduce((total, count) => total + count, 0); +} + export function planProjectRemoval< Thread extends Pick<EnvironmentThreadShell, "environmentId" | "projectId" | "lineage">, >( @@ -61,6 +103,8 @@ export function planProjectRemoval< readonly unloadedThreadCount?: number; /** The members' server-owned threads, which are archived, not deleted: `serverOwnedThreadCount`. */ readonly serverOwnedThreadCount?: number; + /** The members' board task conversations already archived, which are kept: `archivedServerOwnedThreadCount`. */ + readonly archivedServerOwnedThreadCount?: number; }, resolve: MFunctionType = mFallback, ) { @@ -74,6 +118,7 @@ export function planProjectRemoval< projectThreads.filter((thread) => isListedThreadLineage(thread.lineage)).length + (options.unloadedThreadCount ?? 0); const keptCount = options.serverOwnedThreadCount ?? 0; + const archivedKeptCount = options.archivedServerOwnedThreadCount ?? 0; const isWholeGroup = members.length === groupMemberCount; const targetKind = hasOtherMembers || !isWholeGroup ? "checkout" : "project"; const singleMember = members.length === 1 ? members[0]! : null; @@ -134,7 +179,18 @@ export function planProjectRemoval< ), ), ] - : []), + : // With none active that sentence is absent, and "any archived threads are deleted" would + // be false for these. + archivedKeptCount > 0 + ? [ + resolve( + msg( + "{count, plural, one {{count} archived conversation started by a board is kept, not deleted.} other {{count} archived conversations started by a board are kept, not deleted.}}", + { count: archivedKeptCount }, + ), + ), + ] + : []), isWholeGroup && !hasOtherMembers ? resolve(msg("This removes only the project entries, not the files on disk.")) : resolve(msg("Other entries in this grouped project are unaffected.")), From 0b69b151bec957828983ba05724cba7dcbc8d644 Mon Sep 17 00:00:00 2001 From: Tevin2119 <tmuparadzi@hotmail.com> Date: Sun, 22 Nov 2026 15:10:55 +0000 Subject: [PATCH 10/13] fix(server): a restored board thread that holds no task is archived again A board task's thread restored from the board's archive stayed open for good when its task was deleted or held by another conversation: the archive command id was the same on every attempt, so the first archive's receipt answered the retry and nothing happened. The thread was then in no list and not in the archive. The archive command id now ends with the thread's revision (the version of its event stream), which every event raises. A pass repeated over the same state is still answered by the first archive; a thread restored since is archived anew. A restored thread whose task moved to another machine is archived again too. Tests: the deleted task's thread restored, the displaced thread restored, the moved task's thread restored, and a task back in work with its link free, whose restored thread the next pass links. The real-engine test covers the same and the hold without the approval key. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../delivery/BoardTaskThreads.engine.test.ts | 62 ++++++++++++-- .../src/delivery/BoardTaskThreads.test.ts | 69 +++++++++++++-- apps/server/src/delivery/BoardTaskThreads.ts | 85 +++++++++++++------ apps/server/src/delivery/boardThreadRows.ts | 11 +++ 4 files changed, 189 insertions(+), 38 deletions(-) diff --git a/apps/server/src/delivery/BoardTaskThreads.engine.test.ts b/apps/server/src/delivery/BoardTaskThreads.engine.test.ts index cf3937762876e..f9bd56b79f9ab 100644 --- a/apps/server/src/delivery/BoardTaskThreads.engine.test.ts +++ b/apps/server/src/delivery/BoardTaskThreads.engine.test.ts @@ -20,6 +20,7 @@ import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { + CommandId, EnvironmentId, ProviderInstanceId, ProjectId, @@ -150,6 +151,7 @@ function threadStore() { title: string; modelSelection: unknown; archivedAt: string | null; + revision: number; } >(); const receipts = new Set<string>(); @@ -168,21 +170,35 @@ function threadStore() { title: command.title, modelSelection: command.modelSelection, archivedAt: null, + revision: 0, }); const after = hooks.afterCreate; if (after) yield* after(command.threadId); } - if (command.type === "thread.archive") threads.get(command.threadId)!.archivedAt = "archived"; + // Every event of a thread raises its revision, as the event stream's version does. + if (command.type === "thread.archive" || command.type === "thread.unarchive") { + const thread = threads.get(command.threadId)!; + thread.archivedAt = command.type === "thread.archive" ? "archived" : null; + thread.revision += 1; + } return { storedEvents: [] }; }); - return { threads, commands, hooks, dispatch }; + /** A person restores an archived thread from the board's archive. */ + const restore = (threadId: ThreadId) => + dispatch({ + type: "thread.unarchive", + commandId: CommandId.make(`person:restore:${threadId}:${threads.get(threadId)!.revision}`), + threadId, + }); + return { threads, commands, hooks, dispatch, restore }; } -function service(store: ReturnType<typeof threadStore>, key: string = PHRASE) { +function service(store: ReturnType<typeof threadStore>, key: string | null = PHRASE) { return BoardTaskThreads.make.pipe( - Effect.provideService(HostProcess.Environment, { - [BoardTaskThreads.BOARD_THREAD_KEY_VARIABLE]: key, - }), + Effect.provideService( + HostProcess.Environment, + key === null ? {} : { [BoardTaskThreads.BOARD_THREAD_KEY_VARIABLE]: key }, + ), Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { getEnvironmentId: Effect.succeed(ENVIRONMENT), }), @@ -221,6 +237,7 @@ function service(store: ReturnType<typeof threadStore>, key: string = PHRASE) { projectId: PROJECT, title: thread.title, archivedAt: thread.archivedAt, + revision: thread.revision, task, pullRequests: null, issues: null, @@ -337,8 +354,21 @@ const linkLife = Effect.gen(function* () { store.hooks.afterCreate = null; assert.isNotNull(store.threads.get(threadOf(vanishing))!.archivedAt); - // A wrong key is refused by code, and nothing is written or archived. + // Without the approval key nothing is sent to the link route, and the thread waits open. const locked = yield* add(); + const keyless = yield* service(store, null); + assert.deepEqual( + [...(yield* keyless.reconcile())].toSorted(), + [ + [locked, "no-key"], + [moving, "archived-thread"], + ].toSorted(), + ); + assert.isNull(yield* linkOf(locked)); + assert.isNull(store.threads.get(threadOf(locked))!.archivedAt); + assert.equal((yield* setEvents(locked)).length, 0); + + // A wrong key is refused by code, and nothing is written or archived. const wrong = yield* service(store, "not the passphrase at all"); assert.deepEqual( [...(yield* wrong.reconcile())].toSorted(), @@ -357,6 +387,24 @@ const linkLife = Effect.gen(function* () { yield* threads.reconcile(); assert.isNotNull(store.threads.get(threadOf(started))!.archivedAt); assert.isNull(store.threads.get(threadOf(twice))!.archivedAt); + + // Restored from the archive with its task still deleted, or still another conversation's: the + // next pass archives it again, so it never sits open where no list shows it. + for (const id of [started, contested]) { + yield* store.restore(threadOf(id)); + assert.isNull(store.threads.get(threadOf(id))!.archivedAt); + yield* threads.reconcile(); + assert.isNotNull(store.threads.get(threadOf(id))!.archivedAt); + } + assert.equal((yield* linkOf(contested)).threadId, theirs); + + // Restored with its task back in work and the link free: the next pass links it. + yield* store.restore(threadOf(moving)); + assert.deepEqual([...(yield* threads.reconcile())], []); + const relinked = yield* linkOf(moving); + assert.deepEqual([relinked.environmentId, relinked.threadId], [ENVIRONMENT, threadOf(moving)]); + assert.equal((yield* setEvents(moving)).length, 1); + assert.isNull(store.threads.get(threadOf(moving))!.archivedAt); }); it.live.skipIf(ENGINE_ROOT === "")("runs the whole link life against the real engine", () => diff --git a/apps/server/src/delivery/BoardTaskThreads.test.ts b/apps/server/src/delivery/BoardTaskThreads.test.ts index fdebe6e928620..52cddc091613f 100644 --- a/apps/server/src/delivery/BoardTaskThreads.test.ts +++ b/apps/server/src/delivery/BoardTaskThreads.test.ts @@ -1,5 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { + CommandId, EnvironmentId, ProjectId, ThreadId, @@ -58,6 +59,7 @@ interface StoredThread { readonly modelSelection: unknown; readonly marker: string | undefined; archivedAt: string | null; + revision: number; } /** What the thread store keeps across a server restart: threads and command receipts. */ @@ -81,6 +83,7 @@ function threadStore() { modelSelection: command.modelSelection, marker: command.engineIntake, archivedAt: null, + revision: 0, }); receipts.add(command.commandId); const after = hooks.afterCreate; @@ -88,16 +91,27 @@ function threadStore() { after?.(); } if (command.type === "thread.archive") { - threads.get(command.threadId)!.archivedAt = "2026-11-22T11:00:00.000Z"; + const thread = threads.get(command.threadId)!; + thread.archivedAt = "2026-11-22T11:00:00.000Z"; + thread.revision += 1; receipts.add(command.commandId); } if (command.type === "thread.unarchive") { - threads.get(command.threadId)!.archivedAt = null; + const thread = threads.get(command.threadId)!; + thread.archivedAt = null; + thread.revision += 1; receipts.add(command.commandId); } return Effect.succeed({ storedEvents: [] }); }); - return { threads, commands, hooks, dispatch }; + /** A person restores an archived thread from the board's archive. */ + const restore = (threadId: ThreadId) => + dispatch({ + type: "thread.unarchive", + commandId: CommandId.make(`person:restore:${threads.get(threadId)!.revision}`), + threadId, + }); + return { threads, commands, hooks, dispatch, restore }; } type ThreadStore = ReturnType<typeof threadStore>; @@ -163,6 +177,7 @@ function service( projectId: PROJECT, title: thread.title, archivedAt: thread.archivedAt, + revision: thread.revision, task, pullRequests: null, issues: null, @@ -315,6 +330,16 @@ it.effect("adopts the link another writer set first and never overwrites it", () assert.equal(engine.linkOf("task-7")?.threadId, THEIRS); assert.equal(linkWrites(engine).length, 1); assert.equal(engine.requests.filter((request) => request.method === "PUT").length, 1); + // A person restores the displaced thread. The task is still another conversation's, so the + // next pass archives it again, each time it is restored: it never sits open in no list. + for (const restored of [1, 2]) { + yield* store.restore(THREAD); + assert.isNull(store.threads.get(THREAD)!.archivedAt); + yield* threads.reconcile(); + assert.isNotNull(store.threads.get(THREAD)!.archivedAt, `restore ${restored}`); + } + assert.equal(engine.linkOf("task-7")?.threadId, THEIRS); + assert.equal(puts(engine).length, 1); }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-conflict-"))); }); @@ -347,6 +372,25 @@ it.effect("makes no thread for a moved task, and archives one the engine refuses ); assert.equal(puts(engine).length, 1); assert.isNull(engine.linkOf("task-7")); + // Restored while the task is still on the other machine: it holds nothing and is archived + // again. + engine.task("task-7").state = "moved"; + yield* store.restore(THREAD); + assert.deepEqual([...(yield* threads.reconcile())], []); + assert.isNotNull(store.threads.get(THREAD)!.archivedAt); + assert.equal(puts(engine).length, 1); + // The task came back and its link is free: restoring the thread is what links it, on the + // next pass, and it is the task's conversation from then on. + engine.task("task-7").state = "running"; + assert.deepEqual([...(yield* threads.reconcile())], [["task-7", "archived-thread"]]); + yield* store.restore(THREAD); + assert.deepEqual([...(yield* threads.reconcile())], []); + assert.equal(engine.linkOf("task-7")?.threadId, THREAD); + assert.equal(engine.linkOf("task-7")?.environmentId, ENVIRONMENT); + assert.isNotNull(engine.leaseOf("task-7")); + yield* threads.reconcile(); + assert.isNull(store.threads.get(THREAD)!.archivedAt); + assert.equal(store.threads.size, 1); }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-moved-"))); }); @@ -496,10 +540,23 @@ it.effect( assert.isNull(store.threads.get(finished)!.archivedAt); assert.equal(engine.linkOf("task-8")?.threadId, finished); assert.isNull(engine.leaseOf("task-8")); - // A person restored the archived thread from the board: it is not archived a second time. - store.threads.get(THREAD)!.archivedAt = null; - yield* threads.reconcile(); + // A person restores the deleted task's thread. Its task is gone, so no list would show it + // and the board's archive no longer would either: the next pass archives it again, on this + // server and on a new one after a restart, however often it is restored. + yield* store.restore(THREAD); assert.isNull(store.threads.get(THREAD)!.archivedAt); + yield* threads.reconcile(); + assert.isNotNull(store.threads.get(THREAD)!.archivedAt); + yield* store.restore(THREAD); + yield* (yield* service(store)).reconcile(); + assert.isNotNull(store.threads.get(THREAD)!.archivedAt); + // A pass repeated over an archived thread sends no further archive. + const archives = () => + store.commands.filter((command) => command.type === "thread.archive").length; + const sent = archives(); + yield* threads.reconcile(); + assert.equal(archives(), sent); + assert.isNull(store.threads.get(finished)!.archivedAt); }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-ended-"))); }, ); diff --git a/apps/server/src/delivery/BoardTaskThreads.ts b/apps/server/src/delivery/BoardTaskThreads.ts index 539ea04d6fd73..99e434a1d90e1 100644 --- a/apps/server/src/delivery/BoardTaskThreads.ts +++ b/apps/server/src/delivery/BoardTaskThreads.ts @@ -100,7 +100,7 @@ const decodeClaimed = Schema.decodeUnknownOption(Claimed); const decodeSelection = Schema.decodeUnknownEffect(ModelSelection); /** Every task of every board, with each card's link joined once by the engine. */ -const LANES_PATH = "/api/lanes?view=development&set=all"; +export const LANES_PATH = "/api/lanes?view=development&set=all"; // A task in one of these lanes has not started or is not a task run: it has no conversation yet. // `intake` and `ready` are what an engine before the queue lane calls the same wait. @@ -110,6 +110,39 @@ const FINISHED = new Set(["completed", "closed-not-done"]); // A task that moved is worked on another machine; the engine refuses its link here (`moved`). const MOVED = new Set(["moved", "moving"]); +/** A task in work with no conversation: this pass links it to its thread. */ +const awaitsThread = (card: Card) => + card.boardThread === null && + !NOT_STARTED.has(card.lane) && + !FINISHED.has(card.lane) && + !MOVED.has(card.state); + +/** + * How a thread this server made stands with its task, as the engine's lanes show it: `linked` is + * the task's conversation, `free` may still become it, and a `displaced` or `moved` one never + * will here (another conversation holds the task, or it is worked on another machine). The pass + * archives the last two, and the board's archive offers no restore for them. + */ +export const boardThreadStanding = ( + card: { + readonly state: string; + readonly boardThread?: + | { readonly environmentId: string; readonly threadId: string } + | null + | undefined; + }, + environmentId: string, + threadId: string, +) => { + const link = card.boardThread; + if (link) { + return link.environmentId === environmentId && link.threadId === threadId + ? ("linked" as const) + : ("displaced" as const); + } + return MOVED.has(card.state) ? ("moved" as const) : ("free" as const); +}; + /** * The engine's approval key, when the host gives this server one. The link routes are keyed * (spec 6a) and a server holds no person's passphrase, so without this the link is not written. @@ -209,11 +242,17 @@ export const make = Effect.gen(function* () { return yield* local(decodeSelection({ instanceId: instance.instanceId, model: lead.model })); }); - const archive = (task: BoardTask, threadId: ThreadId, why: string) => + /** + * Archives a thread that holds no task. The command id carries the thread's revision, so a pass + * repeated over the same state is answered by the first archive, and a thread a person restored + * since is archived anew: without it the first archive's receipt would answer every later one, + * and the restored thread would stay open, in no list and not in the board's archive. + */ + const archive = (task: BoardTask, threadId: ThreadId, why: string, revision: number) => local( threads.dispatch({ type: "thread.archive", - commandId: CommandId.make(`${boardTaskThreadMarker(task)}:archive:${why}`), + commandId: CommandId.make(`${boardTaskThreadMarker(task)}:archive:${why}:${revision}`), threadId, }), ).pipe(Effect.asVoid); @@ -277,12 +316,14 @@ export const make = Effect.gen(function* () { readonly teams: typeof Teams.Type; readonly folders: ReadonlyMap<string, string>; readonly key: string | undefined; + readonly revisions: ReadonlyMap<string, number>; }, ) { if (!card.set) return "no-board" as const; const task = boardTaskOf(card.set, card.id); if (task === null) return "unmarkable-id" as const; const threadId = boardTaskThreadId(task); + const revision = context.revisions.get(threadId) ?? 0; const folder = context.folders.get(card.set); const project = folder === undefined @@ -346,13 +387,13 @@ export const make = Effect.gen(function* () { yield* holdClaim(card, context.environmentId, threadId); return null; } - yield* archive(task, threadId, "displaced"); + yield* archive(task, threadId, "displaced", revision); return null; } if (refusal.code === "moved" || refusal.code === "not-found") { // The task is worked on another machine, or is gone: it is finished for this server. The // archive is what keeps it so, on every later pass and after a restart. - yield* archive(task, threadId, refusal.code === "moved" ? "moved" : "deleted"); + yield* archive(task, threadId, refusal.code === "moved" ? "moved" : "deleted", revision); return refusal.code === "moved" ? ("moved" as const) : null; } if (refusal.code === "refused") return "refused" as const; @@ -360,8 +401,10 @@ export const make = Effect.gen(function* () { }); /** - * The threads this server made whose task ended: deleted in the engine, or held by another - * conversation now. They are archived, never deleted, and the board lists them. + * The open threads this server made whose task ended here: deleted in the engine, held by + * another conversation, or moved to another machine. They are archived, never deleted, and the + * board lists them. A thread a person restored is judged like any other, so one whose task is + * still gone goes back to the archive on the next pass. */ const settleEnded = Effect.fn("BoardTaskThreads.settleEnded")(function* ( cards: ReadonlyMap<string, Card>, @@ -375,18 +418,13 @@ export const make = Effect.gen(function* () { .pipe(Effect.result); if (read._tag === "Success" || read.failure.status !== 404) continue; yield* releaseClaim(row.task.id); - yield* archive(row.task, row.threadId, "deleted"); + yield* archive(row.task, row.threadId, "deleted", row.revision); continue; } - const link = card.boardThread; - if ( - link !== null && - link !== undefined && - (link.environmentId !== environmentId || link.threadId !== row.threadId) - ) { - yield* releaseClaim(row.task.id); - yield* archive(row.task, row.threadId, "displaced"); - } + const standing = boardThreadStanding(card, environmentId, row.threadId); + if (standing === "linked" || standing === "free") continue; + yield* releaseClaim(row.task.id); + yield* archive(row.task, row.threadId, standing, row.revision); } }); @@ -404,14 +442,11 @@ export const make = Effect.gen(function* () { ); // An engine that serves no `boardThread` has no link to write to. Nothing is made for it. if ([...cards.values()].some((card) => card.boardThread === undefined)) return holds; - const starting = [...cards.values()].filter( - (card) => - card.boardThread === null && - !NOT_STARTED.has(card.lane) && - !FINISHED.has(card.lane) && - !MOVED.has(card.state), - ); + const starting = [...cards.values()].filter(awaitsThread); if (starting.length > 0) { + const revisions = new Map( + (yield* local(rows.list({ archived: false }))).map((row) => [row.threadId, row.revision]), + ); const teams = yield* engine(delivery.read({ path: "/api/teams" })).pipe( Effect.flatMap((response) => engine(decodeTeams(response.body))), ); @@ -422,7 +457,7 @@ export const make = Effect.gen(function* () { ); const key = hostEnvironment[BOARD_THREAD_KEY_VARIABLE] || undefined; for (const card of starting) { - const hold = yield* bind(card, { environmentId, teams, folders, key }); + const hold = yield* bind(card, { environmentId, teams, folders, key, revisions }); if (hold !== null) holds.set(card.id, hold); } } diff --git a/apps/server/src/delivery/boardThreadRows.ts b/apps/server/src/delivery/boardThreadRows.ts index 5c36020d3bec1..82abc8577efc2 100644 --- a/apps/server/src/delivery/boardThreadRows.ts +++ b/apps/server/src/delivery/boardThreadRows.ts @@ -14,6 +14,11 @@ export interface BoardThreadRow { readonly projectId: ProjectId; readonly title: string; readonly archivedAt: string | null; + /** + * The version of the thread's event stream. It grows with every event and never repeats, so it + * tells a thread that was archived and restored from the one first archived. + */ + readonly revision: number; readonly task: BoardTask; /** The thread's pull request and issue links, as stored: JSON arrays, or null for none. */ readonly pullRequests: string | null; @@ -44,6 +49,7 @@ export const listBoardThreadRows = Effect.fn("listBoardThreadRows")(function* (o title: string; archivedAt: string | null; marker: string | null; + revision: number; pullRequests: string | null; issues: string | null; }>` @@ -51,6 +57,10 @@ export const listBoardThreadRows = Effect.fn("listBoardThreadRows")(function* (o t.archived_at AS "archivedAt", json_extract(t.payload_json, '$.pullRequests') AS "pullRequests", json_extract(t.payload_json, '$.issues') AS issues, + ( + SELECT COALESCE(MAX(e.stream_version), 0) FROM orchestration_events AS e + WHERE e.aggregate_kind = 'thread' AND e.stream_id = t.thread_id + ) AS revision, json_extract(t.payload_json, '$.lineage.engineIntake') AS marker FROM orchestration_v2_projection_threads AS t WHERE t.deleted_at IS NULL @@ -67,6 +77,7 @@ export const listBoardThreadRows = Effect.fn("listBoardThreadRows")(function* (o projectId: ProjectId.make(row.projectId), title: row.title, archivedAt: row.archivedAt, + revision: row.revision, task, pullRequests: row.pullRequests, issues: row.issues, From 59da50e76d5c9c218150d2c5ce2e2d2352424924 Mon Sep 17 00:00:00 2001 From: Tevin2119 <tmuparadzi@hotmail.com> Date: Sun, 22 Nov 2026 15:12:01 +0000 Subject: [PATCH 11/13] fix(web): the board's archive offers Restore only where the task can take the thread The archive offered Restore for every thread, including one whose task was deleted, where a restore leaves it holding nothing. The archived board threads read now says how each thread's task stands in the engine: open (its link is free or names this thread), held (another conversation holds it, or it moved), deleted (not in the lanes and the engine answers 404 for it), or unknown (the engine did not answer in time). Only an open task's row offers Restore; the others offer Open and Delete and say why. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../src/delivery/archivedBoardThreads.ts | 96 +++++++++++++++ .../ThreadLaunchService.test.ts | 73 +++++++++++ apps/server/src/ws.ts | 18 +-- .../ArchivedBoardThreads.logic.test.ts | 15 ++- .../delivery/ArchivedBoardThreads.logic.ts | 18 +++ .../delivery/ArchivedBoardThreads.tsx | 114 ++++++++++-------- packages/contracts/src/delivery.ts | 7 ++ 7 files changed, 277 insertions(+), 64 deletions(-) create mode 100644 apps/server/src/delivery/archivedBoardThreads.ts diff --git a/apps/server/src/delivery/archivedBoardThreads.ts b/apps/server/src/delivery/archivedBoardThreads.ts new file mode 100644 index 0000000000000..1ce50163d0f24 --- /dev/null +++ b/apps/server/src/delivery/archivedBoardThreads.ts @@ -0,0 +1,96 @@ +import type { + DeliveryArchivedBoardThreads, + DeliveryError, + DeliveryResponse, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { boardThreadStanding, LANES_PATH } from "./BoardTaskThreads.ts"; +import { listBoardThreadRows } from "./boardThreadRows.ts"; + +const decodeCards = Schema.decodeUnknownOption( + Schema.Struct({ + lanes: Schema.Array( + Schema.Struct({ + cards: Schema.Array( + Schema.Struct({ + id: Schema.String, + state: Schema.String, + boardThread: Schema.optional( + Schema.NullOr( + Schema.Struct({ environmentId: Schema.String, threadId: Schema.String }), + ), + ), + }), + ), + }), + ), + }), +); + +// The archive list is also read when a project is removed: the engine is never waited on for long. +const ENGINE_WAIT = "3 seconds"; + +type ArchivedThread = DeliveryArchivedBoardThreads["threads"][number]; + +/** + * The archived conversations of board tasks, each with how its task stands in the engine. A + * restore only helps a thread whose task can still take it: `open`. A task the engine does not + * list is `deleted` once the engine says so itself (404), and `unknown` while it does not answer, + * so a slow or absent engine never offers a restore and never calls a task deleted. + */ +export const archivedBoardThreads = Effect.fn("archivedBoardThreads")(function* ( + environmentId: string, + read: ((path: string) => Effect.Effect<DeliveryResponse, DeliveryError>) | null, +) { + const rows = yield* listBoardThreadRows({ archived: true }); + const lanes = + read === null || rows.length === 0 + ? Option.none() + : yield* read(LANES_PATH).pipe( + Effect.map((response) => decodeCards(response.body)), + Effect.orElseSucceed(() => Option.none()), + Effect.timeoutOption(ENGINE_WAIT), + Effect.map(Option.flatten), + ); + const cards = new Map( + Option.isSome(lanes) + ? lanes.value.lanes.flatMap((lane) => lane.cards.map((card) => [card.id, card] as const)) + : [], + ); + const taskOf = Effect.fn("archivedBoardThreads.taskOf")(function* ( + row: (typeof rows)[number], + ): Effect.fn.Return<ArchivedThread["task"]> { + if (read === null || Option.isNone(lanes)) return "unknown"; + const card = cards.get(row.task.id); + if (card === undefined) { + const gone = yield* read(`/api/tasks/${row.task.id}`).pipe( + Effect.as(false), + Effect.catch((error) => Effect.succeed(error.status === 404)), + Effect.timeoutOption(ENGINE_WAIT), + ); + return Option.getOrElse(gone, () => false) ? "deleted" : "unknown"; + } + const standing = boardThreadStanding(card, environmentId, row.threadId); + return standing === "linked" || standing === "free" ? "open" : "held"; + }); + const threads = yield* Effect.forEach( + rows, + (row) => + taskOf(row).pipe( + Effect.map((task): ArchivedThread => ({ + threadId: row.threadId, + projectId: row.projectId, + title: row.title, + archivedAt: row.archivedAt ?? "", + board: row.task.board, + taskId: row.task.id, + task, + })), + ), + { concurrency: 4 }, + ); + return { threads }; +}); diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 7d015ad7bdf8c..39161c5d41b69 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -16,11 +16,13 @@ import { boardTaskThreadMarker, } from "../delivery/boardThreadMarker.ts"; import { listBoardThreadRows } from "../delivery/boardThreadRows.ts"; +import { archivedBoardThreads } from "../delivery/archivedBoardThreads.ts"; import { linkedBoardTasks } from "../delivery/linkedBoardTasks.ts"; import { listLinkedPullRequestThreads } from "../pullRequest/linkedThreads.ts"; import { assert, it, vi } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { + DeliveryError, ChatAttachmentId, ComposerContextId, type ChatAttachment, @@ -643,6 +645,77 @@ it.effect("keeps a board task's thread out of both lists, however often it is cr assert.deepEqual(yield* rows(true), [{ threadId, task }]); // The task ended and its conversation is archived: the row stays, told as ended. assert.deepEqual(yield* linkedBoardTasks({ pullRequest }, null), asTask("Task 7", true)); + // The board's archive says how the task stands, which decides whether a restore is offered. + const here = "environment-here"; + const standing = ( + card: Record<string, unknown> | null, + detail: "found" | "gone" | "down" = "gone", + ) => + archivedBoardThreads(here, (path) => + path.startsWith("/api/lanes") + ? card === null + ? Effect.fail(new DeliveryError({ reason: "unreachable", detail: "down" })) + : Effect.succeed({ + readAt: "2026-11-22T10:00:00.000Z", + body: { lanes: [{ cards: "id" in card ? [card] : [] }] }, + }) + : detail === "found" + ? Effect.succeed({ readAt: "2026-11-22T10:00:00.000Z", body: {} }) + : Effect.fail( + new DeliveryError({ + reason: detail === "gone" ? "refused" : "unreachable", + detail, + ...(detail === "gone" ? { status: 404 } : {}), + }), + ), + ).pipe(Effect.map((result) => result.threads.map((entry) => entry.task))); + const card = { id: "task-7", state: "running" }; + // Its link is free, or names this thread: restoring it makes it the task's conversation. + assert.deepEqual(yield* standing({ ...card, boardThread: null }), ["open"]); + assert.deepEqual(yield* standing({ ...card, boardThread: { environmentId: here, threadId } }), [ + "open", + ]); + // Another conversation holds the task, or it moved to another machine: no restore. + assert.deepEqual( + yield* standing({ ...card, boardThread: { environmentId: "other", threadId } }), + ["held"], + ); + assert.deepEqual(yield* standing({ ...card, state: "moved", boardThread: null }), ["held"]); + // Not in the lanes and the engine answers 404 for it: deleted. Any other answer, or an + // engine that is away or not asked, is unknown, never deleted and never restorable. + assert.deepEqual(yield* standing({}), ["deleted"]); + assert.deepEqual(yield* standing({}, "found"), ["unknown"]); + assert.deepEqual(yield* standing({}, "down"), ["unknown"]); + assert.deepEqual(yield* standing(null), ["unknown"]); + assert.deepEqual( + (yield* archivedBoardThreads(here, null)).threads.map((entry) => entry.task), + ["unknown"], + ); + // The row carries the thread's revision, which every archive and restore raises: it is what + // lets a restored thread be archived anew instead of being answered by the first archive. + const revision = (archived: boolean) => + listBoardThreadRows({ archived }).pipe(Effect.map((found) => found[0]!.revision)); + const seen = [yield* revision(true)]; + for (const round of [1, 2]) { + yield* threads.dispatch({ + type: "thread.unarchive", + commandId: CommandId.make(`command:restore-board-task-${round}`), + threadId, + }); + seen.push(yield* revision(false)); + yield* threads.dispatch({ + type: "thread.archive", + commandId: CommandId.make(`command:archive-board-task-${round}`), + threadId, + }); + seen.push(yield* revision(true)); + } + assert.isTrue(seen[0]! > 0); + assert.deepEqual( + seen, + seen.toSorted((a, b) => a - b), + ); + assert.equal(new Set(seen).size, seen.length); }).pipe(Effect.provide(harness.layer)); }); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 312b79f9b839a..b8124c081a5b7 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -267,7 +267,7 @@ import * as ThreadIssueService from "./orchestration-v2/ThreadIssueService.ts"; import * as IssueTrackerConnections from "./issue/IssueTrackerConnections.ts"; import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts"; import { listLinkedPullRequestThreads } from "./pullRequest/linkedThreads.ts"; -import { listBoardThreadRows } from "./delivery/boardThreadRows.ts"; +import { archivedBoardThreads } from "./delivery/archivedBoardThreads.ts"; import { linkedBoardTasks } from "./delivery/linkedBoardTasks.ts"; import { pullRequestSyncKey } from "./pullRequest/pullRequestSyncKey.ts"; import * as SqlClient from "effect/sql/SqlClient"; @@ -3718,6 +3718,7 @@ const layerForkWsRpc = (currentSession: EnvironmentAuth.AuthenticatedSession) => const checkoutUpdate = yield* CheckoutUpdate.CheckoutUpdate; const delivery = yield* DeliveryService.DeliveryService; const sql = yield* SqlClient.SqlClient; + const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; return ForkServerWsRpcGroup.of({ [WS_METHODS.serverSubscribeCheckoutUpdate]: (_input) => checkoutUpdate.states, [WS_METHODS.serverCheckCheckoutUpdate]: (_input) => @@ -3735,18 +3736,11 @@ const layerForkWsRpc = (currentSession: EnvironmentAuth.AuthenticatedSession) => [WS_METHODS.deliveryBindThread]: (input) => delivery.bindThread(input), [WS_METHODS.deliveryThreadBinding]: (input) => delivery.threadState(input.threadId), [WS_METHODS.deliveryArchivedBoardThreads]: () => - listBoardThreadRows({ archived: true }).pipe( + serverEnvironment.getEnvironmentId.pipe( + Effect.flatMap((environmentId) => + archivedBoardThreads(environmentId, (path) => delivery.read({ path })), + ), Effect.provideService(SqlClient.SqlClient, sql), - Effect.map((rows) => ({ - threads: rows.map((row) => ({ - threadId: row.threadId, - projectId: row.projectId, - title: row.title, - archivedAt: row.archivedAt ?? "", - board: row.task.board, - taskId: row.task.id, - })), - })), Effect.mapError( () => new DeliveryError({ diff --git a/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts index a7ab75c8f51bd..2a8e2e9db26c5 100644 --- a/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts @@ -1,7 +1,7 @@ import { ProjectId, ThreadId } from "@t3tools/contracts"; import { expect, it } from "vite-plus/test"; -import { archivedThreadsOfBoard } from "./ArchivedBoardThreads.logic"; +import { archivedThreadsOfBoard, archivedThreadTaskNote } from "./ArchivedBoardThreads.logic"; const thread = (board: string, taskId: string, archivedAt: string) => ({ threadId: ThreadId.make(`thread-${taskId}`), @@ -10,6 +10,7 @@ const thread = (board: string, taskId: string, archivedAt: string) => ({ archivedAt, board, taskId, + task: "open" as const, }); it("lists the open board's archived conversations, newest first, and every board's on all", () => { @@ -26,3 +27,15 @@ it("lists the open board's archived conversations, newest first, and every board ]); expect(archivedThreadsOfBoard(threads, "none")).toEqual([]); }); + +it("offers a restore only for a task that can take the thread back, and says why not", () => { + const row = thread("work", "a", "2026-11-20T10:00:00.000Z"); + // No note is the restore: the row of an open task shows Open, Restore and Delete. + expect(archivedThreadTaskNote(row)).toBeNull(); + expect(archivedThreadTaskNote({ ...row, task: "deleted" })).toBe("The task was deleted."); + // An engine that did not answer never offers a restore and never calls the task deleted. + expect(archivedThreadTaskNote({ ...row, task: "unknown" })).toBe( + "The task could not be checked.", + ); + expect(archivedThreadTaskNote({ ...row, task: "held" })).toBe("The task is held elsewhere."); +}); diff --git a/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts index 5cac75af0d1e5..97bb55c17389d 100644 --- a/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts @@ -14,3 +14,21 @@ export function archivedThreadsOfBoard( .filter((thread) => board === "all" || thread.board === board) .toSorted((a, b) => b.archivedAt.localeCompare(a.archivedAt)); } + +/** + * What the archive says under a thread whose task cannot take it back, or null for one that can + * and is offered a restore. A restored thread of any other task holds nothing and is archived + * again, so the restore is not offered for it. + */ +export function archivedThreadTaskNote(thread: ArchivedBoardThread): string | null { + switch (thread.task) { + case "open": + return null; + case "deleted": + return "The task was deleted."; + case "held": + return "The task is held elsewhere."; + case "unknown": + return "The task could not be checked."; + } +} diff --git a/apps/web/src/components/delivery/ArchivedBoardThreads.tsx b/apps/web/src/components/delivery/ArchivedBoardThreads.tsx index 0cf9b7341e4f4..1f19afd36d8f7 100644 --- a/apps/web/src/components/delivery/ArchivedBoardThreads.tsx +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.tsx @@ -12,11 +12,16 @@ import { RelativeTime } from "../RelativeTime"; import { Button } from "../ui/button"; import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "../ui/popover"; import { toastManager } from "../ui/toast"; -import { archivedThreadsOfBoard, type ArchivedBoardThread } from "./ArchivedBoardThreads.logic"; +import { + archivedThreadsOfBoard, + archivedThreadTaskNote, + type ArchivedBoardThread, +} from "./ArchivedBoardThreads.logic"; /** * The board's door to the conversations of tasks that ended. Such a thread is archived, never - * deleted, and no thread list shows it, so this is where it is opened, restored or deleted. + * deleted, and no thread list shows it, so this is where it is opened, restored or deleted. A + * restore is offered only where the task can take the thread back. */ export function ArchivedBoardThreads(props: { readonly environmentId: EnvironmentId; @@ -93,57 +98,64 @@ export function ArchivedBoardThreads(props: { </p> ) : ( <ul className="flex max-h-[60vh] flex-col gap-1 overflow-y-auto"> - {threads.map((thread) => ( - <li - key={thread.threadId} - className="flex items-center gap-2 rounded-md border border-border px-2 py-1.5" - data-board-archived-thread={thread.taskId} - > - <div className="min-w-0 flex-1"> - <button + {threads.map((thread) => { + const note = archivedThreadTaskNote(thread); + return ( + <li + key={thread.threadId} + className="flex items-center gap-2 rounded-md border border-border px-2 py-1.5" + data-board-archived-thread={thread.taskId} + data-board-archived-task={thread.task} + > + <div className="min-w-0 flex-1"> + <button + type="button" + className="block max-w-full truncate text-left text-xs font-medium underline-offset-2 hover:underline" + onClick={() => + void navigate({ + to: "/$environmentId/$threadId", + params: { + environmentId: props.environmentId, + threadId: thread.threadId, + }, + }) + } + > + {thread.title} + </button> + <p className="truncate text-2xs text-muted-foreground"> + {props.board === "all" ? `${thread.board} · ` : null} + Archived <RelativeTime timestamp={thread.archivedAt} /> + {note === null ? null : ` · ${note}`} + </p> + </div> + {note === null ? ( + <Button + type="button" + size="icon-sm" + variant="outline" + aria-label={`Restore ${thread.title}`} + title="Restore" + disabled={pending !== null} + onClick={() => void act("restore", thread)} + > + <ArchiveX className="size-3.5" /> + </Button> + ) : null} + <Button type="button" - className="block max-w-full truncate text-left text-xs font-medium underline-offset-2 hover:underline" - onClick={() => - void navigate({ - to: "/$environmentId/$threadId", - params: { - environmentId: props.environmentId, - threadId: thread.threadId, - }, - }) - } + size="icon-sm" + variant="destructive-outline" + aria-label={`Delete ${thread.title}`} + title="Delete" + disabled={pending !== null} + onClick={() => void act("delete", thread)} > - {thread.title} - </button> - <p className="truncate text-2xs text-muted-foreground"> - {props.board === "all" ? `${thread.board} · ` : null} - Archived <RelativeTime timestamp={thread.archivedAt} /> - </p> - </div> - <Button - type="button" - size="icon-sm" - variant="outline" - aria-label={`Restore ${thread.title}`} - title="Restore" - disabled={pending !== null} - onClick={() => void act("restore", thread)} - > - <ArchiveX className="size-3.5" /> - </Button> - <Button - type="button" - size="icon-sm" - variant="destructive-outline" - aria-label={`Delete ${thread.title}`} - title="Delete" - disabled={pending !== null} - onClick={() => void act("delete", thread)} - > - <Trash2Icon className="size-3.5" /> - </Button> - </li> - ))} + <Trash2Icon className="size-3.5" /> + </Button> + </li> + ); + })} </ul> )} </PopoverPopup> diff --git a/packages/contracts/src/delivery.ts b/packages/contracts/src/delivery.ts index c2ba039c5e6e0..3e0db5242fbfe 100644 --- a/packages/contracts/src/delivery.ts +++ b/packages/contracts/src/delivery.ts @@ -235,6 +235,13 @@ export const DeliveryArchivedBoardThreads = Schema.Struct({ /** The board and the task the thread was made for. */ board: Schema.String, taskId: Schema.String, + /** + * How the task stands in the engine. Only an `open` task can take the thread back, so only + * its thread is offered a restore: a restored thread of any other is archived again. + * `held` is a task another conversation holds or that moved to another machine; `unknown` + * is an engine that did not answer. + */ + task: Schema.Literals(["open", "held", "deleted", "unknown"]), }), ), }); From 046824337e63b51bfe198d5f893d14fc2f15270a Mon Sep 17 00:00:00 2001 From: Tevin2119 <tmuparadzi@hotmail.com> Date: Sun, 22 Nov 2026 15:14:17 +0000 Subject: [PATCH 12/13] fix(server): the archive's engine check has one wait, inside the removal read's deadline Removing a project reads the archived board threads with a two second deadline. The engine check now has a single 1.5 second wait for the lanes and every task read together: past it each task is unknown and the rows are still answered, so a slow engine never costs the removal confirmation its count. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../src/delivery/archivedBoardThreads.ts | 99 ++++++++++--------- 1 file changed, 52 insertions(+), 47 deletions(-) diff --git a/apps/server/src/delivery/archivedBoardThreads.ts b/apps/server/src/delivery/archivedBoardThreads.ts index 1ce50163d0f24..a6b04b2ac7441 100644 --- a/apps/server/src/delivery/archivedBoardThreads.ts +++ b/apps/server/src/delivery/archivedBoardThreads.ts @@ -30,8 +30,9 @@ const decodeCards = Schema.decodeUnknownOption( }), ); -// The archive list is also read when a project is removed: the engine is never waited on for long. -const ENGINE_WAIT = "3 seconds"; +// One wait for the whole engine check. Removing a project reads this list too, with a two second +// deadline of its own: past this wait every task is unknown and the rows are still answered. +const ENGINE_WAIT = "1500 millis"; type ArchivedThread = DeliveryArchivedBoardThreads["threads"][number]; @@ -46,51 +47,55 @@ export const archivedBoardThreads = Effect.fn("archivedBoardThreads")(function* read: ((path: string) => Effect.Effect<DeliveryResponse, DeliveryError>) | null, ) { const rows = yield* listBoardThreadRows({ archived: true }); - const lanes = - read === null || rows.length === 0 - ? Option.none() - : yield* read(LANES_PATH).pipe( - Effect.map((response) => decodeCards(response.body)), - Effect.orElseSucceed(() => Option.none()), - Effect.timeoutOption(ENGINE_WAIT), - Effect.map(Option.flatten), + type Row = (typeof rows)[number]; + const check = Effect.fn("archivedBoardThreads.check")(function* ( + ask: (path: string) => Effect.Effect<DeliveryResponse, DeliveryError>, + ) { + const lanes = yield* ask(LANES_PATH).pipe( + Effect.map((response) => decodeCards(response.body)), + Effect.orElseSucceed(() => Option.none()), + ); + if (Option.isNone(lanes)) return new Map<Row, ArchivedThread["task"]>(); + const cards = new Map( + lanes.value.lanes.flatMap((lane) => lane.cards.map((card) => [card.id, card] as const)), + ); + const taskOf = (row: Row): Effect.Effect<ArchivedThread["task"]> => { + const card = cards.get(row.task.id); + if (card === undefined) { + return ask(`/api/tasks/${row.task.id}`).pipe( + Effect.as("unknown" as const), + Effect.catch((error) => + Effect.succeed(error.status === 404 ? ("deleted" as const) : ("unknown" as const)), + ), ); - const cards = new Map( - Option.isSome(lanes) - ? lanes.value.lanes.flatMap((lane) => lane.cards.map((card) => [card.id, card] as const)) - : [], - ); - const taskOf = Effect.fn("archivedBoardThreads.taskOf")(function* ( - row: (typeof rows)[number], - ): Effect.fn.Return<ArchivedThread["task"]> { - if (read === null || Option.isNone(lanes)) return "unknown"; - const card = cards.get(row.task.id); - if (card === undefined) { - const gone = yield* read(`/api/tasks/${row.task.id}`).pipe( - Effect.as(false), - Effect.catch((error) => Effect.succeed(error.status === 404)), - Effect.timeoutOption(ENGINE_WAIT), - ); - return Option.getOrElse(gone, () => false) ? "deleted" : "unknown"; - } - const standing = boardThreadStanding(card, environmentId, row.threadId); - return standing === "linked" || standing === "free" ? "open" : "held"; - }); - const threads = yield* Effect.forEach( - rows, - (row) => - taskOf(row).pipe( - Effect.map((task): ArchivedThread => ({ - threadId: row.threadId, - projectId: row.projectId, - title: row.title, - archivedAt: row.archivedAt ?? "", - board: row.task.board, - taskId: row.task.id, - task, - })), + } + const standing = boardThreadStanding(card, environmentId, row.threadId); + return Effect.succeed(standing === "linked" || standing === "free" ? "open" : "held"); + }; + return new Map( + yield* Effect.forEach( + rows, + (row) => taskOf(row).pipe(Effect.map((task) => [row, task] as const)), + { concurrency: 4 }, ), - { concurrency: 4 }, - ); - return { threads }; + ); + }); + const tasks = + read === null || rows.length === 0 + ? Option.none() + : yield* check(read).pipe(Effect.timeoutOption(ENGINE_WAIT)); + return { + threads: rows.map((row): ArchivedThread => ({ + threadId: row.threadId, + projectId: row.projectId, + title: row.title, + archivedAt: row.archivedAt ?? "", + board: row.task.board, + taskId: row.task.id, + task: Option.match(tasks, { + onNone: () => "unknown" as const, + onSome: (found) => found.get(row) ?? "unknown", + }), + })), + }; }); From 4c93060a75f1dd4e8b6d24e9a14dedcde33da477 Mon Sep 17 00:00:00 2001 From: Tevin2119 <tmuparadzi@hotmail.com> Date: Sun, 22 Nov 2026 15:59:02 +0000 Subject: [PATCH 13/13] fix(server): a moved board task's thread is held and re-archived on the real engine The engine lists a task that moved to another machine in no lane, and still answers for it with its state. The archive door and the reconcile pass read only the lanes, so such a thread was told as "could not be checked" and a forced restore of it stayed open in no list. Both now read the state from the task's own detail when the lanes leave the task out. A moved task that kept this thread as its conversation keeps it open, and its claim is released. The scratch engine now leaves moved tasks out of the lanes as the real one does. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../delivery/BoardTaskThreads.engine.test.ts | 11 ++++ .../src/delivery/BoardTaskThreads.test.ts | 54 +++++++++++++++++-- apps/server/src/delivery/BoardTaskThreads.ts | 38 +++++++++++-- .../src/delivery/archivedBoardThreads.ts | 30 ++++++----- .../src/delivery/boardThreadEngine.testkit.ts | 16 ++++-- .../ThreadLaunchService.test.ts | 24 ++++++--- 6 files changed, 142 insertions(+), 31 deletions(-) diff --git a/apps/server/src/delivery/BoardTaskThreads.engine.test.ts b/apps/server/src/delivery/BoardTaskThreads.engine.test.ts index f9bd56b79f9ab..436005039ca55 100644 --- a/apps/server/src/delivery/BoardTaskThreads.engine.test.ts +++ b/apps/server/src/delivery/BoardTaskThreads.engine.test.ts @@ -342,6 +342,17 @@ const linkLife = Effect.gen(function* () { store.hooks.afterCreate = null; assert.isNotNull(store.threads.get(threadOf(moving))!.archivedAt); assert.isNull(yield* linkOf(moving)); + // The engine lists a moved task in no lane and still answers for it. A forced restore of its + // thread is archived again on the next pass, from the state its detail gives. + const lanes = yield* engineGet(BoardTaskThreads.LANES_PATH); + assert.isFalse( + lanes.lanes.some((lane: any) => lane.cards.some((card: any) => card.id === moving)), + ); + assert.equal((yield* engineGet(`/api/tasks/${moving}`)).state, "moved"); + yield* store.restore(threadOf(moving)); + assert.isNull(store.threads.get(threadOf(moving))!.archivedAt); + assert.deepEqual([...(yield* threads.reconcile())], []); + assert.isNotNull(store.threads.get(threadOf(moving))!.archivedAt); yield* control("/move", { id: moving, state: "triage" }); assert.deepEqual([...(yield* threads.reconcile())], [[moving, "archived-thread"]]); assert.isNull(yield* linkOf(moving)); diff --git a/apps/server/src/delivery/BoardTaskThreads.test.ts b/apps/server/src/delivery/BoardTaskThreads.test.ts index 52cddc091613f..83aed6ebfeab9 100644 --- a/apps/server/src/delivery/BoardTaskThreads.test.ts +++ b/apps/server/src/delivery/BoardTaskThreads.test.ts @@ -372,12 +372,21 @@ it.effect("makes no thread for a moved task, and archives one the engine refuses ); assert.equal(puts(engine).length, 1); assert.isNull(engine.linkOf("task-7")); - // Restored while the task is still on the other machine: it holds nothing and is archived - // again. + // Restored while the task is still on the other machine. The lanes no longer list it, so + // the task's own detail is what says it moved: the thread holds nothing and is archived + // again, each time it is restored, on this server and on a new one after a restart. engine.task("task-7").state = "moved"; - yield* store.restore(THREAD); - assert.deepEqual([...(yield* threads.reconcile())], []); - assert.isNotNull(store.threads.get(THREAD)!.archivedAt); + for (const pass of [threads, yield* service(store)]) { + yield* store.restore(THREAD); + assert.isNull(store.threads.get(THREAD)!.archivedAt); + assert.deepEqual([...(yield* pass.reconcile())], []); + assert.isNotNull(store.threads.get(THREAD)!.archivedAt); + assert.deepEqual(engine.requests.at(-1), { + method: "GET", + path: "/api/tasks/task-7", + body: undefined, + }); + } assert.equal(puts(engine).length, 1); // The task came back and its link is free: restoring the thread is what links it, on the // next pass, and it is the task's conversation from then on. @@ -394,6 +403,41 @@ it.effect("makes no thread for a moved task, and archives one the engine refuses }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-moved-"))); }); +it.effect( + "archives a moved task's thread once its link is gone, and keeps one it still holds", + () => { + const engine = board(); + engine.addTask({ id: "task-7" }); + engine.addTask({ id: "task-8" }); + engine.addTask({ id: "task-9" }); + const store = threadStore(); + const threadOf = (id: string) => boardTaskThreadId(boardTaskOf("work", id)!); + return Effect.gen(function* () { + const threads = yield* service(store); + yield* threads.reconcile(); + // Three linked tasks leave this machine. One lost its link first, one keeps it, and one is + // still on its way, which the lanes go on listing. + engine.handle("DELETE", "/api/tasks/task-7/board-thread", { key: engine.key }); + engine.task("task-7").state = "moved"; + engine.task("task-8").state = "moved"; + engine.task("task-9").state = "moving"; + yield* threads.reconcile(); + assert.isNotNull(store.threads.get(THREAD)!.archivedAt); + // A thread its moved task still names stays the task's conversation, and claims nothing. + for (const id of ["task-8", "task-9"]) { + assert.isNull(store.threads.get(threadOf(id))!.archivedAt, id); + assert.equal(engine.linkOf(id)?.threadId, threadOf(id)); + assert.isNull(engine.leaseOf(id), id); + } + assert.isNull(engine.leaseOf("task-7")); + // A forced restore of the moved task's thread cannot leave it open in no list. + yield* store.restore(THREAD); + yield* threads.reconcile(); + assert.isNotNull(store.threads.get(THREAD)!.archivedAt); + }).pipe(Effect.provide(deliveryLayer(engine, "board-threads-moved-away-"))); + }, +); + it.effect("archives the thread of a task the engine no longer has, and never asks again", () => { const engine = board(); engine.addTask({ id: "task-7" }); diff --git a/apps/server/src/delivery/BoardTaskThreads.ts b/apps/server/src/delivery/BoardTaskThreads.ts index 99e434a1d90e1..48a4e5fc03926 100644 --- a/apps/server/src/delivery/BoardTaskThreads.ts +++ b/apps/server/src/delivery/BoardTaskThreads.ts @@ -97,6 +97,14 @@ const decodeRefusal = Schema.decodeUnknownOption(Refusal); const decodeLinked = Schema.decodeUnknownEffect(Linked); const decodeDetail = Schema.decodeUnknownOption(Detail); const decodeClaimed = Schema.decodeUnknownOption(Claimed); +const decodeStanding = Schema.decodeUnknownOption( + Schema.Struct({ + state: Schema.String, + boardThread: Schema.optional( + Schema.NullOr(Schema.Struct({ environmentId: Schema.String, threadId: Schema.String })), + ), + }), +); const decodeSelection = Schema.decodeUnknownEffect(ModelSelection); /** Every task of every board, with each card's link joined once by the engine. */ @@ -143,6 +151,19 @@ export const boardThreadStanding = ( return MOVED.has(card.state) ? ("moved" as const) : ("free" as const); }; +/** + * The standing of a thread whose task the lanes do not list, from the task's own detail. The + * engine gives a task that moved to another machine no lane, and still answers for it with its + * state: that answer is the only place that says so. Any other task the lanes leave out is not + * judged here (`null`). + */ +export const movedTaskStanding = (detail: unknown, environmentId: string, threadId: string) => { + const task = decodeStanding(detail); + return Option.isSome(task) && MOVED.has(task.value.state) + ? boardThreadStanding(task.value, environmentId, threadId) + : null; +}; + /** * The engine's approval key, when the host gives this server one. The link routes are keyed * (spec 6a) and a server holds no person's passphrase, so without this the link is not written. @@ -402,8 +423,8 @@ export const make = Effect.gen(function* () { /** * The open threads this server made whose task ended here: deleted in the engine, held by - * another conversation, or moved to another machine. They are archived, never deleted, and the - * board lists them. A thread a person restored is judged like any other, so one whose task is + * another conversation, or moved to another machine without keeping this one. They are + * archived, never deleted, and the board lists them. A thread a person restored is judged like any other, so one whose task is * still gone goes back to the archive on the next pass. */ const settleEnded = Effect.fn("BoardTaskThreads.settleEnded")(function* ( @@ -416,9 +437,18 @@ export const make = Effect.gen(function* () { const read = yield* delivery .read({ path: `/api/tasks/${row.task.id}` }) .pipe(Effect.result); - if (read._tag === "Success" || read.failure.status !== 404) continue; + // Only the engine's own answer ends a thread: 404 is a deleted task, and a task it still + // answers for as moved is on another machine. Anything else is left for the next pass. + const ended = + read._tag === "Success" + ? movedTaskStanding(read.success.body, environmentId, row.threadId) + : read.failure.status === 404 + ? ("deleted" as const) + : null; + if (ended === null || ended === "free") continue; + // A moved task takes no work here, whether or not it kept this thread as its conversation. yield* releaseClaim(row.task.id); - yield* archive(row.task, row.threadId, "deleted", row.revision); + if (ended !== "linked") yield* archive(row.task, row.threadId, ended, row.revision); continue; } const standing = boardThreadStanding(card, environmentId, row.threadId); diff --git a/apps/server/src/delivery/archivedBoardThreads.ts b/apps/server/src/delivery/archivedBoardThreads.ts index a6b04b2ac7441..51aae2dc76466 100644 --- a/apps/server/src/delivery/archivedBoardThreads.ts +++ b/apps/server/src/delivery/archivedBoardThreads.ts @@ -7,7 +7,7 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import { boardThreadStanding, LANES_PATH } from "./BoardTaskThreads.ts"; +import { boardThreadStanding, LANES_PATH, movedTaskStanding } from "./BoardTaskThreads.ts"; import { listBoardThreadRows } from "./boardThreadRows.ts"; const decodeCards = Schema.decodeUnknownOption( @@ -38,9 +38,9 @@ type ArchivedThread = DeliveryArchivedBoardThreads["threads"][number]; /** * The archived conversations of board tasks, each with how its task stands in the engine. A - * restore only helps a thread whose task can still take it: `open`. A task the engine does not - * list is `deleted` once the engine says so itself (404), and `unknown` while it does not answer, - * so a slow or absent engine never offers a restore and never calls a task deleted. + * restore only helps a thread whose task can still take it: `open`. A task the lanes do not list + * is `deleted` on the engine's 404, judged by its own detail when that says it moved away, and + * `unknown` otherwise: a slow or absent engine never offers a restore or calls a task deleted. */ export const archivedBoardThreads = Effect.fn("archivedBoardThreads")(function* ( environmentId: string, @@ -60,17 +60,21 @@ export const archivedBoardThreads = Effect.fn("archivedBoardThreads")(function* lanes.value.lanes.flatMap((lane) => lane.cards.map((card) => [card.id, card] as const)), ); const taskOf = (row: Row): Effect.Effect<ArchivedThread["task"]> => { + const told = (standing: ReturnType<typeof boardThreadStanding>) => + standing === "linked" || standing === "free" ? ("open" as const) : ("held" as const); const card = cards.get(row.task.id); - if (card === undefined) { - return ask(`/api/tasks/${row.task.id}`).pipe( - Effect.as("unknown" as const), - Effect.catch((error) => - Effect.succeed(error.status === 404 ? ("deleted" as const) : ("unknown" as const)), - ), - ); + if (card !== undefined) { + return Effect.succeed(told(boardThreadStanding(card, environmentId, row.threadId))); } - const standing = boardThreadStanding(card, environmentId, row.threadId); - return Effect.succeed(standing === "linked" || standing === "free" ? "open" : "held"); + return ask(`/api/tasks/${row.task.id}`).pipe( + Effect.map((response) => { + const standing = movedTaskStanding(response.body, environmentId, row.threadId); + return standing === null ? ("unknown" as const) : told(standing); + }), + Effect.catch((error) => + Effect.succeed(error.status === 404 ? ("deleted" as const) : ("unknown" as const)), + ), + ); }; return new Map( yield* Effect.forEach( diff --git a/apps/server/src/delivery/boardThreadEngine.testkit.ts b/apps/server/src/delivery/boardThreadEngine.testkit.ts index 37c43087cdc42..39d32043b0c5d 100644 --- a/apps/server/src/delivery/boardThreadEngine.testkit.ts +++ b/apps/server/src/delivery/boardThreadEngine.testkit.ts @@ -212,7 +212,8 @@ export function scratchEngine( const body = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>; requests.push({ method, path: pathname, body: raw }); if (method === "GET" && pathname === "/api/lanes") { - const cards = [...tasks.values()].map(cardOf); + // A task that moved away has no lane and is on no board; one on its way keeps its lane. + const cards = [...tasks.values()].filter((task) => task.state !== "moved").map(cardOf); return { status: 200, body: { @@ -229,9 +230,18 @@ export function scratchEngine( const detail = /^\/api\/tasks\/([\w-]+)$/.exec(pathname); if (method === "GET" && detail) { const task = tasks.get(detail[1]!); - // `thread` keeps meaning the task id; the conversation is only ever `boardThread`. + // `thread` keeps meaning the task id; the conversation is only ever `boardThread`. A moved + // task is still answered for, with its state and no lane. return task - ? { status: 200, body: { ...cardOf(task), thread: task.id, source: null } } + ? { + status: 200, + body: { + ...cardOf(task), + ...(task.state === "moved" ? { lane: null } : {}), + thread: task.id, + source: null, + }, + } : refused(404, `no task ${detail[1]}`); } // The moved guard of every task write, which runs before the key is looked at. diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 39161c5d41b69..78be6bc505d0c 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -649,7 +649,7 @@ it.effect("keeps a board task's thread out of both lists, however often it is cr const here = "environment-here"; const standing = ( card: Record<string, unknown> | null, - detail: "found" | "gone" | "down" = "gone", + detail: "gone" | "down" | Record<string, unknown> = "gone", ) => archivedBoardThreads(here, (path) => path.startsWith("/api/lanes") @@ -659,8 +659,8 @@ it.effect("keeps a board task's thread out of both lists, however often it is cr readAt: "2026-11-22T10:00:00.000Z", body: { lanes: [{ cards: "id" in card ? [card] : [] }] }, }) - : detail === "found" - ? Effect.succeed({ readAt: "2026-11-22T10:00:00.000Z", body: {} }) + : typeof detail === "object" + ? Effect.succeed({ readAt: "2026-11-22T10:00:00.000Z", body: detail }) : Effect.fail( new DeliveryError({ reason: detail === "gone" ? "refused" : "unreachable", @@ -675,16 +675,28 @@ it.effect("keeps a board task's thread out of both lists, however often it is cr assert.deepEqual(yield* standing({ ...card, boardThread: { environmentId: here, threadId } }), [ "open", ]); - // Another conversation holds the task, or it moved to another machine: no restore. + // Another conversation holds the task, or it is on its way to another machine: no restore. assert.deepEqual( yield* standing({ ...card, boardThread: { environmentId: "other", threadId } }), ["held"], ); - assert.deepEqual(yield* standing({ ...card, state: "moved", boardThread: null }), ["held"]); + assert.deepEqual(yield* standing({ ...card, state: "moving", boardThread: null }), ["held"]); // Not in the lanes and the engine answers 404 for it: deleted. Any other answer, or an // engine that is away or not asked, is unknown, never deleted and never restorable. assert.deepEqual(yield* standing({}), ["deleted"]); - assert.deepEqual(yield* standing({}, "found"), ["unknown"]); + assert.deepEqual(yield* standing({}, { state: "closed" }), ["unknown"]); + assert.deepEqual(yield* standing({}, {}), ["unknown"]); + // A task that moved away is in no lane, and the engine still answers for it: held, unless + // it kept this thread as its conversation. + assert.deepEqual(yield* standing({}, { state: "moved", boardThread: null }), ["held"]); + assert.deepEqual( + yield* standing({}, { state: "moved", boardThread: { environmentId: "other", threadId } }), + ["held"], + ); + assert.deepEqual( + yield* standing({}, { state: "moved", boardThread: { environmentId: here, threadId } }), + ["open"], + ); assert.deepEqual(yield* standing({}, "down"), ["unknown"]); assert.deepEqual(yield* standing(null), ["unknown"]); assert.deepEqual(