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 ( Linked threads + {boardTasks.map((task) => ( + + + + + {gt("Board task: {title}", { title: task.title })} + + + {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")} + + + + ))} {threads.map((thread) => { const title = thread.title || gt("Untitled thread"); return ( 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: { removeMembers([member])} + onPress={() => void removeMembers([member])} /> ) : null} @@ -486,7 +503,7 @@ function ProjectOverviewContent(props: { tone="danger" disabled={!canRemoveGroup || isRemoving} loading={isRemoving} - onPress={() => removeMembers(props.members)} + onPress={() => void removeMembers(props.members)} /> diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index f03e4461b41c2..db34830fff7cd 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5463,5 +5463,9 @@ "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", + "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 69ba52747808c..04ba1477f4016 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5465,5 +5465,9 @@ "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", + "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 e56c4c97cbf70..2e3e2af7aa351 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5457,5 +5457,9 @@ "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", + "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 e78bb03676d9a..3c32856a6cdc9 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5457,5 +5457,9 @@ "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", + "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 b49054983d456..aa3af10b65dfc 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5438,5 +5438,9 @@ "ad208e3e32c85029": "すべて非表示", "3328503592789bed": "Zen", "856812e7e1fc445e": "チャット内のツール呼び出し", - "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。" + "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。", + "cdf5dd7d370e594c": "ボードのタスク: {title}", + "dae94973cc4ff259": "タスクは終了しました。会話はボードのアーカイブにあります", + "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 7c9d231cb1953..ffdf2e31dedcf 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5442,5 +5442,9 @@ "ad208e3e32c85029": "모두 숨기기", "3328503592789bed": "Zen", "856812e7e1fc445e": "채팅의 도구 호출", - "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다." + "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다.", + "cdf5dd7d370e594c": "보드 작업: {title}", + "dae94973cc4ff259": "작업이 종료되었습니다. 대화는 보드의 보관함에 있습니다", + "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 948c273b6220e..497666749800d 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5457,5 +5457,9 @@ "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", + "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 28ec612ac4946..24fb4ac8d2b19 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5537,5 +5537,9 @@ "ad208e3e32c85029": "Скрывать все", "3328503592789bed": "Дзен", "856812e7e1fc445e": "Вызовы инструментов в чате", - "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда." + "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда.", + "cdf5dd7d370e594c": "Задача доски: {title}", + "dae94973cc4ff259": "Задача завершена. Её обсуждение находится в архиве доски", + "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 035949f616d16..b80843748c3ba 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5463,5 +5463,9 @@ "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", + "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 04206812c2c5e..4b9be3ca97195 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5448,5 +5448,9 @@ "ad208e3e32c85029": "全部隐藏", "3328503592789bed": "专注模式", "856812e7e1fc445e": "聊天中的工具调用", - "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。" + "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。", + "cdf5dd7d370e594c": "看板任务:{title}", + "dae94973cc4ff259": "任务已结束。其对话位于看板的归档中", + "afeb354df4c94446": "请在网页版或桌面应用的看板中打开", + "a65acdb87eac322b": "{count, plural, other {由看板发起的 {count} 个已归档对话会保留,不会删除。}}" } 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 +// +// 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= board-thread-engine.ts ", + ); + 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((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((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/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/BoardTaskThreads.engine.test.ts b/apps/server/src/delivery/BoardTaskThreads.engine.test.ts new file mode 100644 index 0000000000000..436005039ca55 --- /dev/null +++ b/apps/server/src/delivery/BoardTaskThreads.engine.test.ts @@ -0,0 +1,429 @@ +// @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 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 { + CommandId, + 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((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 = {}) => + 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; + revision: number; + } + >(); + const receipts = new Set(); + const commands: Array = []; + const hooks: { afterCreate: ((threadId: string) => Effect.Effect) | 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, + revision: 0, + }); + const after = hooks.afterCreate; + if (after) yield* after(command.threadId); + } + // 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: [] }; + }); + /** 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, key: string | null = PHRASE) { + return BoardTaskThreads.make.pipe( + Effect.provideService( + HostProcess.Environment, + key === null ? {} : { [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, + revision: thread.revision, + 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)); + // 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)); + 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); + + // 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(), + [ + [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); + + // 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", () => + 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/delivery/BoardTaskThreads.test.ts b/apps/server/src/delivery/BoardTaskThreads.test.ts new file mode 100644 index 0000000000000..83aed6ebfeab9 --- /dev/null +++ b/apps/server/src/delivery/BoardTaskThreads.test.ts @@ -0,0 +1,653 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { + CommandId, + 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 { + boardTaskOf, + 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. BoardTaskThreads.engine.test.ts runs the real engine. + +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; + revision: number; +} + +/** 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, + revision: 0, + }); + receipts.add(command.commandId); + const after = hooks.afterCreate; + hooks.afterCreate = null; + after?.(); + } + if (command.type === "thread.archive") { + 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") { + const thread = threads.get(command.threadId)!; + thread.archivedAt = null; + thread.revision += 1; + receipts.add(command.commandId); + } + return Effect.succeed({ storedEvents: [] }); + }); + /** 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; + +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 }, + archivedAt: store.threads.get(threadId)?.archivedAt ?? null, + }, + }), + } 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, + revision: thread.revision, + task, + pullRequests: null, + issues: null, + }, + ]; + }), + ), + }), + ); +} + +/** 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 = 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"); + +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: THEIRS, setBy: OTHER }); + }); + const threads = yield* service(store); + yield* threads.reconcile(); + // 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, 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-"))); +}); + +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"))); + // 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")); + // 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"; + 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. + 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-"))); +}); + +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" }); + 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())], []); + 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-"))); +}); + +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(boardTaskOf("work", "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 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-"))); + }, +); + +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..48a4e5fc03926 --- /dev/null +++ b/apps/server/src/delivery/BoardTaskThreads.ts @@ -0,0 +1,530 @@ +// 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 { + boardTaskOf, + 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 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 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. */ +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. +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"]); + +/** 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 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. + */ +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"; + +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 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(); + 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 })); + }); + + /** + * 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}:${revision}`), + 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); + }); + + 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, + context: { + readonly environmentId: EnvironmentId; + readonly teams: typeof Teams.Type; + readonly folders: ReadonlyMap; + readonly key: string | undefined; + readonly revisions: ReadonlyMap; + }, + ) { + 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 + ? 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; + // 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* 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. 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; + } + 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", revision); + 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 }); + }); + + /** + * The open threads this server made whose task ended here: deleted in the engine, held by + * 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* ( + 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); + // 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); + if (ended !== "linked") yield* archive(row.task, row.threadId, ended, row.revision); + continue; + } + 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); + } + }); + + 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(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))), + ); + 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, revisions }); + 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/archivedBoardThreads.ts b/apps/server/src/delivery/archivedBoardThreads.ts new file mode 100644 index 0000000000000..51aae2dc76466 --- /dev/null +++ b/apps/server/src/delivery/archivedBoardThreads.ts @@ -0,0 +1,105 @@ +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, movedTaskStanding } 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 }), + ), + ), + }), + ), + }), + ), + }), +); + +// 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]; + +/** + * 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 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, + read: ((path: string) => Effect.Effect) | null, +) { + const rows = yield* listBoardThreadRows({ archived: true }); + type Row = (typeof rows)[number]; + const check = Effect.fn("archivedBoardThreads.check")(function* ( + ask: (path: string) => Effect.Effect, + ) { + const lanes = yield* ask(LANES_PATH).pipe( + Effect.map((response) => decodeCards(response.body)), + Effect.orElseSucceed(() => Option.none()), + ); + if (Option.isNone(lanes)) return new Map(); + const cards = new Map( + lanes.value.lanes.flatMap((lane) => lane.cards.map((card) => [card.id, card] as const)), + ); + const taskOf = (row: Row): Effect.Effect => { + const told = (standing: ReturnType) => + standing === "linked" || standing === "free" ? ("open" as const) : ("held" as const); + const card = cards.get(row.task.id); + if (card !== undefined) { + return Effect.succeed(told(boardThreadStanding(card, environmentId, row.threadId))); + } + 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( + rows, + (row) => taskOf(row).pipe(Effect.map((task) => [row, task] as const)), + { concurrency: 4 }, + ), + ); + }); + 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", + }), + })), + }; +}); diff --git a/apps/server/src/delivery/boardThreadEngine.testkit.ts b/apps/server/src/delivery/boardThreadEngine.testkit.ts new file mode 100644 index 0000000000000..39d32043b0c5d --- /dev/null +++ b/apps/server/src/delivery/boardThreadEngine.testkit.ts @@ -0,0 +1,374 @@ +// A scratch engine serving the frozen task-to-thread contract (BOARD-REVAMP-UI-SPEC.md 6a), with +// 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"; +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; + /** 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; + + 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") { + // 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: { + 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`. A moved + // task is still answered for, with its state and no lane. + return task + ? { + 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. + 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, + linkWrites, + }; +} + +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 = () => { + const { status, body: answered } = engine.handle(request.method, url.pathname, body); + return HttpClientResponse.fromWeb( + request, + status === 204 + ? new Response(null, { status: 204 }) + : 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 0b2f8723ab980..bf80180241297 100644 --- a/apps/server/src/delivery/boardThreadMarker.test.ts +++ b/apps/server/src/delivery/boardThreadMarker.test.ts @@ -4,7 +4,16 @@ import * as NodePath from "node:path"; import { assert, it } from "@effect/vitest"; -import { boardTaskThreadMarker } from "./boardThreadMarker.ts"; +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 @@ -59,27 +68,97 @@ 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\),$/, +]; + +// 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 reads the marker's value; every other reader asks whether it is set", () => { +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", () => { - 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("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 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, and another prefix. + `intake-${"a".repeat(64)}:0`, + "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 857eb3f40308c..ddd8fadfe73ff 100644 --- a/apps/server/src/delivery/boardThreadMarker.ts +++ b/apps/server/src/delivery/boardThreadMarker.ts @@ -1,16 +1,53 @@ -import { CommandId } from "@t3tools/contracts"; +import { CommandId, ThreadId } from "@t3tools/contracts"; -interface BoardTask { +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:"; + +// 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. 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}${task.board}:${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, 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 [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/delivery/boardThreadRows.ts b/apps/server/src/delivery/boardThreadRows.ts new file mode 100644 index 0000000000000..82abc8577efc2 --- /dev/null +++ b/apps/server/src/delivery/boardThreadRows.ts @@ -0,0 +1,99 @@ +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; + /** + * 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; + readonly issues: string | null; +} + +/** + * 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") {} + +/** 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; + revision: number; + 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, + ( + 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 + 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, + revision: row.revision, + task, + pullRequests: row.pullRequests, + issues: row.issues, + }, + ]; + }); +}); + +export const layer = Layer.effect( + BoardThreadRows, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return BoardThreadRows.of({ + list: Effect.fn("BoardThreadRows.list")((options) => + listBoardThreadRows(options).pipe(Effect.provideService(SqlClient.SqlClient, sql)), + ), + }); + }), +); 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 | null, +): Effect.fn.Return, never, SqlClient.SqlClient> { + const linked = + "pullRequest" in link ? linksPullRequest(link.pullRequest) : linksIssue(link.issue); + const list = (archived: boolean) => + listBoardThreadRows({ archived }).pipe( + Effect.orElseSucceed((): ReadonlyArray => []), + ); + 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/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 2209f4baf4353..78be6bc505d0c 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -10,10 +10,19 @@ 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 { 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, @@ -21,6 +30,7 @@ import { DEFAULT_SERVER_SETTINGS, EnvironmentId, GitCommandError, + IssueTrackerKind, MessageId, RunId, ProjectId, @@ -544,7 +554,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", @@ -577,6 +587,147 @@ 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), []); + // 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"), + threadId, + }); + 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)); + // The board's archive says how the task stands, which decides whether a restore is offered. + const here = "environment-here"; + const standing = ( + card: Record | null, + detail: "gone" | "down" | Record = "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] : [] }] }, + }) + : typeof detail === "object" + ? Effect.succeed({ readAt: "2026-11-22T10:00:00.000Z", body: detail }) + : 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 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: "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({}, { 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( + (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)); }); @@ -620,10 +771,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/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; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index a391562d28359..b8124c081a5b7 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,8 @@ 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 { archivedBoardThreads } from "./delivery/archivedBoardThreads.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"; @@ -1994,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 = ( + result: A, + link: Parameters[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), @@ -2846,6 +2870,7 @@ export const layerWsRpc = ( ? Effect.succeed({ threads: [] }) : listLinkedPullRequestThreads(key).pipe( Effect.provideService(SqlClient.SqlClient, sql), + Effect.flatMap((result) => withBoardTasks(result, { pullRequest: key })), ), ), ), @@ -3692,6 +3717,8 @@ const layerForkWsRpc = (currentSession: EnvironmentAuth.AuthenticatedSession) => Effect.gen(function* () { 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) => @@ -3708,6 +3735,20 @@ 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]: () => + serverEnvironment.getEnvironmentId.pipe( + Effect.flatMap((environmentId) => + archivedBoardThreads(environmentId, (path) => delivery.read({ path })), + ), + Effect.provideService(SqlClient.SqlClient, sql), + 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/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; } 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) => Promise; + /** + * 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; + 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: , + 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/delivery/ArchivedBoardThreads.logic.test.ts b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts new file mode 100644 index 0000000000000..2a8e2e9db26c5 --- /dev/null +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.test.ts @@ -0,0 +1,41 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { expect, it } from "vite-plus/test"; + +import { archivedThreadsOfBoard, archivedThreadTaskNote } 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, + task: "open" as const, +}); + +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([]); +}); + +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 new file mode 100644 index 0000000000000..97bb55c17389d --- /dev/null +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.logic.ts @@ -0,0 +1,34 @@ +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)); +} + +/** + * 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 new file mode 100644 index 0000000000000..1f19afd36d8f7 --- /dev/null +++ b/apps/web/src/components/delivery/ArchivedBoardThreads.tsx @@ -0,0 +1,164 @@ +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, + 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. A + * restore is offered only where the task can take the thread back. + */ +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) => { + const note = archivedThreadTaskNote(thread); + return ( +
  • +
    + +

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

    +
    + {note === null ? ( + + ) : null} + +
  • + ); + })} +
+ )} +
+
+ ); +} 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 9ddb0a0b201e6..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, @@ -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"; @@ -61,6 +62,7 @@ import { InWorkSections, QueueLine, ReworkCount, WaitKinds } from "./BoardLaneCa import { TaskEditor } from "./TaskEditor"; import { Age, + CardActivity, CardPeople, CardSigns, laneTone, @@ -87,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; @@ -141,6 +167,7 @@ const CardFace = memo(function CardFace(props: { {card.blocker}

) : null} +
{showsKinds ? null : } @@ -348,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} @@ -732,7 +760,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/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/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) ? ( - {linkedThreads.length || "?"} + {linkedCount || "?"} } /> 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) ? ( - {linkedThreads.length || "?"} + {linkedCount || "?"} } /> 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 a78cbae36068a..edf4b2429baa2 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12569,5 +12569,9 @@ "27d76249d09eb69f": "Review-Leitfaden bereit", "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", - "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden" + "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", + "cdf5dd7d370e594c": "Board-Aufgabe: {title}", + "dae94973cc4ff259": "Aufgabe beendet. Die Unterhaltung liegt im Archiv des Boards", + "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 cadb6c9682c8c..036a20f29b85d 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12578,5 +12578,9 @@ "27d76249d09eb69f": "Review guide ready", "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", - "9e91e9a77b664e4e": "Could not start a review guide" + "9e91e9a77b664e4e": "Could not start a review guide", + "cdf5dd7d370e594c": "Board task: {title}", + "dae94973cc4ff259": "Task ended. Its conversation is in the board's archive", + "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 43221088433c0..9c085522977c0 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12564,5 +12564,9 @@ "27d76249d09eb69f": "Guía de revisión lista", "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", - "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión" + "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", + "cdf5dd7d370e594c": "Tarea del tablero: {title}", + "dae94973cc4ff259": "Tarea finalizada. Su conversación está en el archivo del 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 56d9ba529d20b..6e81a78e7b966 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12569,5 +12569,9 @@ "27d76249d09eb69f": "Guide de revue prêt", "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", - "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue" + "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", + "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", + "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 58b37026d557d..a2b5eb2d9d1c4 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12518,5 +12518,9 @@ "27d76249d09eb69f": "レビューガイドの準備ができました", "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", - "9e91e9a77b664e4e": "レビューガイドを開始できませんでした" + "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", + "cdf5dd7d370e594c": "ボードのタスク: {title}", + "dae94973cc4ff259": "タスクは終了しました。会話はボードのアーカイブにあります", + "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 d0b8a743bd720..440600c7b8b77 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12513,5 +12513,9 @@ "27d76249d09eb69f": "검토 가이드 준비됨", "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", - "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다" + "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", + "cdf5dd7d370e594c": "보드 작업: {title}", + "dae94973cc4ff259": "작업이 종료되었습니다. 대화는 보드의 보관함에 있습니다", + "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 e56ec30d7efb0..28c644480f68a 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12569,5 +12569,9 @@ "27d76249d09eb69f": "Guia de revisão pronto", "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", - "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão" + "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", + "cdf5dd7d370e594c": "Tarefa do quadro: {title}", + "dae94973cc4ff259": "Tarefa encerrada. A conversa está no arquivo do 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 9e0f129145336..8a441652f5dd5 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12569,5 +12569,9 @@ "27d76249d09eb69f": "Гид по ревью готов", "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", - "9e91e9a77b664e4e": "Не удалось запустить гид по ревью" + "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", + "cdf5dd7d370e594c": "Задача доски: {title}", + "dae94973cc4ff259": "Задача завершена. Её обсуждение находится в архиве доски", + "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 e5e48d2ba7e36..a17857f305b1b 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12576,5 +12576,9 @@ "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", + "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 3a81d633db38b..cc2731649de17 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12595,5 +12595,9 @@ "27d76249d09eb69f": "审查导览已就绪", "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", - "9e91e9a77b664e4e": "无法开始生成审查导览" + "9e91e9a77b664e4e": "无法开始生成审查导览", + "cdf5dd7d370e594c": "看板任务:{title}", + "dae94973cc4ff259": "任务已结束。其对话位于看板的归档中", + "1f8f11ca7798711e": "在看板上打开该任务", + "a65acdb87eac322b": "{count, plural, other {由看板发起的 {count} 个已归档对话会保留,不会删除。}}" } 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 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?: 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", diff --git a/packages/client-runtime/src/state/delivery.ts b/packages/client-runtime/src/state/delivery.ts index 3b42c784340c5..d26ca83a8d833 100644 --- a/packages/client-runtime/src/state/delivery.ts +++ b/packages/client-runtime/src/state/delivery.ts @@ -23,6 +23,17 @@ 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, + }), + /** 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 | null>; + readonly timeoutMs?: number; +}): Promise { + 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, >( @@ -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.")), diff --git a/packages/contracts/src/delivery.ts b/packages/contracts/src/delivery.ts index afbc71f7a106a..3e0db5242fbfe 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,47 @@ 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, + /** + * 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"]), + }), + ), +}); +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; 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,