diff --git a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx index ca9a8999e3ddc..71d814b302b16 100644 --- a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx @@ -46,7 +46,7 @@ import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-en import { leaveSettingsPage } from "./settings-navigation"; import { workspaceHasColumns } from "../layout/workspace/workspace-selection-store"; import { DEFAULT_SETTINGS_PAGE } from "../layout/workspace/workspace-tab-navigation"; -import { readUnloadedThreadCount } from "../../state/olderSettledShelf"; +import { readServerOwnedThreadCount, readUnloadedThreadCount } from "../../state/olderSettledShelf"; import { m } from "../../i18n/messages"; export function SettingsProjectOverviewRouteScreen() { @@ -253,6 +253,7 @@ function ProjectOverviewContent(props: { displayName, threads, unloadedThreadCount: readUnloadedThreadCount(members, threads), + serverOwnedThreadCount: readServerOwnedThreadCount(members, threads), }, m, ); diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 8777f08e663ce..f03e4461b41c2 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -723,6 +723,7 @@ "bac5ef48aafb20b1": "Dadurch werden {count} gruppierte Projekteinträge entfernt.", "3e46fbf3eadf0745": "Diese Threads und alle archivierten Threads werden aus T3 Code gelöscht. Anbietersitzungen bleiben erhalten.", "1a50cbc984f8fe1c": "Alle archivierten Threads werden aus T3 Code gelöscht. Anbietersitzungen bleiben erhalten.", + "361080ce34c8e8ed": "{count, plural, one {{count} von einem Board oder der Engine gestartetes Gespräch wird archiviert, nicht gelöscht.} other {{count} von einem Board oder der Engine gestartete Gespräche werden archiviert, nicht gelöscht.}} Bereits archivierte Board- und Engine-Gespräche bleiben erhalten.", "4f076ebbf1c8846e": "Dadurch werden nur die Projekteinträge entfernt, nicht die Dateien auf der Festplatte.", "19b8f3ad79efb9e1": "Andere Einträge in diesem gruppierten Projekt sind nicht betroffen.", "2207c69b042b2e37": "Diese Aktion kann nicht rückgängig gemacht werden.", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index dfe3a473fe248..69ba52747808c 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -723,6 +723,7 @@ "bac5ef48aafb20b1": "This removes {count} grouped project entries.", "3e46fbf3eadf0745": "Those threads and any archived threads are deleted from T3 Code. Provider sessions are kept.", "1a50cbc984f8fe1c": "Any archived threads are deleted from T3 Code. Provider sessions are kept.", + "361080ce34c8e8ed": "{count, plural, one {{count} conversation started by a board or the engine is archived, not deleted.} other {{count} conversations started by a board or the engine are archived, not deleted.}} Board and engine conversations already archived are kept.", "4f076ebbf1c8846e": "This removes only the project entries, not the files on disk.", "19b8f3ad79efb9e1": "Other entries in this grouped project are unaffected.", "2207c69b042b2e37": "This action cannot be undone.", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 05f58a63227d3..e56c4c97cbf70 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -723,6 +723,7 @@ "bac5ef48aafb20b1": "Esto quita {count} entradas de proyecto agrupadas.", "3e46fbf3eadf0745": "Esos hilos y los hilos archivados se eliminan de T3 Code. Las sesiones del proveedor se conservan.", "1a50cbc984f8fe1c": "Los hilos archivados se eliminan de T3 Code. Las sesiones del proveedor se conservan.", + "361080ce34c8e8ed": "{count, plural, one {{count} conversación iniciada por un tablero o por el motor se archiva, no se elimina.} other {{count} conversaciones iniciadas por un tablero o por el motor se archivan, no se eliminan.}} Las conversaciones de tableros y del motor ya archivadas se conservan.", "4f076ebbf1c8846e": "Esto solo quita las entradas del proyecto, no los archivos del disco.", "19b8f3ad79efb9e1": "Las demás entradas de este proyecto agrupado no se ven afectadas.", "2207c69b042b2e37": "Esta acción no se puede deshacer.", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index f661c315215c0..e78bb03676d9a 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -723,6 +723,7 @@ "bac5ef48aafb20b1": "Cela retire {count} entrées de projet regroupées.", "3e46fbf3eadf0745": "Ces fils et tous les fils archivés sont supprimés de T3 Code. Les sessions du fournisseur sont conservées.", "1a50cbc984f8fe1c": "Tous les fils archivés sont supprimés de T3 Code. Les sessions du fournisseur sont conservées.", + "361080ce34c8e8ed": "{count, plural, one {{count} conversation lancée par un tableau ou par le moteur est archivée, pas supprimée.} other {{count} conversations lancées par un tableau ou par le moteur sont archivées, pas supprimées.}} Les conversations de tableaux et du moteur déjà archivées sont conservées.", "4f076ebbf1c8846e": "Cela retire uniquement les entrées de projet, pas les fichiers sur le disque.", "19b8f3ad79efb9e1": "Les autres entrées de ce projet regroupé ne sont pas affectées.", "2207c69b042b2e37": "Cette action est irréversible.", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 56616809052d3..b49054983d456 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -723,6 +723,7 @@ "bac5ef48aafb20b1": "グループ化された {count} 件のプロジェクトエントリを削除します。", "3e46fbf3eadf0745": "それらのスレッドとアーカイブ済みのスレッドは T3 Code から削除されます。プロバイダーのセッションは保持されます。", "1a50cbc984f8fe1c": "アーカイブ済みのスレッドは T3 Code から削除されます。プロバイダーのセッションは保持されます。", + "361080ce34c8e8ed": "{count, plural, other {ボードまたはエンジンが開始した会話 {count} 件はアーカイブされ、削除されません。}}すでにアーカイブ済みのボードおよびエンジンの会話は保持されます。", "4f076ebbf1c8846e": "削除されるのはプロジェクトのエントリだけで、ディスク上のファイルは削除されません。", "19b8f3ad79efb9e1": "このグループ化されたプロジェクト内の他のエントリには影響しません。", "2207c69b042b2e37": "この操作は元に戻せません。", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 443285f8664c4..7c9d231cb1953 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -723,6 +723,7 @@ "bac5ef48aafb20b1": "그룹화된 프로젝트 항목 {count}개를 제거합니다.", "3e46fbf3eadf0745": "해당 스레드와 보관된 스레드는 T3 Code에서 삭제됩니다. 제공자 세션은 유지됩니다.", "1a50cbc984f8fe1c": "보관된 스레드는 T3 Code에서 삭제됩니다. 제공자 세션은 유지됩니다.", + "361080ce34c8e8ed": "{count, plural, other {보드 또는 엔진이 시작한 대화 {count}개는 삭제되지 않고 보관됩니다.}} 이미 보관된 보드 및 엔진 대화는 그대로 유지됩니다.", "4f076ebbf1c8846e": "디스크의 파일이 아닌 프로젝트 항목만 제거합니다.", "19b8f3ad79efb9e1": "이 그룹화된 프로젝트의 다른 항목은 영향을 받지 않습니다.", "2207c69b042b2e37": "이 작업은 되돌릴 수 없습니다.", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 33793cc553d34..948c273b6220e 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -723,6 +723,7 @@ "bac5ef48aafb20b1": "Isto remove {count} entradas de projeto agrupadas.", "3e46fbf3eadf0745": "Essas threads e as threads arquivadas são excluídas do T3 Code. As sessões do provedor são mantidas.", "1a50cbc984f8fe1c": "As threads arquivadas são excluídas do T3 Code. As sessões do provedor são mantidas.", + "361080ce34c8e8ed": "{count, plural, one {{count} conversa iniciada por um quadro ou pelo motor é arquivada, não excluída.} other {{count} conversas iniciadas por um quadro ou pelo motor são arquivadas, não excluídas.}} As conversas de quadros e do motor já arquivadas são mantidas.", "4f076ebbf1c8846e": "Isto remove apenas as entradas do projeto, não os arquivos no disco.", "19b8f3ad79efb9e1": "As outras entradas deste projeto agrupado não são afetadas.", "2207c69b042b2e37": "Esta ação não pode ser desfeita.", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index d0e2d9577a9ab..28ec612ac4946 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -723,6 +723,7 @@ "bac5ef48aafb20b1": "Будут удалены сгруппированные записи проекта: {count}.", "3e46fbf3eadf0745": "Эти треды и все архивные треды будут удалены из T3 Code. Сеансы провайдера сохранятся.", "1a50cbc984f8fe1c": "Все архивные треды будут удалены из T3 Code. Сеансы провайдера сохранятся.", + "361080ce34c8e8ed": "{count, plural, one {{count} разговор, начатый доской или движком, будет архивирован, а не удалён.} few {{count} разговора, начатых доской или движком, будут архивированы, а не удалены.} many {{count} разговоров, начатых доской или движком, будут архивированы, а не удалены.} other {{count} разговора, начатых доской или движком, будут архивированы, а не удалены.}} Уже архивированные разговоры досок и движка сохранятся.", "4f076ebbf1c8846e": "Удаляются только записи проекта, а не файлы на диске.", "19b8f3ad79efb9e1": "Другие записи в этом сгруппированном проекте не затрагиваются.", "2207c69b042b2e37": "Это действие нельзя отменить.", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7fd2f945cc033..035949f616d16 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -723,6 +723,7 @@ "bac5ef48aafb20b1": "Det här tar bort {count} grupperade projektposter.", "3e46fbf3eadf0745": "De trådarna och eventuella arkiverade trådar tas bort från T3 Code. Leverantörssessioner behålls.", "1a50cbc984f8fe1c": "Eventuella arkiverade trådar tas bort från T3 Code. Leverantörssessioner behålls.", + "361080ce34c8e8ed": "{count, plural, one {{count} konversation som startats av en tavla eller motorn arkiveras, den tas inte bort.} other {{count} konversationer som startats av en tavla eller motorn arkiveras, de tas inte bort.}} Redan arkiverade konversationer från tavlor och motorn behålls.", "4f076ebbf1c8846e": "Det här tar bara bort projektposterna, inte filerna på disken.", "19b8f3ad79efb9e1": "Andra poster i det här grupperade projektet påverkas inte.", "2207c69b042b2e37": "Den här åtgärden kan inte ångras.", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 54c72efe3b4fb..04206812c2c5e 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -723,6 +723,7 @@ "bac5ef48aafb20b1": "将移除 {count} 个已分组的项目条目。", "3e46fbf3eadf0745": "这些会话及所有已归档会话将从 T3 Code 中删除。提供方自身保存的对话记录会保留。", "1a50cbc984f8fe1c": "所有已归档会话将从 T3 Code 中删除。提供方自身保存的对话记录会保留。", + "361080ce34c8e8ed": "{count, plural, other {由看板或引擎发起的 {count} 个对话将被归档,不会删除。}}已归档的看板和引擎对话会保留。", "4f076ebbf1c8846e": "仅移除项目条目,磁盘上的文件会保留。", "19b8f3ad79efb9e1": "此项目组中的其他条目不受影响。", "2207c69b042b2e37": "此操作无法撤销。", diff --git a/apps/mobile/src/state/olderSettledShelf.ts b/apps/mobile/src/state/olderSettledShelf.ts index e55bf927b4b06..6cfd786c08411 100644 --- a/apps/mobile/src/state/olderSettledShelf.ts +++ b/apps/mobile/src/state/olderSettledShelf.ts @@ -1,5 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import { serverOwnedThreadCount } from "@t3tools/client-runtime/state/projects"; import { isListedSettledThread, settledShelfFrontier, @@ -137,3 +138,19 @@ export function useOlderSettledCount( ); return project === null ? 0 : (older?.counts.get(project.id) ?? 0); } + +/** + * Threads of these projects that the server started for itself, which the shell counts and does + * not send: see `serverOwnedThreadCount`. A project removal archives them. + */ +export function readServerOwnedThreadCount( + members: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly id: ProjectId }>, + threads: ReadonlyArray, +): number { + return serverOwnedThreadCount({ + members, + counted: (environmentId) => + appAtomRegistry.get(threadFamilies.snapshotAtom(environmentId))?.serverOwnedThreads, + threads, + }); +} diff --git a/apps/mobile/src/state/use-thread-selection.test.tsx b/apps/mobile/src/state/use-thread-selection.test.tsx new file mode 100644 index 0000000000000..464054d15e5e9 --- /dev/null +++ b/apps/mobile/src/state/use-thread-selection.test.tsx @@ -0,0 +1,186 @@ +import * as NodeModule from "node:module"; + +import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/threads"; +import { + EnvironmentId, + isListedThreadLineage, + ThreadId, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Option from "effect/Option"; +import { act, useLayoutEffect } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +import { extractAgentNotificationDeepLink } from "../features/agent-awareness/notificationPayload"; +import { scopedThreadKey } from "../lib/scopedEntities"; +import { makeRawThreadShell } from "../test-fixtures"; + +// The environment is stood in for at the two reads the thread route makes: the shell row and the +// thread's own detail. Mobile has no fake socket to drive a whole screen against. +const harness = vi.hoisted(() => ({ + route: { key: "thread", name: "Thread", params: {} as object }, + shell: null as unknown, + detail: null as unknown, + detailReads: [] as Array, +})); + +vi.mock("@react-navigation/native", () => ({ useRoute: () => harness.route })); +vi.mock("./entities", () => ({ + useQuietThreadShell: () => harness.shell, + useProject: () => null, +})); +vi.mock("./threads", () => ({ + useEnvironmentThread: (environmentId: string | null, threadId: string | null) => { + harness.detailReads.push([environmentId, threadId]); + return environmentId === null ? EMPTY_ENVIRONMENT_THREAD_STATE : harness.detail; + }, +})); +vi.mock("./use-thread-outbox", () => ({ useThreadOutboxMessages: () => ({}) })); +vi.mock("./use-remote-environment-registry", () => ({ + useRemoteEnvironmentRuntime: () => null, + useSavedRemoteConnection: () => null, +})); + +import { useThreadSelection } from "./use-thread-selection"; + +const requireNavigation = NodeModule.createRequire( + NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"), +); +const { getStateFromPath } = requireNavigation("@react-navigation/core") as { + getStateFromPath: typeof import("@react-navigation/native").getStateFromPath; +}; + +const environmentId = EnvironmentId.make("environment-1"); +const threadId = ThreadId.make("board-task-thread"); +const boardTask = makeRawThreadShell({ + id: threadId, + title: "Task 7", + lineage: { + rootThreadId: threadId, + parentThreadId: null, + relationshipToParent: null, + engineIntake: "board-task:board-1:task-7", + }, +}); + +function detailOf(archivedAt: DateTime.Utc | null): OrchestrationV2ThreadProjection { + return { + thread: { + id: boardTask.id, + projectId: boardTask.projectId, + title: boardTask.title, + providerInstanceId: boardTask.providerInstanceId, + modelSelection: boardTask.modelSelection, + runtimeMode: boardTask.runtimeMode, + interactionMode: boardTask.interactionMode, + branch: boardTask.branch, + worktreePath: boardTask.worktreePath, + activeProviderThreadId: boardTask.activeProviderThreadId, + lineage: boardTask.lineage, + forkedFrom: boardTask.forkedFrom, + createdBy: boardTask.createdBy, + creationSource: boardTask.creationSource, + createdAt: boardTask.createdAt, + updatedAt: boardTask.updatedAt, + archivedAt, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + runs: [], + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + plans: [], + turnItems: [], + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: [], + updatedAt: boardTask.updatedAt, + }; +} + +/** The Thread route's params for a link, read with the path `Stack.tsx` gives that route. */ +function threadRouteParams(link: string) { + const state = getStateFromPath(link, { + screens: { Thread: { path: "threads/:environmentId?/:threadId?" } }, + }); + const route = state?.routes.at(-1); + if (route?.name !== "Thread") throw new Error(`${link} did not open the thread route`); + return route.params ?? {}; +} + +function select() { + let selection: ReturnType | null = null; + function Probe() { + const current = useThreadSelection(); + useLayoutEffect(() => { + selection = current; + }); + return null; + } + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + try { + act(() => root.render()); + return (selection as ReturnType | null)!; + } finally { + act(() => root.unmount()); + } +} + +const archivedAt = DateTime.makeUnsafe("2026-11-20T00:00:00.000Z"); +const live = { ...EMPTY_ENVIRONMENT_THREAD_STATE, status: "live" as const }; + +it.each([ + { shell: "left its row out", row: null, detail: detailOf(null), archived: false }, + { shell: "has archived it", row: null, detail: detailOf(archivedAt), archived: true }, + { shell: "got its row as a delta", row: boardTask, detail: null, archived: false }, +])("opens a board task's thread from a link by id when the shell $shell", (c) => { + // The link a notification or another app hands over, as the app itself writes it. + const link = extractAgentNotificationDeepLink({ + notification: { request: { content: { data: { environmentId, threadId } } } }, + }); + expect(link).toBe("/threads/environment-1/board-task-thread"); + harness.route = { key: "thread", name: "Thread", params: threadRouteParams(link!) }; + harness.shell = c.row === null ? null : { ...c.row, environmentId }; + harness.detail = c.detail === null ? live : { ...live, data: Option.some(c.detail) }; + harness.detailReads = []; + + const { selectedThread } = select(); + + // The route screen shows the thread when the selection is the thread the route names. + expect(selectedThread).not.toBeNull(); + expect(scopedThreadKey(selectedThread!.environmentId, selectedThread!.id)).toBe( + scopedThreadKey(environmentId, threadId), + ); + expect(selectedThread!.title).toBe("Task 7"); + // It is still a thread no list shows: the lists filter on this lineage. + expect(isListedThreadLineage(selectedThread!.lineage)).toBe(false); + expect(selectedThread!.archivedAt !== null).toBe(c.archived); + // Without a row the thread's own detail is what opens it; with one the detail is not read here. + expect(harness.detailReads.at(-1)).toEqual( + c.row === null ? [environmentId, threadId] : [null, null], + ); +}); + +it("has no thread to show when neither the shell nor the thread's detail knows the id", () => { + harness.route = { + key: "thread", + name: "Thread", + params: threadRouteParams("/threads/environment-1/gone"), + }; + harness.shell = null; + harness.detail = { ...EMPTY_ENVIRONMENT_THREAD_STATE, status: "deleted" as const }; + expect(select().selectedThread).toBeNull(); +}); diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index aa1231e934c16..0a20af3980e36 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -46,6 +46,7 @@ const reactTests = [ "src/native/useRetryingImageSource.test.tsx", "src/state/queries.debounce.test.tsx", "src/state/use-selected-thread-git-state.test.tsx", + "src/state/use-thread-selection.test.tsx", "src/features/terminal/useTerminalExitNavigation.test.tsx", "src/features/threads/use-thread-list-now.test.tsx", "src/features/threads/use-composer-command-menu.select.test.tsx", diff --git a/apps/server/src/delivery/boardThreadMarker.test.ts b/apps/server/src/delivery/boardThreadMarker.test.ts new file mode 100644 index 0000000000000..0b2f8723ab980 --- /dev/null +++ b/apps/server/src/delivery/boardThreadMarker.test.ts @@ -0,0 +1,85 @@ +// @effect-diagnostics nodeBuiltinImport:off - reads the source tree synchronously, once. +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import { assert, it } from "@effect/vitest"; + +import { boardTaskThreadMarker } from "./boardThreadMarker.ts"; + +// A board task's thread reuses `lineage.engineIntake` as its marker, with a value of its own. That +// is safe only while every reader but the engine intake asks whether the field is set, never what +// it holds: a reader of the value would treat a board thread as an intake, or find a thread from a +// task. These tests read the source, so a new reader has to be named here on purpose. + +const REPO = NodePath.resolve(import.meta.dirname, "../../../.."); +const SOURCE_ROOTS = [ + "apps/server/src", + "apps/web/src", + "apps/mobile/src", + "apps/desktop/src", + "packages/contracts/src", + "packages/client-runtime/src", + "packages/shared/src", +]; + +function sourceFiles(directory: string): ReadonlyArray { + return NodeFS.readdirSync(NodePath.join(REPO, directory), { withFileTypes: true }).flatMap( + (entry) => { + const path = `${directory}/${entry.name}`; + if (entry.isDirectory()) return entry.name === "node_modules" ? [] : sourceFiles(path); + return /\.tsx?$/.test(entry.name) && !/\.test\.tsx?$/.test(entry.name) ? [path] : []; + }, + ); +} + +const linesNaming = (pattern: RegExp) => + SOURCE_ROOTS.flatMap(sourceFiles).flatMap((file) => + NodeFS.readFileSync(NodePath.join(REPO, file), "utf8") + .split("\n") + .filter((line) => pattern.test(line)) + .map((line) => ({ file, line: line.trim() })), + ); + +// Every way the field may appear without its value deciding anything. +const NOT_A_VALUE_READ: ReadonlyArray = [ + // The schema and the row types that declare it. + /^engineIntake: Schema\.optional\(TrimmedNonEmptyString\),$/, + /^readonly engine_intake\??: string \| null;$/, + /^lineage: Pick,$/, + // Presence: `isServerOwnedThreadLineage` and the SQL exclusions. + /^\): boolean => lineage\.engineIntake !== undefined;$/, + /^AND json_extract\((t|threads)\.payload_json, '\$\.lineage\.engineIntake'\) IS NULL`?$/, + // Carried from a command or a row into the lineage, or selected to be carried, unread. + /^\.\.\.\(command\.engineIntake === undefined \? \{\} : \{ engineIntake: command\.engineIntake \}\),$/, + /^\.\.\.\(row\.engine_intake == null \? \{\} : \{ engineIntake: row\.engine_intake \}\),$/, + /^\$\{indexedField\("\$\.lineage\.engineIntake"\)\} AS engine_intake,$/, + /^json_extract\(t\.payload_json, '\$\.lineage\.engineIntake'\) AS engine_intake,$/, + /^CASE WHEN json_valid\(payload_json\) THEN json_extract\(payload_json, '\$\.lineage\.engineIntake'\) END,$/, + // Taken off a client's create command, so only the server stamps it. + /^engineIntake: _engineIntake,$/, + // The engine intake stamping its own admission. + /^engineIntake: admissionId,$/, +]; + +it("only the engine intake reads the marker's value; every other reader asks whether it is set", () => { + 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)", + }, + ]); +}); + +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.deepEqual( + [...new Set(linesNaming(/board-task:/).map(({ file }) => file))], + ["apps/server/src/delivery/boardThreadMarker.ts"], + ); +}); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ee70086a04555..9ca90a5d8f18b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -300,6 +300,20 @@ export class OrchestratorSubagentThreadReadOnlyError extends Schema.TaggedError< } } +/** The one sentence every entry point gives for a send into an archived thread. */ +export const archivedThreadRefusal = (threadId: ThreadId) => + `Thread ${threadId} is archived and cannot receive messages.`; + +/** An archived thread receives nothing: no client, CLI or tool send starts or steers a turn in it. */ +export class OrchestratorThreadArchivedError extends Schema.TaggedError()( + "OrchestratorThreadArchivedError", + { commandId: CommandId, threadId: ThreadId }, +) { + override get message(): string { + return archivedThreadRefusal(this.threadId); + } +} + export class OrchestratorThreadAboveModeLimitError extends Schema.TaggedError()( "OrchestratorThreadAboveModeLimitError", { @@ -387,6 +401,7 @@ export const OrchestratorV2Error = Schema.Union([ OrchestratorCommandPreviouslyRejectedError, OrchestratorCommandIdConflictError, OrchestratorSubagentThreadReadOnlyError, + OrchestratorThreadArchivedError, OrchestratorThreadAboveModeLimitError, OrchestratorProviderSelectionBusyError, OrchestratorRuntimeModeAboveCeilingError, @@ -7114,6 +7129,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return thread; }); + /** + * An archived thread receives nothing a person, the CLI or a tool sends. The server's own + * follow-ups to a run (a steer follow-up, a usage-limit or restart continuation, a notification, + * an idle compaction) are not refused here: each settles quietly on an archived thread below. + */ + const refuseArchivedThreadMessage = Effect.fnUntraced(function* ( + command: Extract, + thread: Pick, + ) { + if ( + thread.archivedAt !== null && + command.steerFollowUpOfRunId === undefined && + command.usageLimitContinuationOfRunId === undefined && + command.restartContinuationOfRunId === undefined && + command.notification === undefined && + command.idleCompaction === undefined + ) { + return yield* new OrchestratorThreadArchivedError({ + commandId: command.commandId, + threadId: command.threadId, + }); + } + }); + const dispatchMessage = Effect.fn("Orchestrator.dispatchMessage")(function* ( command: Extract, events: Ref.Ref>, @@ -15842,6 +15881,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio break; case "message.dispatch": { const thread = yield* refuseNativeSubagentMessage(command); + yield* refuseArchivedThreadMessage(command, thread); const guestSend = command.guestMessageId === undefined ? undefined diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index f0d851fe29c63..a46773746f2a5 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -58,6 +58,7 @@ import { THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, THREAD_HISTORY_TURN_SNAPSHOT_ROW_LIMIT, } from "./threadHistoryPaging.ts"; +import { loadSubscriberShellSnapshot } from "./ShellStream.ts"; import { buildBoundedThreadStreamSnapshot } from "./ThreadStream.ts"; import { limitRecoveryCommand } from "./UsageLimitRecoveryWorker.ts"; @@ -3314,6 +3315,35 @@ it.effect("SQL list older settled threads below a cursor", () => .map((thread) => thread.id), [id("child"), id("engine-intake"), id("engine-intake-open")], ); + // What a client is sent: a subscriber that reads families gets no server-owned thread, open + // or settled. One that cannot read families still gets every row. + const sql = yield* SqlClient.SqlClient; + const serverOwnedSentTo = (omitIdleSubagents: boolean) => + loadSubscriberShellSnapshot({ + sql, + listShellIndex: store.listActiveShellIndex(), + readThreads: (threadIds) => + store.readShellSnapshot({ + location: "active", + ...(threadIds === undefined ? {} : { threadIds }), + }), + listProjects: Effect.succeed([]), + latestSequence: Effect.succeed(0), + options: { omitIdleSubagents, omitOlderSettled: false }, + }).pipe( + Effect.map(({ snapshot }) => ({ + sent: snapshot.threads + .map((thread) => thread.id) + .filter((threadId) => threadId.includes("engine-intake")), + counted: snapshot.serverOwnedThreads, + })), + ); + // Either way the snapshot counts them per project, so a client can say the project has them. + const counted = [{ projectId: ProjectId.make("project:a"), count: 2 }]; + assert.deepEqual(yield* serverOwnedSentTo(true), { sent: [], counted }); + const everyRow = yield* serverOwnedSentTo(false); + assert.sameMembers(everyRow.sent, [id("engine-intake"), id("engine-intake-open")]); + assert.deepEqual(everyRow.counted, counted); const list = ( before: { readonly settledAt: string; readonly threadId?: ThreadId }, diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index fbc610235dd01..e3f410a15536c 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -23,6 +23,8 @@ import { dedupeShellEnrichment, omitIdleSubagentShells, omitOlderSettledShells, + omitServerOwnedArchivedShells, + omitServerOwnedShells, shellStreamItemFromEnrichmentRefresh, shellStreamItemsFromInitialSnapshot, shouldPublishShellApplicationEvent, @@ -217,6 +219,78 @@ describe("omitIdleSubagentShells", () => { }); }); +describe("omitServerOwnedShells", () => { + const row = ( + id: string, + lineage: Partial = {}, + overrides: Partial = {}, + ) => + shellFixture({ + id: ThreadId.make(id), + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: ThreadId.make(id), + ...lineage, + }, + status: "completed", + activityRunStatus: null, + pendingRuntimeRequest: null, + pendingBackgroundTasks: [], + ...overrides, + }); + const boardTask = { engineIntake: "board-task:board-1:task-7" }; + const under = (parent: string) => ({ + parentThreadId: ThreadId.make(parent), + rootThreadId: ThreadId.make(parent), + }); + const threads = [ + row("listed"), + row("listed-seat", { ...under("listed"), relationshipToParent: "subagent" }), + row("task", boardTask), + // Running does not keep it: no list or badge reads a board task's row. + row("task-running", boardTask, { activityRunStatus: "running" }), + row("seat", { ...under("task-running"), relationshipToParent: "subagent" }), + row("task-side-chat", { ...under("task"), relationshipToParent: "fork", sideChat: true }), + ]; + + it("leaves out a board task's thread and the seats and side chats under it", () => { + expect(omitServerOwnedShells(threads).map((thread) => thread.id)).toEqual([ + "listed", + "listed-seat", + ]); + expect(activeShellRowsForSubscriber(threads, true).threads.map((thread) => thread.id)).toEqual([ + "listed", + ]); + // A subscriber that cannot read families has no other way to these rows. + expect(activeShellRowsForSubscriber(threads, false).threads).toEqual(threads); + }); + + it("keeps one that delegated a task to a linked environment, which nests under it there", () => { + const delegating = { ...row("task-remote", boardTask), hasRemoteTasks: true }; + expect(omitServerOwnedShells([...threads, delegating]).map((thread) => thread.id)).toEqual([ + "listed", + "listed-seat", + "task-remote", + ]); + }); + + it("returns the same rows when none is server-owned", () => { + const listed = threads.slice(0, 2); + expect(omitServerOwnedShells(listed)).toBe(listed); + expect(omitServerOwnedArchivedShells(listed)).toBe(listed); + }); + + it("leaves an archived board task's thread out of the archive snapshot", () => { + expect(omitServerOwnedArchivedShells(threads).map((thread) => thread.id)).toEqual([ + "listed", + "listed-seat", + "seat", + "task-side-chat", + ]); + }); +}); + describe("omitOlderSettledShells", () => { const DAY = 24 * 60 * 60 * 1000; const now = DateTime.makeUnsafe(100 * DAY); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 5ee1005b16830..a414adc11bf12 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -15,6 +15,7 @@ import { isListedThreadLineage, isLiveSubagentShell, isOlderSettledThreadShell, + isServerOwnedThreadLineage, OrchestrationProjectShell as ProjectShellSchema, OrchestrationV2ThreadShell as ThreadShellSchema, } from "@t3tools/contracts"; @@ -191,6 +192,9 @@ interface ShellTrimFacts { readonly subagentThreadIds: Set; /** Only the store's index knows these; shells alone leave it empty. */ readonly remoteTaskParentIds: ReadonlySet; + /** Threads carrying the server-owned marker: an engine intake or a board task's conversation. */ + readonly serverOwnedThreadIds: ReadonlySet; + readonly serverOwnedCounts: ReadonlyArray; /** Undefined when no thread is settled, so none is older. */ readonly olderSettledBeforeMs: number | undefined; readonly olderSettledCounts: ReadonlyArray; @@ -202,9 +206,15 @@ function shellTrimFacts(rows: ReadonlyArray): ShellTrimFacts { const subagentParentIds = new Set(); const subagentThreadIds = new Set(); const remoteTaskParentIds = new Set(); + const serverOwnedThreadIds = new Set(); + const serverOwned = new Map(); const settledTimes: Array = []; for (const row of rows) { if (row.hasRemoteTasks === true) remoteTaskParentIds.add(row.id); + if (isServerOwnedThreadLineage(row.lineage)) { + serverOwnedThreadIds.add(row.id); + serverOwned.set(row.projectId, (serverOwned.get(row.projectId) ?? 0) + 1); + } if (row.lineage.relationshipToParent === "subagent") { subagentThreadIds.add(row.id); if (row.lineage.parentThreadId) subagentParentIds.add(row.lineage.parentThreadId); @@ -231,6 +241,8 @@ function shellTrimFacts(rows: ReadonlyArray): ShellTrimFacts { subagentParentIds, subagentThreadIds, remoteTaskParentIds, + serverOwnedThreadIds, + serverOwnedCounts: Array.from(serverOwned, ([projectId, count]) => ({ projectId, count })), olderSettledBeforeMs, olderSettledCounts: Array.from(counts, ([projectId, count]) => ({ projectId, count })), }; @@ -248,6 +260,52 @@ function hiddenChildAncestorIds( return ancestorIds; } +/** + * Whether a row belongs to work the server started for itself: a thread carrying the marker, or a + * subagent or side chat rooted at one. No list shows any of them, so a subscriber that reads + * families gets the whole family on demand when its thread is opened by id. The parent of a task + * in a linked environment stays, like in the other trims, so that task still nests under it. + */ +function isOmittedServerOwnedRow( + row: Pick, + facts: Pick, +): boolean { + return ( + (facts.serverOwnedThreadIds.has(row.id) || + facts.serverOwnedThreadIds.has(row.lineage.rootThreadId)) && + !facts.remoteTaskParentIds.has(row.id) + ); +} + +function omitServerOwnedShellsWith>( + rows: ReadonlyArray, + facts: Pick, +): ReadonlyArray { + return facts.serverOwnedThreadIds.size === 0 + ? rows + : rows.filter((row) => !isOmittedServerOwnedRow(row, facts)); +} + +/** + * Server-owned work has no row in any list, so a subscriber that reads thread families does not + * get it in the shell: a board with twenty tasks would otherwise add twenty rows every client only + * hides. Changes to such a thread still arrive as deltas, which keep an open one current. + */ +export function omitServerOwnedShells( + threads: ReadonlyArray, +): ReadonlyArray { + return omitServerOwnedShellsWith(threads, shellTrimFacts(threads)); +} + +/** The archive lists no server-owned thread, so its snapshot does not carry one. */ +export function omitServerOwnedArchivedShells< + Row extends Pick, +>(threads: ReadonlyArray): ReadonlyArray { + return threads.some((thread) => isServerOwnedThreadLineage(thread.lineage)) + ? threads.filter((thread) => !isServerOwnedThreadLineage(thread.lineage)) + : threads; +} + function omitIdleSubagentShellsWith( threads: ReadonlyArray, facts: Pick, @@ -322,7 +380,9 @@ export function activeShellRowsForSubscriber( } { const facts = shellTrimFacts(threads); return { - threads: omitIdleSubagents ? omitIdleSubagentShellsWith(threads, facts) : threads, + threads: omitIdleSubagents + ? omitIdleSubagentShellsWith(omitServerOwnedShellsWith(threads, facts), facts) + : threads, subagentThreadIds: facts.subagentThreadIds, }; } @@ -354,15 +414,21 @@ function trimShellSnapshot( facts: ShellTrimFacts, options: ShellSubscriberOptions & { readonly now: DateTime.Utc }, ): OrchestrationV2ShellSnapshot { + // Both trims rest on the same opt-in: the subscriber reads what the shell leaves out by family. const threads = options.omitIdleSubagents - ? omitIdleSubagentShellsWith(base.threads, facts) + ? omitIdleSubagentShellsWith(omitServerOwnedShellsWith(base.threads, facts), facts) : base.threads; - if (!options.omitOlderSettled) return { ...base, threads }; + // Counted for every subscriber: an older client drops the key, a newer one need not hold rows. + const counted = + facts.serverOwnedCounts.length === 0 + ? { ...base, threads } + : { ...base, threads, serverOwnedThreads: facts.serverOwnedCounts }; + if (!options.omitOlderSettled) return counted; const older = omitOlderSettledShellsWith( { threads, snapshotSequence: base.snapshotSequence, now: options.now }, facts, ); - return { ...base, threads: older.threads, olderSettled: older.olderSettled }; + return { ...counted, threads: older.threads, olderSettled: older.olderSettled }; } /** @@ -370,10 +436,13 @@ function trimShellSnapshot( * trimming the shells read for these ids gives the snapshot trimming every shell would. */ function shellSubscriberThreadIds( - index: ReadonlyArray, + everyEntry: ReadonlyArray, options: ShellSubscriberOptions, ): ReadonlyArray { - const facts = shellTrimFacts(index); + const facts = shellTrimFacts(everyEntry); + const index = options.omitIdleSubagents + ? omitServerOwnedShellsWith(everyEntry, facts) + : everyEntry; const subagents = index.filter( (entry) => entry.lineage.relationshipToParent === "subagent" && diff --git a/apps/server/src/orchestration-v2/ThreadDeletion.ts b/apps/server/src/orchestration-v2/ThreadDeletion.ts index 265f59008d87f..ec7ab1d3a634f 100644 --- a/apps/server/src/orchestration-v2/ThreadDeletion.ts +++ b/apps/server/src/orchestration-v2/ThreadDeletion.ts @@ -14,8 +14,16 @@ export interface ThreadDeletionPlan { readonly effects: ReadonlyArray; } +/** + * Ends a thread's work and removes it. With `keep: "archived"` the thread is archived instead: its + * runs, requests and sessions end the same way, and the conversation and its attachments stay. + */ export const planThreadDeletion = Effect.fn("ThreadDeletion.planThreadDeletion")(function* (input: { - readonly command: Extract; + readonly command: Pick< + Extract, + "commandId" | "threadId" + >; + readonly keep?: "archived"; readonly projection: Pick< OrchestrationV2ThreadProjection, "thread" | "runs" | "attempts" | "nodes" | "runtimeRequests" | "subagents" | "providerSessions" @@ -25,6 +33,8 @@ export const planThreadDeletion = Effect.fn("ThreadDeletion.planThreadDeletion") readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; }): Effect.fn.Return { const { command, projection, now, idAllocator } = input; + const ended = input.keep === "archived" ? "The thread was archived." : "The thread was deleted."; + const detached = input.keep === "archived" ? "Thread archived." : "Thread deleted."; const events: Array = []; const effects: Array = []; let current = projection; @@ -53,18 +63,39 @@ export const planThreadDeletion = Effect.fn("ThreadDeletion.planThreadDeletion") } }); - yield* emitEvent({ - type: "thread.deleted", - threadId: command.threadId, - providerInstanceId: projection.thread.providerInstanceId, - occurredAt: now, - payload: { - ...projection.thread, - deletedAt: projection.thread.deletedAt ?? now, - titleRegeneration: null, - updatedAt: now, - }, - }); + yield* emitEvent( + input.keep === "archived" + ? { + type: "thread.archived", + threadId: command.threadId, + providerInstanceId: projection.thread.providerInstanceId, + occurredAt: now, + // The fields an archive through the orchestrator sets: the share and the watches end. + payload: { + ...projection.thread, + archivedAt: projection.thread.archivedAt ?? now, + titleRegeneration: null, + guestShare: null, + pullRequests: projection.thread.pullRequests?.map(({ watch, endedWatch, ...link }) => { + const ended = watch ?? endedWatch; + return ended === undefined ? link : { ...link, endedWatch: ended }; + }), + updatedAt: now, + }, + } + : { + type: "thread.deleted", + threadId: command.threadId, + providerInstanceId: projection.thread.providerInstanceId, + occurredAt: now, + payload: { + ...projection.thread, + deletedAt: projection.thread.deletedAt ?? now, + titleRegeneration: null, + updatedAt: now, + }, + }, + ); const activeRuns = projection.runs.filter((run) => ["preparing", "queued", "starting", "running", "waiting"].includes(run.status), @@ -121,7 +152,7 @@ export const planThreadDeletion = Effect.fn("ThreadDeletion.planThreadDeletion") payload: { ...request, status: "cancelled", - responseCapability: { type: "not_resumable", reason: "The thread was deleted." }, + responseCapability: { type: "not_resumable", reason: ended }, resolvedAt: now, }, }); @@ -194,7 +225,7 @@ export const planThreadDeletion = Effect.fn("ThreadDeletion.planThreadDeletion") payload: { providerSessionId: session.id, detachedAt: now, - reason: "Thread deleted.", + reason: detached, }, }); effects.push({ @@ -204,7 +235,7 @@ export const planThreadDeletion = Effect.fn("ThreadDeletion.planThreadDeletion") request: { type: "provider-session.detach", providerSessionId: session.id, - detail: "Thread deleted.", + detail: detached, revokeMcpCredential: true, }, }); @@ -227,7 +258,8 @@ export const planThreadDeletion = Effect.fn("ThreadDeletion.planThreadDeletion") threadId: command.threadId, request: { type: "preview.cleanup" }, }); - const attachmentIds = Array.from(new Set(input.attachmentIds)); + // An archived thread keeps its conversation, so its files stay with it. + const attachmentIds = input.keep === "archived" ? [] : Array.from(new Set(input.attachmentIds)); if (attachmentIds.length > 0) { effects.push({ id: `effect:${command.commandId}:attachment.cleanup`, diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 5d64f0d134447..2209f4baf4353 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -580,6 +580,69 @@ it.effect("keeps a board task's thread out of both lists, however often it is cr }).pipe(Effect.provide(harness.layer)); }); +it.effect("an archived thread receives no message, a board task's or any other", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const threads = yield* ThreadManagement.ThreadManagementService; + const create = (name: string, engineIntake?: string) => + threads.dispatch({ + type: "thread.create", + commandId: CommandId.make(`command:create:${name}`), + threadId: ThreadId.make(`thread:${name}`), + projectId, + title: name, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "system", + creationSource: "server", + ...(engineIntake === undefined ? {} : { engineIntake }), + }); + // The command the web composer sends. + const send = (name: string) => + threads.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`command:send:${name}`), + threadId: ThreadId.make(`thread:${name}`), + messageId: MessageId.make(`message:${name}`), + createdBy: "user", + creationSource: "web", + text: "Still there?", + attachments: [], + dispatchMode: { type: "start_immediately" }, + }); + const received = (name: string) => + threads + .getProjectThreadRecords({ projectId, threadId: ThreadId.make(`thread:${name}`) }, [ + "runs", + "messages", + ]) + .pipe(Effect.map((records) => [records.runs.length, records.messages.length])); + const marker = boardTaskThreadMarker({ board: "board-1", id: "task-9" }); + yield* create("archived-board", marker); + yield* create("archived-ordinary"); + yield* create("live-board", boardTaskThreadMarker({ board: "board-1", id: "task-10" })); + for (const name of ["archived-board", "archived-ordinary"]) { + yield* threads.dispatch({ + type: "thread.archive", + commandId: CommandId.make(`command:archive:${name}`), + threadId: ThreadId.make(`thread:${name}`), + }); + const refused = yield* Effect.flip(send(name)); + assert.equal(refused._tag, "OrchestratorThreadArchivedError"); + assert.equal( + refused.message, + `Thread thread:${name} is archived and cannot receive messages.`, + ); + assert.deepEqual(yield* received(name), [0, 0]); + } + yield* send("live-board"); + assert.deepEqual(yield* received("live-board"), [1, 1]); + }).pipe(Effect.provide(harness.layer)); +}); + it.effect("runs a thread-bound automation on the provider the thread uses now", () => { const harness = makeHarness({ adapters: [adapter, claudeAdapter] }); const layerScheduledTasks = ScheduledTasks.layer.pipe( diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index a0b5625af0d2a..f9782d7ccce83 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -1015,6 +1015,46 @@ it.effect.each([ }), ); +it.effect("lists no seat or side chat rooted at server-owned work, with or without subagents", () => + Effect.gen(function* () { + const projectId = ProjectId.make("project:thread-management:family"); + const row = (id: string, root: string, lineage: object = {}) => ({ + id: ThreadId.make(id), + projectId, + updatedAt: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"), + lineage: { + parentThreadId: id === root ? null : ThreadId.make(root), + rootThreadId: ThreadId.make(root), + ...lineage, + }, + }); + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + listActiveThreads: () => + Effect.succeed([ + row("ordinary", "ordinary"), + row("ordinary-seat", "ordinary", { relationshipToParent: "subagent" }), + row("board", "board", { engineIntake: "board-task:board-1:task-7" }), + row("board-seat", "board", { relationshipToParent: "subagent" }), + ] as never), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerReceiptsTest), + ); + const list = (includeSubagents: boolean) => + Effect.gen(function* () { + const service = yield* ThreadManagementService.ThreadManagementService; + const listed = yield* service.listProjectThreads({ projectId, includeSubagents }); + return listed.map((thread) => thread.id).toSorted(); + }).pipe(Effect.provide(layerTest)); + expect(yield* list(true)).toEqual(["ordinary", "ordinary-seat"]); + expect(yield* list(false)).toEqual(["ordinary"]); + }), +); + it.effect("Force stop refuses once a newer run has started, before killing anything", () => Effect.gen(function* () { const threadId = ThreadId.make("thread:thread-management:force-stop-superseded"); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index b12dd3fd87857..af9ed901c7da3 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -268,7 +268,7 @@ export class ThreadManagementThreadArchivedError extends Schema.TaggedError - threads + Effect.map((threads) => { + // The shell's family rule: server-owned work is listed nowhere, and neither is a seat or + // side chat rooted at it. + const serverOwnedIds = new Set( + threads + .filter((thread) => isServerOwnedThreadLineage(thread.lineage)) + .map((thread) => thread.id), + ); + return threads .filter((thread) => input.includeSubagents - ? thread.lineage.sideChat !== true && !isServerOwnedThreadLineage(thread.lineage) + ? thread.lineage.sideChat !== true && + !serverOwnedIds.has(thread.id) && + !serverOwnedIds.has(thread.lineage.rootThreadId) : isListedThreadLineage(thread.lineage) && !isDelegatedAppThread(thread), ) .toSorted( (left, right) => DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) || right.id.localeCompare(left.id), - ), - ), + ); + }), ); const sendToThread: ThreadManagementServiceShape["sendToThread"] = Effect.fn( diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts index 5d9ec263b0b0d..ae47dac361327 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts @@ -30,6 +30,7 @@ function dispatchWasNotAccepted( case "OrchestratorCommandPreviouslyRejectedError": case "OrchestratorCommandIdConflictError": case "OrchestratorSubagentThreadReadOnlyError": + case "OrchestratorThreadArchivedError": case "OrchestratorThreadAboveModeLimitError": case "OrchestratorProviderSelectionBusyError": case "OrchestratorRuntimeModeAboveCeilingError": diff --git a/apps/server/src/project/ProjectService.deletion.test.ts b/apps/server/src/project/ProjectService.deletion.test.ts index 25e5ee54a2737..47e799d0b3e40 100644 --- a/apps/server/src/project/ProjectService.deletion.test.ts +++ b/apps/server/src/project/ProjectService.deletion.test.ts @@ -89,7 +89,11 @@ const seedProject = Effect.fn("ProjectDeletionTest.seedProject")(function* (proj `; }); -function nativeThreadCreated(projectId: ProjectId, threadId: ThreadId) { +function nativeThreadCreated( + projectId: ProjectId, + threadId: ThreadId, + overrides: Partial> = {}, +) { const createdAt = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z"); const providerInstanceId = ProviderInstanceId.make("codex"); const payload: OrchestrationV2AppThread = { @@ -114,6 +118,7 @@ function nativeThreadCreated(projectId: ProjectId, threadId: ThreadId) { settledAt: null, lastVisitedAt: null, deletedAt: null, + ...overrides, }; return { id: EventId.make(`created:${threadId}`), @@ -427,6 +432,97 @@ it.effect("rejects a child deletion command ID already accepted for an unrelated }).pipe(Effect.provide(layerDatabase)), ); +it.effect( + "archives a removed project's board task threads and their seats, and deletes the rest", + () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const projectId = ProjectId.make("project:board-threads"); + const id = (name: string) => ThreadId.make(`thread:board:${name}`); + const boardTask = (name: string) => ({ + parentThreadId: null, + relationshipToParent: null, + rootThreadId: id(name), + engineIntake: `board-task:board-1:${name}`, + }); + yield* seedProject(projectId); + yield* TestClock.setTime(Date.parse("2026-09-04T12:00:00.000Z")); + const archivedBefore = DateTime.makeUnsafe("2026-02-01T00:00:00.000Z"); + + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + yield* eventSink.write({ + events: [ + nativeThreadCreated(projectId, id("listed")), + nativeThreadCreated(projectId, id("task"), { lineage: boardTask("task") }), + nativeThreadCreated(projectId, id("seat"), { + lineage: { + parentThreadId: id("task"), + relationshipToParent: "subagent", + rootThreadId: id("task"), + }, + }), + nativeThreadCreated(projectId, id("done"), { + lineage: boardTask("done"), + archivedAt: archivedBefore, + }), + ], + }); + const service = yield* ProjectService.make; + // Board threads are affected too, so a removal that was not confirmed is still refused. + const unconfirmed = yield* service + .delete({ commandId: CommandId.make("command:board:unconfirmed"), projectId }) + .pipe(Effect.flip); + assert.equal(unconfirmed._tag, "ProjectNotEmptyError"); + + const input = { commandId: CommandId.make("command:board:delete"), projectId, force: true }; + const removed = yield* service.delete(input); + assert.isNotNull(removed.deletedAt); + const threadOf = (name: string) => + projections.getThreadProjection(id(name)).pipe(Effect.map(({ thread }) => thread)); + assert.isNotNull((yield* threadOf("listed")).deletedAt); + const removedAt = yield* DateTime.now; + for (const name of ["task", "seat"]) { + const kept = yield* threadOf(name); + assert.isNull(kept.deletedAt, name); + assert.deepEqual(kept.archivedAt, removedAt, name); + } + // Already archived: left exactly as it was. + const done = yield* threadOf("done"); + assert.isNull(done.deletedAt); + assert.deepEqual(done.archivedAt, archivedBefore); + + const threadEvents = sql<{ readonly stream_id: string; readonly event_type: string }>` + SELECT stream_id, event_type FROM orchestration_events + WHERE event_type IN ('thread.deleted', 'thread.archived') + ORDER BY stream_id ASC + `; + const events = yield* threadEvents; + assert.deepEqual( + events.map((event) => [event.stream_id, event.event_type]), + [ + [id("listed"), "thread.deleted"], + [id("seat"), "thread.archived"], + [id("task"), "thread.archived"], + ], + ); + // An archived thread keeps its files; only the deleted one has them cleaned up. + const cleanups = yield* sql<{ readonly thread_id: string; readonly effect_type: string }>` + SELECT thread_id, effect_type FROM orchestration_v2_effect_outbox + WHERE effect_type = 'terminal.cleanup' ORDER BY thread_id ASC + `; + assert.deepEqual( + cleanups.map((cleanup) => cleanup.thread_id), + [id("listed"), id("seat"), id("task")], + ); + // A retried removal repeats nothing. + assert.deepEqual(yield* service.delete(input), removed); + assert.deepEqual(yield* threadEvents, events); + }).pipe(Effect.provide(layerServices)); + }).pipe(Effect.provide(layerDatabase)), +); + it.effect("deletes a project without force once its imported threads were deleted in V2", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index 80fabe6101c05..34471740e47ef 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -1,6 +1,8 @@ import { CommandId, + isServerOwnedThreadLineage, type OrchestrationProjectShell, + type OrchestrationV2ThreadShell, PROJECT_TRACKED_FOLDERS_MAX, ProjectId, type Project, @@ -655,9 +657,11 @@ export const make = Effect.gen(function* () { }, ); + // `keep: "archived"` ends the thread's work and archives it; see `deleteChildThreads`. const deleteChildThread = Effect.fn("ProjectService.deleteChildThread")(function* ( input: ProjectDeleteInput, threadId: ThreadId, + keep?: "archived", ) { yield* legacyImporter.ensureTranscript(threadId); const projection = yield* threadProjections.getThreadRecords(threadId, [ @@ -671,16 +675,26 @@ export const make = Effect.gen(function* () { if (projection.thread.deletedAt !== null || projection.thread.projectId !== input.projectId) { return; } - const command = { - type: "thread.delete" as const, - commandId: CommandId.make(`${input.commandId}:delete-thread:${threadId}`), - threadId, - }; + if (keep === "archived" && projection.thread.archivedAt !== null) return; + const command = + keep === "archived" + ? { + type: "thread.archive" as const, + commandId: CommandId.make(`${input.commandId}:archive-thread:${threadId}`), + threadId, + } + : { + type: "thread.delete" as const, + commandId: CommandId.make(`${input.commandId}:delete-thread:${threadId}`), + threadId, + }; const now = yield* DateTime.now; const plan = yield* planThreadDeletion({ command, + ...(keep === undefined ? {} : { keep }), projection, - attachmentIds: yield* threadProjections.getThreadAttachmentIds(threadId), + attachmentIds: + keep === "archived" ? [] : yield* threadProjections.getThreadAttachmentIds(threadId), now, idAllocator, }); @@ -705,6 +719,24 @@ export const make = Effect.gen(function* () { } }); + /** + * The project's threads the server started for itself, a board task's conversation among them, + * with the seats and side chats under them. No list shows these, so removing the project must + * not delete them out of sight: their work ends and they are archived. + */ + const serverOwnedFamilyIds = ( + threads: ReadonlyArray>, + ) => { + const owned = new Set( + threads.filter((thread) => isServerOwnedThreadLineage(thread.lineage)).map(({ id }) => id), + ); + return new Set( + threads + .filter((thread) => owned.has(thread.id) || owned.has(thread.lineage.rootThreadId)) + .map(({ id }) => id), + ); + }; + const deleteChildThreads = Effect.fn("ProjectService.deleteChildThreads")(function* ( input: ProjectDeleteInput, ) { @@ -723,12 +755,18 @@ export const make = Effect.gen(function* () { if (projectThreads.length > 0 && input.force !== true) { return yield* new ProjectNotEmptyError({ projectId }); } + const kept = serverOwnedFamilyIds(projectThreads); // Delete children durably before the project so a failed cascade can be retried. yield* Effect.forEach( projectThreads, (thread) => threadCommands - .withDeletionLock(threadCommands.withLock(thread.id, deleteChildThread(input, thread.id))) + .withDeletionLock( + threadCommands.withLock( + thread.id, + deleteChildThread(input, thread.id, kept.has(thread.id) ? "archived" : undefined), + ), + ) .pipe( Effect.mapError( (cause) => diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index d8aa09f63de85..a391562d28359 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -145,6 +145,7 @@ import { shellStreamItemFromThreadShell, shellStreamItemsFromInitialSnapshot, loadSubscriberShellSnapshot, + omitServerOwnedArchivedShells, canResumeShellFrom, resumeIdentityRoots, shellStreamItemsFromResumeSnapshot, @@ -1952,7 +1953,7 @@ export const layerWsRpc = ( schemaVersion: threads.schemaVersion, snapshotSequence, projects, - threads: threads.archivedThreads, + threads: omitServerOwnedArchivedShells(threads.archivedThreads), } as const; }).pipe( Effect.flatMap((snapshot) => diff --git a/apps/web/src/components/ChatView.archivedSend.browser.test.tsx b/apps/web/src/components/ChatView.archivedSend.browser.test.tsx new file mode 100644 index 0000000000000..cf676bb87b51a --- /dev/null +++ b/apps/web/src/components/ChatView.archivedSend.browser.test.tsx @@ -0,0 +1,90 @@ +import { createMemoryHistory } from "@tanstack/react-router"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; +import type * as Context from "effect/Context"; +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { AppRoot } from "~/AppRoot"; +// The route loads ChatView lazily; importing it here keeps its first transform out of the test. +import "~/components/ChatView"; +import { __setClientSettingsForTests } from "~/hooks/useSettings"; +import { getRouter } from "~/router"; +import { + ENVIRONMENT_ID, + dispatchedCommands, + installFakeEnvironment, + threadWithHistory, + type FakeDriver, + type FakeThread, +} from "../../test/fakeEnvironment"; +import { render } from "../../test/render"; + +// The socket is the only fake layer; see test/appScenarios.renders.tsx. +vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => { + const [actual, { fakeDriver }, Layer] = await Promise.all([ + importOriginal<{ readonly ConnectionDriver: Context.Key }>(), + import("../../test/fakeEnvironment"), + import("effect/Layer"), + ]); + return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; +}); + +vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ + ...(await original()), + trackRpcRequestSent: () => {}, +})); + +const REFUSAL = "This thread is archived and cannot receive messages."; +const sends = () => dispatchedCommands().filter((command) => command.type === "message.dispatch"); + +async function openAndType(thread: FakeThread) { + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + // AppRoot brings its own router. + const app = await render(, { router: false }); + await expect.element(page.getByText(`${thread.id}: question 0`)).toBeVisible(); + const editor = page.getByTestId("composer-editor"); + await userEvent.click(editor); + await userEvent.keyboard("still there?"); + await vi.waitFor(() => expect(editor.element().textContent).toContain("still there?")); + return app; +} + +// An archived board task's thread is the archived thread a person can reach: it opens by id. +it("an archived board thread says it takes no message, and sends none", async () => { + const thread: FakeThread = { + ...threadWithHistory("archived-board", 1), + engineIntake: "board-task:probe", + archived: true, + }; + using _environment = installFakeEnvironment([thread], { acceptCommands: true }); + await using _app = await openAndType(thread); + + await expect.element(page.getByText(REFUSAL)).toBeVisible(); + await expect.element(page.getByRole("button", { name: REFUSAL })).toBeDisabled(); + await userEvent.keyboard("{Enter}"); + // The refusal is still on screen and the words are still in the composer. + await expect.element(page.getByText(REFUSAL)).toBeVisible(); + expect(page.getByTestId("composer-editor").element().textContent).toContain("still there?"); + expect(sends()).toEqual([]); +}); + +it("a live board thread still sends", async () => { + const thread: FakeThread = { + ...threadWithHistory("live-board", 1), + engineIntake: "board-task:probe", + offShell: true, + }; + using _environment = installFakeEnvironment([thread], { acceptCommands: true }); + await using _app = await openAndType(thread); + + expect(page.getByText(REFUSAL).query()).toBeNull(); + await userEvent.keyboard("{Enter}"); + await vi.waitFor(() => expect(sends()).toHaveLength(1)); +}); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index dee580aac7748..8b1fe2f99dbc2 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -84,6 +84,10 @@ import { resolveWorktreeRepositorySelection } from "@t3tools/client-runtime/stat import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import type { UsageLimitSourceSnapshots } from "@t3tools/contracts"; import { feedbackBannerItem } from "./chat/ComposerFeedback"; +import { + archivedThreadBannerItem, + archivedThreadSendBlockReason, +} from "./chat/ComposerArchivedThread"; import { freshSessionBannerItem } from "./chat/ComposerFreshSession"; import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./chat/freshSessionArms"; import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel"; @@ -2891,7 +2895,11 @@ export default function ChatView(props: ChatViewProps) { : null, messages, ); + // An archived thread opens to read. The server refuses every message to it, so the composer says + // so before one is written, not after a send that goes nowhere. + const threadArchived = serverThread !== null && serverThread.archivedAt !== null; const composerBannerItems = (() => { + const archivedItems = threadArchived ? [archivedThreadBannerItem(messages)] : []; const fallbackSelection = draftFallback?.selection; const defaultSelection = draftDefaultModelSelection ?? @@ -2954,6 +2962,7 @@ export default function ChatView(props: ChatViewProps) { : []; if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) { return [ + ...archivedItems, ...feedbackBannerItems, ...fallbackItems, ...limitRecoveryItems, @@ -2966,6 +2975,7 @@ export default function ChatView(props: ChatViewProps) { ]; } return [ + ...archivedItems, ...feedbackBannerItems, ...fallbackItems, ...limitRecoveryItems, @@ -4087,17 +4097,19 @@ export default function ChatView(props: ChatViewProps) { sendDisabledReason={ !canOperateThread ? gt("This connection cannot change threads.") - : isEnvironmentChanging - ? gt("Preparing machine") - : isRevertingCheckpoint - ? gt("Rewinding conversation") - : feedbackUploading - ? gt("Sending feedback") - : threadDetailLoading - ? gt("Messages loading") - : worktreeSetupBlocksSend - ? gt("Preparing worktree") - : projectCloneSendBlockReason + : threadArchived + ? archivedThreadSendBlockReason(messages) + : isEnvironmentChanging + ? gt("Preparing machine") + : isRevertingCheckpoint + ? gt("Rewinding conversation") + : feedbackUploading + ? gt("Sending feedback") + : threadDetailLoading + ? gt("Messages loading") + : worktreeSetupBlocksSend + ? gt("Preparing worktree") + : projectCloneSendBlockReason } isPreparingWorktree={isPreparingWorktree && !sendQueuesBehindSetup} bannerItems={ diff --git a/apps/web/src/components/ThreadRouteView.browser.test.tsx b/apps/web/src/components/ThreadRouteView.browser.test.tsx index 008f187a6605a..99e037e817c7a 100644 --- a/apps/web/src/components/ThreadRouteView.browser.test.tsx +++ b/apps/web/src/components/ThreadRouteView.browser.test.tsx @@ -9,8 +9,11 @@ import { AppRoot } from "~/AppRoot"; import "~/components/ChatView"; import { __setClientSettingsForTests } from "~/hooks/useSettings"; import { getRouter } from "~/router"; +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { environmentThreadShells } from "~/state/threads"; import { ENVIRONMENT_ID, + emitShellThread, installFakeEnvironment, threadWithHistory, type FakeDriver, @@ -33,46 +36,90 @@ vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ trackRpcRequestSent: () => {}, })); -it.each([ - { name: "the shell carries it", offShell: false }, - { name: "the shell leaves it out", offShell: true }, -])("opens a thread no list shows by id, from a link and after a reload, when $name", async (c) => { - const listed = threadWithHistory("probe-listed", 1); - const unlisted: FakeThread = { - ...threadWithHistory("probe-unlisted", 1), - engineIntake: "board-task:probe", - ...(c.offShell ? { offShell: true as const } : {}), - }; - using _environment = installFakeEnvironment([listed, unlisted]); - __setClientSettingsForTests({ - ...DEFAULT_CLIENT_SETTINGS, - onboardingCompletedAt: "2026-01-01T00:00:00.000Z", - }); - const open = async (path: string) => { - const router = getRouter(createMemoryHistory({ initialEntries: [path] })); - await router.load(); - return router; - }; - const params = { environmentId: ENVIRONMENT_ID, threadId: unlisted.id }; - const sidebarRows = () => - Array.from(document.querySelectorAll("[data-thread-item]"), (row) => - row.getAttribute("data-thread-item"), +// A server that serves families sends no board task's row in its snapshot. A change to the thread +// still brings its row in as a delta. An archived one is in no shell and no family. +const SHELL_ROWS = [ + { shell: "got its row as a delta", fixture: { offShell: true }, delta: true }, + { shell: "leaves its row out", fixture: { offShell: true }, delta: false }, + { shell: "has archived it", fixture: { archived: true }, delta: false }, +] as const; +const HIDDEN_TAGS = ["private"]; +// The server's settings arrive after the first paint, so the filter takes a moment to apply. +const SETTLED = { timeout: 10_000 }; + +it.each( + SHELL_ROWS.flatMap((row) => [ + { ...row, filter: "off", tagFilter: false, tag: "no tag", tags: [] }, + { ...row, filter: "on", tagFilter: true, tag: "no tag", tags: [] }, + // The filter hides rows of lists. A board task's thread is in none, so its tag closes nothing. + { ...row, filter: "on", tagFilter: true, tag: "a hidden tag", tags: HIDDEN_TAGS }, + // Each case has its own thread: a detail cached by an earlier case would open a thread the + // route is about to close. + ]).map((row, index) => ({ ...row, name: `probe-unlisted-${index}` })), +)( + "opens a board task's thread by id, from a link and after a reload, when the shell $shell, the tag filter is $filter and it carries $tag", + async (c) => { + const listed = threadWithHistory("probe-listed", 1); + // A listed thread the filter hides: its row leaving the sidebar says the filter is in force. + const tagged: FakeThread = { ...threadWithHistory("probe-tagged", 1), tags: HIDDEN_TAGS }; + const unlisted: FakeThread = { + ...threadWithHistory(c.name, 1), + engineIntake: "board-task:probe", + tags: c.tags, + ...c.fixture, + }; + using _environment = installFakeEnvironment( + [listed, tagged, unlisted], + c.tagFilter ? { hiddenThreadTags: HIDDEN_TAGS } : undefined, ); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const open = async (path: string) => { + const router = getRouter(createMemoryHistory({ initialEntries: [path] })); + await router.load(); + return router; + }; + const params = { environmentId: ENVIRONMENT_ID, threadId: unlisted.id }; + const path = `/${ENVIRONMENT_ID}/${unlisted.id}`; + // Which fixtures have a sidebar row. The board task's thread never does. + const sidebarRows = () => { + const rows = Array.from(document.querySelectorAll("[data-thread-item]"), (row) => + row.getAttribute("data-thread-item"), + ); + return [listed, tagged, unlisted] + .filter((thread) => rows.some((row) => row?.includes(thread.id))) + .map((thread) => thread.id); + }; + const shellRow = () => + appAtomRegistry.get(environmentThreadShells.quietThreadShellAtom(params)) !== null; + const listedRows = c.tagFilter ? [listed.id] : [listed.id, tagged.id]; - { - const router = await open(`/${ENVIRONMENT_ID}/${listed.id}`); + { + const router = await open(`/${ENVIRONMENT_ID}/${listed.id}`); + // AppRoot brings its own router. + await using _app = await render(, { router: false }); + await expect.element(page.getByText("probe-listed: question 0")).toBeVisible(); + await expect.poll(sidebarRows, SETTLED).toEqual(listedRows); + if (c.delta) { + await emitShellThread(unlisted.id); + await expect.poll(shellRow).toBe(true); + } + await act(() => router.navigate({ to: "/$environmentId/$threadId", params })); + await expect.element(page.getByText(`${c.name}: question 0`)).toBeVisible(); + expect(router.state.location.pathname).toBe(path); + } + // A reload or a pasted link starts a new router on the thread's own address. + const router = await open(path); // AppRoot brings its own router. await using _app = await render(, { router: false }); - await expect.element(page.getByText("probe-listed: question 0")).toBeVisible(); - await expect.poll(sidebarRows).toEqual([expect.stringContaining(listed.id)]); - await act(() => router.navigate({ to: "/$environmentId/$threadId", params })); - await expect.element(page.getByText("probe-unlisted: question 0")).toBeVisible(); - } - // A reload or a pasted link starts a new router on the thread's own address. - const router = await open(`/${ENVIRONMENT_ID}/${unlisted.id}`); - // AppRoot brings its own router. - await using _app = await render(, { router: false }); - await expect.element(page.getByText("probe-unlisted: question 0")).toBeVisible(); - expect(router.state.location.pathname).toBe(`/${ENVIRONMENT_ID}/${unlisted.id}`); - await expect.poll(sidebarRows).toEqual([expect.stringContaining(listed.id)]); -}); + // The sidebar first, so the open is judged with the shell and the filter loaded. + await expect.poll(sidebarRows, SETTLED).toEqual(listedRows); + await expect.element(page.getByText(`${c.name}: question 0`)).toBeVisible(); + expect(router.state.location.pathname).toBe(path); + // The open thread reads its row from the shell, or from its family when the shell left it out. + await expect.poll(shellRow, SETTLED).toBe(!("archived" in c.fixture)); + expect(sidebarRows()).toEqual(listedRows); + }, +); diff --git a/apps/web/src/components/ThreadRouteView.tagFilter.browser.test.tsx b/apps/web/src/components/ThreadRouteView.tagFilter.browser.test.tsx new file mode 100644 index 0000000000000..7c6a681d54788 --- /dev/null +++ b/apps/web/src/components/ThreadRouteView.tagFilter.browser.test.tsx @@ -0,0 +1,93 @@ +import { createMemoryHistory } from "@tanstack/react-router"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; +import type * as Context from "effect/Context"; +import { expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +import { AppRoot } from "~/AppRoot"; +// The route loads ChatView lazily; importing it here keeps its first transform out of the test. +import "~/components/ChatView"; +import { __setClientSettingsForTests } from "~/hooks/useSettings"; +import { getRouter } from "~/router"; +import { + ENVIRONMENT_ID, + installFakeEnvironment, + threadWithHistory, + type FakeDriver, + type FakeThread, +} from "../../test/fakeEnvironment"; +import { act, render } from "../../test/render"; + +// The socket is the only fake layer; see test/appScenarios.renders.tsx. +vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => { + const [actual, { fakeDriver }, Layer] = await Promise.all([ + importOriginal<{ readonly ConnectionDriver: Context.Key }>(), + import("../../test/fakeEnvironment"), + import("effect/Layer"), + ]); + return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; +}); + +vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ + ...(await original()), + trackRpcRequestSent: () => {}, +})); + +// The reverse of the board-thread probe in ThreadRouteView.browser.test.tsx: what that work must +// not have loosened for ordinary threads. Its own file, since the shell rows of a file's first +// test stay for the rest of it. +const HIDDEN_TAGS = ["private"]; +// The server's settings arrive after the first paint, so the filter takes a moment to apply. +const SETTLED = { timeout: 10_000 }; + +it("still opens an ordinary thread with the tag filter on, and still keeps a hidden or an archived one closed", async () => { + const listed = threadWithHistory("ordinary-listed", 1); + const other = threadWithHistory("ordinary-other", 1); + const tagged: FakeThread = { ...threadWithHistory("ordinary-tagged", 1), tags: HIDDEN_TAGS }; + const archived: FakeThread = { ...threadWithHistory("ordinary-archived", 1), archived: true }; + using _environment = installFakeEnvironment([listed, other, tagged, archived], { + hiddenThreadTags: HIDDEN_TAGS, + }); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${listed.id}`] }), + ); + await router.load(); + // AppRoot brings its own router. + await using _app = await render(, { router: false }); + const sidebarRows = () => + Array.from(document.querySelectorAll("[data-thread-item]"), (row) => + row.getAttribute("data-thread-item"), + ); + const open = (thread: FakeThread) => + act(() => + router.navigate({ + to: "/$environmentId/$threadId", + params: { environmentId: ENVIRONMENT_ID, threadId: thread.id }, + }), + ); + const pathname = () => router.state.location.pathname; + + await expect.element(page.getByText("ordinary-listed: question 0")).toBeVisible(); + // The tagged thread's row leaving the sidebar says the filter is in force. + await expect + .poll(sidebarRows, SETTLED) + .toEqual([expect.stringContaining(listed.id), expect.stringContaining(other.id)]); + + await open(other); + await expect.element(page.getByText("ordinary-other: question 0")).toBeVisible(); + expect(pathname()).toBe(`/${ENVIRONMENT_ID}/${other.id}`); + + // Hidden by its tag: its address does not open it. + await open(tagged); + await expect.poll(pathname, SETTLED).toBe("/"); + expect(document.body.textContent).not.toContain("ordinary-tagged: question 0"); + + // Archived, and not server-owned: it is restored from the archive, not opened by id. + await open(archived); + await expect.poll(pathname, SETTLED).toBe("/"); + expect(document.body.textContent).not.toContain("ordinary-archived: question 0"); +}); diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index 48b86b8ddfe56..7afd2ac017386 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -2,7 +2,7 @@ import { useAtomValue } from "@effect/atom-react"; import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment"; import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entities"; import { visibilityParentKey } from "@t3tools/client-runtime/state/threads"; -import type { ScopedThreadRef } from "@t3tools/contracts"; +import { isServerOwnedThreadLineage, type ScopedThreadRef } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { Navigate, useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; @@ -120,12 +120,20 @@ export function ThreadRouteView({ ); const hidingAnywhere = useAnyEnvironmentHiding(); const draftRedirectShell = useQuietThreadShell(draftRedirect ?? null); - const hiddenByTagFilter = serverThreadRef !== null && hiddenKeys.has(threadKey(serverThreadRef)); + // Server-owned work, such as a board task's conversation, has no parent and no row in any list, + // so its lineage alone opens it, whatever its tags: the shell never sends it, its id is the only + // way in, and the tag filter hides rows of lists it is not in. Opening one brings its row in. + const serverOwned = + (serverThreadShell !== null && isServerOwnedThreadLineage(serverThreadShell.lineage)) || + (unlistedThread !== null && isServerOwnedThreadLineage(unlistedThread.lineage)); + const hiddenByTagFilter = + serverThreadRef !== null && !serverOwned && hiddenKeys.has(threadKey(serverThreadRef)); // Cached detail can predate a tag or an archive, so while hiding an off-shell thread opens only // as the child of a loaded, visible parent (lineage never changes); anything else stays closed. const offShellBlocked = hidingAnywhere && unlistedThreadRef !== null && + !serverOwned && !( unlistedParentKey !== null && unlistedParentShell !== null && diff --git a/apps/web/src/components/chat/ComposerArchivedThread.tsx b/apps/web/src/components/chat/ComposerArchivedThread.tsx new file mode 100644 index 0000000000000..5ca35c5540583 --- /dev/null +++ b/apps/web/src/components/chat/ComposerArchivedThread.tsx @@ -0,0 +1,21 @@ +import { msg } from "gt-react"; +import { ArchiveIcon } from "lucide-react"; + +import { m, type MessageResolver } from "../../i18n/messages"; + +import type { ComposerBannerStackItem } from "./ComposerBannerStack"; + +/** Why an archived thread's composer sends nothing: the server refuses every message to it. */ +export function archivedThreadSendBlockReason(resolve: MessageResolver = m) { + return resolve(msg("This thread is archived and cannot receive messages.")); +} + +/** Shown above the composer of an archived thread, which opens to read and takes no message. */ +export function archivedThreadBannerItem(resolve: MessageResolver = m): ComposerBannerStackItem { + return { + id: "archived-thread", + variant: "info", + icon: , + title: archivedThreadSendBlockReason(resolve), + }; +} diff --git a/apps/web/src/components/delivery/TaskConversation.browser.test.tsx b/apps/web/src/components/delivery/TaskConversation.browser.test.tsx index aa73c1cfb2056..2a1d4d5999e0f 100644 --- a/apps/web/src/components/delivery/TaskConversation.browser.test.tsx +++ b/apps/web/src/components/delivery/TaskConversation.browser.test.tsx @@ -1,17 +1,26 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { useEffect } from "react"; import { page } from "vite-plus/test/browser"; -import { expect, it, vi } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; import "~/index.css"; -import { render } from "../../../test/render"; +import { act, fakeTimers, render } from "../../../test/render"; import { parseTask } from "../../lib/delivery"; +import type { SeatThread } from "../../lib/taskConversation"; import { useThreadInspection } from "../chat/ThreadInspectionContext"; import { TaskConversation } from "./TaskConversation"; +import { SEAT_LINKED_VIEW_DELAY_MS, useSteadySeat } from "./useTaskConversation"; + +/** Every thread the direct view was mounted for, in order. */ +const mountedThreads: string[] = []; vi.mock("../ChatView", () => ({ default: ({ threadId }: { threadId: string }) => { const inspect = useThreadInspection(); + useEffect(() => { + mountedThreads.push(threadId); + }, [threadId]); return (

Thread view {threadId}

@@ -31,6 +40,13 @@ vi.mock("../ChatView", () => ({ }, })); +// The read-only view of a linked environment's thread, which reads over the task's connection. +vi.mock("../chat/LinkedThreadPane", () => ({ + LinkedThread: ({ surface }: { surface: { threadId: string } }) => ( +

Linked view of {surface.threadId}

+ ), +})); + const ref = { environmentId: EnvironmentId.make("env-1"), threadId: ThreadId.make("lead-thread") }; const task = (extra: Record = {}) => { @@ -50,6 +66,7 @@ const task = (extra: Record = {}) => { const idle = { seat: null, + seatResolving: false, seatName: null, onOpenThread: () => {}, onBackToTask: () => {}, @@ -142,3 +159,93 @@ it("hands a thread the conversation opens to the view, and offers the way back f await page.getByRole("button", { name: "Back to task #12" }).click(); expect(onBackToTask).toHaveBeenCalledOnce(); }); + +describe("a seat in a linked environment", () => { + const remote = EnvironmentId.make("env-remote"); + const direct = { environmentId: remote, threadId: ThreadId.make("seat-thread") }; + const linked = { ...direct, linked: { viaEnvironmentId: ref.environmentId, label: "Desktop" } }; + const loading = { certain: false, connected: false }; + const loaded = { certain: true, connected: false }; + const online = { certain: true, connected: true }; + + // The hook and the view together, as TaskWorkspace wires them. + function Seat(props: { + readonly resolved: SeatThread; + readonly reach: { readonly certain: boolean; readonly connected: boolean }; + }) { + const { seat, resolving } = useSteadySeat(props.resolved, props.reach); + return ( + + ); + } + + it("waits for the links before it mounts either view, and never shows the task's own thread", async () => { + mountedThreads.length = 0; + await using screen = await render(); + await expect.element(screen.getByText("Seat qa")).toBeVisible(); + await expect.element(screen.getByText("Loading the conversation...")).toBeVisible(); + await screen.rerender(); + await expect.element(screen.getByText("Linked view of seat-thread")).toBeVisible(); + expect(mountedThreads).toEqual([]); + }); + + it("stays in the direct view, composer and all, while a saved environment that nothing links to is offline", async () => { + using _timers = fakeTimers(); + await using screen = await render(); + const composer = screen.getByRole("textbox", { name: "Composer" }); + await composer.fill("half a sentence"); + const element = composer.element(); + // Offline with no link: the links answer, and there is still nothing to read it through. + for (const reach of [loading, loaded]) { + await screen.rerender(); + await act(() => vi.advanceTimersByTime(SEAT_LINKED_VIEW_DELAY_MS * 3)); + expect(element.isConnected).toBe(true); + expect(document.activeElement).toBe(element); + } + // Back online: the same view, with what was typed. + await screen.rerender(); + expect((element as HTMLTextAreaElement).value).toBe("half a sentence"); + expect(document.body.textContent).not.toContain("Linked view"); + }); + + it("keeps the composer, its text and its focus through a reconnect, and moves to the linked view only when the connection stays down", async () => { + // The hook's wait is a timer, held here until the test moves it. + using _timers = fakeTimers(); + await using screen = await render(); + const composer = screen.getByRole("textbox", { name: "Composer" }); + await composer.fill("half a sentence"); + const element = composer.element(); + const untouched = () => + document.activeElement === element && + element.isConnected && + (element as HTMLTextAreaElement).value === "half a sentence"; + expect(untouched()).toBe(true); + + // The connection drops and the link answers: the linked view is only offered for later. + await screen.rerender(); + await act(() => vi.advanceTimersByTime(SEAT_LINKED_VIEW_DELAY_MS - 1)); + expect(untouched()).toBe(true); + // Back before the wait is over, and the wait does not carry into the next drop. + await screen.rerender(); + await act(() => vi.advanceTimersByTime(SEAT_LINKED_VIEW_DELAY_MS)); + expect(untouched()).toBe(true); + await screen.rerender(); + await act(() => vi.advanceTimersByTime(SEAT_LINKED_VIEW_DELAY_MS - 1)); + expect(untouched()).toBe(true); + + // It stays down: the read-only view through the link takes over. + await act(() => vi.advanceTimersByTime(1)); + await expect.element(screen.getByText("Linked view of seat-thread")).toBeVisible(); + expect(element.isConnected).toBe(false); + // Its own connection returns: the direct view is back at once. + await screen.rerender(); + await expect.element(screen.getByText("Thread view seat-thread")).toBeVisible(); + }); +}); diff --git a/apps/web/src/components/delivery/TaskConversation.tsx b/apps/web/src/components/delivery/TaskConversation.tsx index f697141adf87f..b2f1e2522cabc 100644 --- a/apps/web/src/components/delivery/TaskConversation.tsx +++ b/apps/web/src/components/delivery/TaskConversation.tsx @@ -145,6 +145,7 @@ function OpenConversation(props: { readonly thread: ScopedThreadRef; readonly offline: boolean; readonly seat: SeatThread | null; + readonly seatResolving: boolean; readonly seatName: string | null; readonly onOpenThread: (thread: ScopedThreadRef) => void; readonly onBackToTask: () => void; @@ -154,10 +155,16 @@ function OpenConversation(props: { const [view, setView] = useState<"conversation" | "log">("conversation"); const [attempt, setAttempt] = useState(0); const shown = props.seat ?? props.thread; + const inSeat = props.seat !== null || props.seatResolving; + const loading = ( +

+ {gt("Loading the conversation...")} +

+ ); return (
{props.offline ? (

) : null} - {props.seat ? ( + {inSeat ? ( ) : (

@@ -187,7 +194,11 @@ function OpenConversation(props: {
)} - {view === "log" && !props.seat ? ( + {props.seat === null && props.seatResolving ? ( + // The seat is open but its links are not known yet. The task's own conversation is not + // shown in its place, and neither view is mounted only to be swapped for the other. + loading + ) : view === "log" && !inSeat ? ( props.log ) : ( @@ -197,13 +208,7 @@ function OpenConversation(props: { setAttempt((n) => n + 1)} /> } > - - {gt("Loading the conversation...")} -

- } - > +
{props.seat?.linked ? ( @@ -243,6 +248,8 @@ export function TaskConversation(props: { readonly task: TaskView; readonly state: ConversationState; readonly seat: SeatThread | null; + /** A seat is open but cannot be placed yet. */ + readonly seatResolving: boolean; readonly seatName: string | null; readonly onOpenThread: (thread: ScopedThreadRef) => void; readonly onBackToTask: () => void; @@ -272,6 +279,7 @@ export function TaskConversation(props: { thread={state.ref} offline={state.offline} seat={props.seat} + seatResolving={props.seatResolving} seatName={props.seatName} onOpenThread={props.onOpenThread} onBackToTask={props.onBackToTask} diff --git a/apps/web/src/components/delivery/TaskWorkspace.tsx b/apps/web/src/components/delivery/TaskWorkspace.tsx index ea935dfcd0a5f..ce57c7d459907 100644 --- a/apps/web/src/components/delivery/TaskWorkspace.tsx +++ b/apps/web/src/components/delivery/TaskWorkspace.tsx @@ -2325,6 +2325,7 @@ export function TaskWorkspace(props: { task={task} state={conversation.state} seat={conversation.seat} + seatResolving={conversation.seatResolving} seatName={conversation.seatName} onOpenThread={openInCentre} onBackToTask={conversation.backToTask} diff --git a/apps/web/src/components/delivery/useTaskConversation.ts b/apps/web/src/components/delivery/useTaskConversation.ts index f68e261f79f95..0df82899cb404 100644 --- a/apps/web/src/components/delivery/useTaskConversation.ts +++ b/apps/web/src/components/delivery/useTaskConversation.ts @@ -1,23 +1,62 @@ import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import type { TaskView } from "../../lib/delivery"; import { conversationState, openSeatThread, + sameSeatView, sameThread, seatConversation, seatOfThread, + steadySeatThread, taskConversation, + type SeatCertainty, type SeatReach, type SeatThread, } from "../../lib/taskConversation"; import { useEnvironment, useEnvironments } from "../../state/environments"; import { useQuietThreadProjection } from "../../state/entities"; -import { useLinkedEnvironments } from "../../state/peerLinks"; +import { useLinkedEnvironmentsRead } from "../../state/peerLinks"; const NO_CHILDREN: ReadonlyArray = []; +/** + * How long this client's connection to a seat's environment may stay down before the open seat + * moves to the read-only view through the link. A reconnect is usually over well inside it. + */ +export const SEAT_LINKED_VIEW_DELAY_MS = 10_000; + +const seatViewKey = (seat: SeatThread) => + `${seat.environmentId}:${seat.threadId}:${seat.linked?.viaEnvironmentId ?? ""}`; + +/** + * The seat the centre shows, held steady while the links load and through a short reconnect: see + * `steadySeatThread`. `resolving` is a seat that was opened and cannot be placed yet. + */ +export function useSteadySeat( + resolved: SeatThread | null, + reach: SeatCertainty, +): { readonly seat: SeatThread | null; readonly resolving: boolean } { + const [shown, setShown] = useState(null); + // The view whose wait is over. Kept by key, so a wait that ended for one view moves no other. + const [waitedFor, setWaitedFor] = useState(null); + const steady = steadySeatThread(shown, resolved, reach); + const later = steady.kind === "shown" ? (steady.later ?? null) : null; + const laterKey = later === null ? null : seatViewKey(later); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a timer: the linked view replaces the direct one only after the connection has stayed down this long + useEffect(() => { + if (laterKey === null) return; + const timer = setTimeout(() => setWaitedFor(laterKey), SEAT_LINKED_VIEW_DELAY_MS); + return () => clearTimeout(timer); + }, [laterKey]); + const seat = + steady.kind !== "shown" ? null : later !== null && waitedFor === laterKey ? later : steady.seat; + if (!sameSeatView(seat, shown)) setShown(seat); + if (laterKey === null && waitedFor !== null) setWaitedFor(null); + return { seat, resolving: steady.kind === "resolving" }; +} + /** * The task's conversation for the task view: what the centre shows, which seat conversation is * open in it, and the seat rows that open one. Everything the engine does not tell us yet is read @@ -35,7 +74,7 @@ export function useTaskConversation(task: TaskView | null) { return own && { connected: own.connection.phase === "connected" }; }; // Links are read only while a seat runs somewhere this client is not connected to. - const links = useLinkedEnvironments( + const links = useLinkedEnvironmentsRead( ref !== null && children.some( (child) => @@ -46,9 +85,19 @@ export function useTaskConversation(task: TaskView | null) { ? ref.environmentId : null, ); - const reach: SeatReach = { ownConnection, isLinked: (id) => links.has(id) }; + const reach: SeatReach = { ownConnection, isLinked: (id) => links.names.has(id) }; const [opened, setSeat] = useState(null); - const seat: SeatThread | null = openSeatThread(ref, children, opened, reach); + const resolved = openSeatThread(ref, children, opened, reach); + const connected = resolved !== null && ownConnection(resolved.environmentId)?.connected === true; + const { seat, resolving } = useSteadySeat(resolved, { + connected, + // A seat in the task's own environment needs no link, and an environment that is not + // reachable cannot be asked for its links, nor read through one. + certain: + connected || resolved?.environmentId === ref?.environmentId || links.settled || !reachable, + }); + // A seat still being placed is the open one, so its row and its name do not wait. + const current: SeatThread | null = seat ?? (resolving ? opened : null); // A seat's thread, or the task's own: what a lineage link or a seat row asks to open. const open = (thread: ScopedThreadRef) => setSeat(sameThread(thread, ref) ? null : thread); @@ -57,12 +106,14 @@ export function useTaskConversation(task: TaskView | null) { state: conversationState(conversation, reachable), ref, seat, - seatName: seatOfThread(ref, children, seat), + /** A seat is open but cannot be placed yet: the centre waits instead of showing the task. */ + seatResolving: resolving, + seatName: seatOfThread(ref, children, current), open, backToTask: () => setSeat(null), seats: { thread: (name: string) => seatConversation(ref, children, name, reach), - current: seat, + current, open, }, }; diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts b/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts index c42c375a5e154..9342e8458c476 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts +++ b/apps/web/src/components/settings/ProjectSettingsPanel.logic.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { EnvironmentId, ProjectId, SourceControlProviderKind, ThreadId } from "@t3tools/contracts"; -import { planProjectRemoval } from "@t3tools/client-runtime/state/projects"; +import { planProjectRemoval, serverOwnedThreadCount } from "@t3tools/client-runtime/state/projects"; import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping"; import type { Project } from "../../types"; @@ -140,6 +140,51 @@ describe("project removal confirmation", () => { ); }); + it("says how many board task conversations a removal archives, which no list shows", () => { + const boardTask = { ...listed, engineIntake: "board-task:board-1:task-7" }; + const held = { environmentId: local.environmentId, projectId: local.id, lineage: boardTask }; + // Each environment counts its own projects, and these two share a project id. + const counted = (count: number) => (environmentId: EnvironmentId) => [ + { projectId: local.id, count: environmentId === local.environmentId ? count : 9 }, + ]; + // The shell leaves these rows out and counts them, so the count is all the client has. + expect(serverOwnedThreadCount({ members: [local], counted: counted(3), threads: [] })).toBe(3); + // A row that came in since as a delta is one of the counted, or newer than the count. + expect( + serverOwnedThreadCount({ members: [local], counted: counted(1), threads: [held, held] }), + ).toBe(2); + // A server that does not count sends every row. + expect( + serverOwnedThreadCount({ members: [local], counted: () => undefined, threads: [held] }), + ).toBe(1); + expect( + serverOwnedThreadCount({ members: [local, remote], counted: counted(3), threads: [] }), + ).toBe(12); + + const plan = planProjectRemoval({ + members: [local], + groupMemberCount: 1, + hasOtherMembers: false, + displayName: "Repo", + threads: [{ environmentId: local.environmentId, projectId: local.id, lineage: listed }, held], + serverOwnedThreadCount: 3, + }); + expect(plan.confirmationMessage).toBe( + 'Remove project "Repo" and delete its 1 thread?\nPath: /work/repo\nEnvironment: Local\nThose threads and any archived threads are deleted from T3 Code. Provider sessions are kept.\n3 conversations started by a board or the engine are archived, not deleted. Board and engine conversations already archived are kept.\nThis removes only the project entries, not the files on disk.\nThis action cannot be undone.', + ); + // With no listed thread the line still shows: it is the only sign these exist. + expect( + planProjectRemoval({ + members: [local], + groupMemberCount: 1, + hasOtherMembers: false, + displayName: "Repo", + threads: [], + serverOwnedThreadCount: 1, + }).confirmationMessage, + ).toContain("1 conversation started by a board or the engine is archived, not deleted."); + }); + 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 c4ed6e4ff33b1..c72347248acc3 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx @@ -63,7 +63,7 @@ import { scopeProjectSettingsGroup, } from "./ProjectSettingsPanel.logic"; import { useSettingsProjectGroups } from "./useSettingsProjectGroups"; -import { readUnloadedThreadCount } from "../../state/olderSettledShelf"; +import { readServerOwnedThreadCount, readUnloadedThreadCount } from "../../state/olderSettledShelf"; import { settingsScopeEnvironmentLabels } from "./settingsScopeAxis"; const ProjectIconPickerDialog = lazy(() => @@ -367,6 +367,7 @@ function ProjectDetail({ displayName: group.displayName, threads, unloadedThreadCount: readUnloadedThreadCount(members, threads), + serverOwnedThreadCount: readServerOwnedThreadCount(members, threads), }, resolveMessage, ); diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 8da62e9688376..a78cbae36068a 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -723,6 +723,8 @@ "bac5ef48aafb20b1": "Dadurch werden {count} gruppierte Projekteinträge entfernt.", "3e46fbf3eadf0745": "Diese Threads und alle archivierten Threads werden aus T3 Code gelöscht. Anbietersitzungen bleiben erhalten.", "1a50cbc984f8fe1c": "Alle archivierten Threads werden aus T3 Code gelöscht. Anbietersitzungen bleiben erhalten.", + "361080ce34c8e8ed": "{count, plural, one {{count} von einem Board oder der Engine gestartetes Gespräch wird archiviert, nicht gelöscht.} other {{count} von einem Board oder der Engine gestartete Gespräche werden archiviert, nicht gelöscht.}} Bereits archivierte Board- und Engine-Gespräche bleiben erhalten.", + "fea770db813e04c2": "Dieser Thread ist archiviert und kann keine Nachrichten empfangen.", "4f076ebbf1c8846e": "Dadurch werden nur die Projekteinträge entfernt, nicht die Dateien auf der Festplatte.", "19b8f3ad79efb9e1": "Andere Einträge in diesem gruppierten Projekt sind nicht betroffen.", "2207c69b042b2e37": "Diese Aktion kann nicht rückgängig gemacht werden.", @@ -2944,7 +2946,7 @@ "62b07b6189c49945": "Prüfungen", "e0b8b2689450b31f": "Review", "09cb08818ce2de09": "QA", - "4cd3443ad230b1a6": "Phase nicht bekannt", + "4cd3443ad230b1a6": "Phase unbekannt", "0701fbd09730561e": "Entwürfe", "13863c07e8d9e46c": "Team-Chats", "f3686a9b71b11789": "Warteschlange", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 1f425765a1fb6..cadb6c9682c8c 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -723,6 +723,8 @@ "bac5ef48aafb20b1": "This removes {count} grouped project entries.", "3e46fbf3eadf0745": "Those threads and any archived threads are deleted from T3 Code. Provider sessions are kept.", "1a50cbc984f8fe1c": "Any archived threads are deleted from T3 Code. Provider sessions are kept.", + "361080ce34c8e8ed": "{count, plural, one {{count} conversation started by a board or the engine is archived, not deleted.} other {{count} conversations started by a board or the engine are archived, not deleted.}} Board and engine conversations already archived are kept.", + "fea770db813e04c2": "This thread is archived and cannot receive messages.", "4f076ebbf1c8846e": "This removes only the project entries, not the files on disk.", "19b8f3ad79efb9e1": "Other entries in this grouped project are unaffected.", "2207c69b042b2e37": "This action cannot be undone.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 892e4ecbf3736..43221088433c0 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -723,6 +723,8 @@ "bac5ef48aafb20b1": "Esto quita {count} entradas de proyecto agrupadas.", "3e46fbf3eadf0745": "Esos hilos y los hilos archivados se eliminan de T3 Code. Las sesiones del proveedor se conservan.", "1a50cbc984f8fe1c": "Los hilos archivados se eliminan de T3 Code. Las sesiones del proveedor se conservan.", + "361080ce34c8e8ed": "{count, plural, one {{count} conversación iniciada por un tablero o por el motor se archiva, no se elimina.} other {{count} conversaciones iniciadas por un tablero o por el motor se archivan, no se eliminan.}} Las conversaciones de tableros y del motor ya archivadas se conservan.", + "fea770db813e04c2": "Este hilo está archivado y no puede recibir mensajes.", "4f076ebbf1c8846e": "Esto solo quita las entradas del proyecto, no los archivos del disco.", "19b8f3ad79efb9e1": "Las demás entradas de este proyecto agrupado no se ven afectadas.", "2207c69b042b2e37": "Esta acción no se puede deshacer.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 7d7a93e682e1f..56d9ba529d20b 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -723,6 +723,8 @@ "bac5ef48aafb20b1": "Cela retire {count} entrées de projet regroupées.", "3e46fbf3eadf0745": "Ces fils et tous les fils archivés sont supprimés de T3 Code. Les sessions du fournisseur sont conservées.", "1a50cbc984f8fe1c": "Tous les fils archivés sont supprimés de T3 Code. Les sessions du fournisseur sont conservées.", + "361080ce34c8e8ed": "{count, plural, one {{count} conversation lancée par un tableau ou par le moteur est archivée, pas supprimée.} other {{count} conversations lancées par un tableau ou par le moteur sont archivées, pas supprimées.}} Les conversations de tableaux et du moteur déjà archivées sont conservées.", + "fea770db813e04c2": "Ce fil est archivé et ne peut pas recevoir de messages.", "4f076ebbf1c8846e": "Cela retire uniquement les entrées de projet, pas les fichiers sur le disque.", "19b8f3ad79efb9e1": "Les autres entrées de ce projet regroupé ne sont pas affectées.", "2207c69b042b2e37": "Cette action est irréversible.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index fce86494edfa3..58b37026d557d 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -723,6 +723,8 @@ "bac5ef48aafb20b1": "グループ化された {count} 件のプロジェクトエントリを削除します。", "3e46fbf3eadf0745": "それらのスレッドとアーカイブ済みのスレッドは T3 Code から削除されます。プロバイダーのセッションは保持されます。", "1a50cbc984f8fe1c": "アーカイブ済みのスレッドは T3 Code から削除されます。プロバイダーのセッションは保持されます。", + "361080ce34c8e8ed": "{count, plural, other {ボードまたはエンジンが開始した会話 {count} 件はアーカイブされ、削除されません。}}すでにアーカイブ済みのボードおよびエンジンの会話は保持されます。", + "fea770db813e04c2": "このスレッドはアーカイブ済みのため、メッセージを受信できません。", "4f076ebbf1c8846e": "削除されるのはプロジェクトのエントリだけで、ディスク上のファイルは削除されません。", "19b8f3ad79efb9e1": "このグループ化されたプロジェクト内の他のエントリには影響しません。", "2207c69b042b2e37": "この操作は元に戻せません。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 5981c5d08e0a7..d0b8a743bd720 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -723,6 +723,8 @@ "bac5ef48aafb20b1": "그룹화된 프로젝트 항목 {count}개를 제거합니다.", "3e46fbf3eadf0745": "해당 스레드와 보관된 스레드는 T3 Code에서 삭제됩니다. 제공자 세션은 유지됩니다.", "1a50cbc984f8fe1c": "보관된 스레드는 T3 Code에서 삭제됩니다. 제공자 세션은 유지됩니다.", + "361080ce34c8e8ed": "{count, plural, other {보드 또는 엔진이 시작한 대화 {count}개는 삭제되지 않고 보관됩니다.}} 이미 보관된 보드 및 엔진 대화는 그대로 유지됩니다.", + "fea770db813e04c2": "이 스레드는 보관되어 메시지를 받을 수 없습니다.", "4f076ebbf1c8846e": "디스크의 파일이 아닌 프로젝트 항목만 제거합니다.", "19b8f3ad79efb9e1": "이 그룹화된 프로젝트의 다른 항목은 영향을 받지 않습니다.", "2207c69b042b2e37": "이 작업은 되돌릴 수 없습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 65350ebe06a38..e56ec30d7efb0 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -723,6 +723,8 @@ "bac5ef48aafb20b1": "Isto remove {count} entradas de projeto agrupadas.", "3e46fbf3eadf0745": "Essas threads e as threads arquivadas são excluídas do T3 Code. As sessões do provedor são mantidas.", "1a50cbc984f8fe1c": "As threads arquivadas são excluídas do T3 Code. As sessões do provedor são mantidas.", + "361080ce34c8e8ed": "{count, plural, one {{count} conversa iniciada por um quadro ou pelo motor é arquivada, não excluída.} other {{count} conversas iniciadas por um quadro ou pelo motor são arquivadas, não excluídas.}} As conversas de quadros e do motor já arquivadas são mantidas.", + "fea770db813e04c2": "Esta thread está arquivada e não pode receber mensagens.", "4f076ebbf1c8846e": "Isto remove apenas as entradas do projeto, não os arquivos no disco.", "19b8f3ad79efb9e1": "As outras entradas deste projeto agrupado não são afetadas.", "2207c69b042b2e37": "Esta ação não pode ser desfeita.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 5a56c2baa1d1f..9e0f129145336 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -723,6 +723,8 @@ "bac5ef48aafb20b1": "Будут удалены сгруппированные записи проекта: {count}.", "3e46fbf3eadf0745": "Эти треды и все архивные треды будут удалены из T3 Code. Сеансы провайдера сохранятся.", "1a50cbc984f8fe1c": "Все архивные треды будут удалены из T3 Code. Сеансы провайдера сохранятся.", + "361080ce34c8e8ed": "{count, plural, one {{count} разговор, начатый доской или движком, будет архивирован, а не удалён.} few {{count} разговора, начатых доской или движком, будут архивированы, а не удалены.} many {{count} разговоров, начатых доской или движком, будут архивированы, а не удалены.} other {{count} разговора, начатых доской или движком, будут архивированы, а не удалены.}} Уже архивированные разговоры досок и движка сохранятся.", + "fea770db813e04c2": "Этот тред в архиве и не может получать сообщения.", "4f076ebbf1c8846e": "Удаляются только записи проекта, а не файлы на диске.", "19b8f3ad79efb9e1": "Другие записи в этом сгруппированном проекте не затрагиваются.", "2207c69b042b2e37": "Это действие нельзя отменить.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index be4490cb8c331..e5e48d2ba7e36 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -723,6 +723,8 @@ "bac5ef48aafb20b1": "Det här tar bort {count} grupperade projektposter.", "3e46fbf3eadf0745": "De trådarna och eventuella arkiverade trådar tas bort från T3 Code. Leverantörssessioner behålls.", "1a50cbc984f8fe1c": "Eventuella arkiverade trådar tas bort från T3 Code. Leverantörssessioner behålls.", + "361080ce34c8e8ed": "{count, plural, one {{count} konversation som startats av en tavla eller motorn arkiveras, den tas inte bort.} other {{count} konversationer som startats av en tavla eller motorn arkiveras, de tas inte bort.}} Redan arkiverade konversationer från tavlor och motorn behålls.", + "fea770db813e04c2": "Den här tråden är arkiverad och kan inte ta emot meddelanden.", "4f076ebbf1c8846e": "Det här tar bara bort projektposterna, inte filerna på disken.", "19b8f3ad79efb9e1": "Andra poster i det här grupperade projektet påverkas inte.", "2207c69b042b2e37": "Den här åtgärden kan inte ångras.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 1dd02d2dc9792..3a81d633db38b 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -723,6 +723,8 @@ "bac5ef48aafb20b1": "将移除 {count} 个已分组的项目条目。", "3e46fbf3eadf0745": "这些会话及所有已归档会话将从 T3 Code 中删除。提供方自身保存的对话记录会保留。", "1a50cbc984f8fe1c": "所有已归档会话将从 T3 Code 中删除。提供方自身保存的对话记录会保留。", + "361080ce34c8e8ed": "{count, plural, other {由看板或引擎发起的 {count} 个对话将被归档,不会删除。}}已归档的看板和引擎对话会保留。", + "fea770db813e04c2": "此会话已归档,无法接收消息。", "4f076ebbf1c8846e": "仅移除项目条目,磁盘上的文件会保留。", "19b8f3ad79efb9e1": "此项目组中的其他条目不受影响。", "2207c69b042b2e37": "此操作无法撤销。", diff --git a/apps/web/src/lib/taskConversation.test.ts b/apps/web/src/lib/taskConversation.test.ts index 756c2d556fc89..dd84687cfd737 100644 --- a/apps/web/src/lib/taskConversation.test.ts +++ b/apps/web/src/lib/taskConversation.test.ts @@ -7,6 +7,7 @@ import { openSeatThread, seatConversation, seatOfThread, + steadySeatThread, taskConversation, } from "./taskConversation"; @@ -141,6 +142,79 @@ describe("a seat's conversation", () => { }); }); +describe("an open seat's view, held steady", () => { + const remote = EnvironmentId.make("env-remote"); + const direct = { environmentId: remote, threadId: ThreadId.make("child-b") }; + const linked = { ...direct, linked: { viaEnvironmentId: ref.environmentId, label: "Desktop" } }; + const loading = { certain: false, connected: false }; + const loaded = { certain: true, connected: false }; + const online = { certain: true, connected: true }; + + it("waits to place a newly opened seat until the links have loaded", () => { + // Saved but offline reads as direct, and unsaved as linked, before the links say which. + expect(steadySeatThread(null, direct, loading)).toEqual({ kind: "resolving" }); + expect(steadySeatThread(null, linked, loading)).toEqual({ kind: "resolving" }); + expect(steadySeatThread(null, linked, loaded)).toEqual({ kind: "shown", seat: linked }); + expect(steadySeatThread(null, direct, loaded)).toEqual({ kind: "shown", seat: direct }); + // This client's own connection needs no link, so it never waits. + expect(steadySeatThread(null, direct, online)).toEqual({ kind: "shown", seat: direct }); + // Another seat opened over this one is placed afresh, not swapped in under the old view. + const other = { ...direct, threadId: ThreadId.make("child-z") }; + expect(steadySeatThread(other, direct, loading)).toEqual({ kind: "resolving" }); + }); + + it("keeps the direct view through a reconnect, and offers the linked view for later", () => { + // The connection drops: the links are asked for, and until they answer nothing changes. + expect(steadySeatThread(direct, direct, loading)).toEqual({ kind: "shown", seat: direct }); + // They answer that a link exists. The direct view stays; the linked view waits its turn. + expect(steadySeatThread(direct, linked, loaded)).toEqual({ + kind: "shown", + seat: direct, + later: linked, + }); + // The connection is back before that turn comes: nothing was remounted. + expect(steadySeatThread(direct, direct, online)).toEqual({ kind: "shown", seat: direct }); + }); + + it("leaves the linked view at once for a connection of its own, not for links that reload", () => { + expect(steadySeatThread(linked, direct, online)).toEqual({ kind: "shown", seat: direct }); + expect(steadySeatThread(linked, direct, loading)).toEqual({ kind: "shown", seat: linked }); + // The link is really gone and the environment is saved: it opens in place, offline. + expect(steadySeatThread(linked, direct, loaded)).toEqual({ kind: "shown", seat: direct }); + // A new name for the linked environment redraws the same view. + const renamed = { ...linked, linked: { ...linked.linked, label: "Workstation" } }; + expect(steadySeatThread(linked, renamed, loaded)).toEqual({ kind: "shown", seat: renamed }); + }); + + it("shows nothing once the seat is closed", () => { + expect(steadySeatThread(direct, null, online)).toEqual({ kind: "none" }); + }); + + it("keeps a seat open in place when its saved environment goes offline and nothing links to it", () => { + const children = [ + { + childThreadId: null, + remoteChild: { environmentId: remote, threadId: direct.threadId, label: "Desktop" }, + teamChat: { seat: "remote-qa" }, + }, + ]; + // What the connections say at each step, for a saved environment no link reaches. + const resolved = (connected: boolean) => + openSeatThread(ref, children, direct, { + ownConnection: () => ({ connected }), + isLinked: () => false, + }); + const open = steadySeatThread(null, resolved(true), online); + expect(open).toEqual({ kind: "shown", seat: direct }); + // Offline: the same view stays, where the app says it is offline and can reconnect. There + // is no linked view to move to, however long it lasts, and coming back changes nothing. + for (const reach of [loading, loaded]) { + expect(steadySeatThread(direct, resolved(false), reach)).toEqual(open); + } + expect(steadySeatThread(direct, resolved(true), online)).toEqual(open); + }); +}); + describe("why a task waits", () => { it("reports only the engine's place, and says when none was sent", () => { const queue = { position: 3, cap: 4, busy: 4, holders: [] }; diff --git a/apps/web/src/lib/taskConversation.ts b/apps/web/src/lib/taskConversation.ts index 855437b04834c..bd54e1fa86065 100644 --- a/apps/web/src/lib/taskConversation.ts +++ b/apps/web/src/lib/taskConversation.ts @@ -155,6 +155,54 @@ export function openSeatThread( return target ?? thread; } +/** Whether the open seat reads through a link (`linked`) or in its own environment (`direct`). */ +const seatMode = (seat: SeatThread) => (seat.linked === undefined ? "direct" : "linked"); + +/** Two targets that draw the same view: swapping one for the other remounts nothing. */ +export const sameSeatView = (a: SeatThread | null, b: SeatThread | null): boolean => + a === b || + (sameThread(a, b) && + a?.linked?.viaEnvironmentId === b?.linked?.viaEnvironmentId && + a?.linked?.label === b?.linked?.label); + +/** What the centre does with the seat a person opened. */ +export type SteadySeat = + | { readonly kind: "none" } + /** Opened, but how to reach it is not known yet. Nothing is mounted, so nothing is swapped. */ + | { readonly kind: "resolving" } + /** + * `later` is the read-only view to move to if this client's connection stays down. Until + * then the direct view stays, which says it is offline and keeps its composer and scroll. + */ + | { readonly kind: "shown"; readonly seat: SeatThread; readonly later?: SeatThread }; + +/** What decides whether an open seat's view may change now. */ +export interface SeatCertainty { + /** The answer does not rest on links that have not loaded yet. */ + readonly certain: boolean; + /** This client's own connection to the seat's environment is up. */ + readonly connected: boolean; +} + +/** + * Holds an open seat's view steady: the direct and the linked view are two components, so a swap + * remounts the conversation. `resolved` is what `openSeatThread` says now, which changes while + * links load and during a reconnect; `shown` is what the centre shows. + */ +export function steadySeatThread( + shown: SeatThread | null, + resolved: SeatThread | null, + reach: SeatCertainty, +): SteadySeat { + if (resolved === null) return { kind: "none" }; + if (shown === null || !sameThread(shown, resolved)) { + return reach.certain ? { kind: "shown", seat: resolved } : { kind: "resolving" }; + } + if (seatMode(shown) === seatMode(resolved)) return { kind: "shown", seat: resolved }; + if (seatMode(shown) === "direct") return { kind: "shown", seat: shown, later: resolved }; + return { kind: "shown", seat: reach.connected || reach.certain ? resolved : shown }; +} + /** * Why a task waits, as the engine reports it on the card. `place` is the engine's own position; * without one there is no place to show, and nothing is worked out. diff --git a/apps/web/src/state/olderSettledShelf.ts b/apps/web/src/state/olderSettledShelf.ts index e313c805dd3cc..3fec76b31b455 100644 --- a/apps/web/src/state/olderSettledShelf.ts +++ b/apps/web/src/state/olderSettledShelf.ts @@ -1,5 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import { serverOwnedThreadCount } from "@t3tools/client-runtime/state/projects"; import { isListedSettledThread, settledShelfFrontier, @@ -122,3 +123,19 @@ export function readUnloadedThreadCount( ), }); } + +/** + * Threads of these projects that the server started for itself, which the shell counts and does + * not send: see `serverOwnedThreadCount`. A project removal archives them. + */ +export function readServerOwnedThreadCount( + members: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly id: ProjectId }>, + threads: ReadonlyArray, +): number { + return serverOwnedThreadCount({ + members, + counted: (environmentId) => + appAtomRegistry.get(threadFamilies.snapshotAtom(environmentId))?.serverOwnedThreads, + threads, + }); +} diff --git a/apps/web/src/state/peerLinks.ts b/apps/web/src/state/peerLinks.ts index ab1d30a2791f8..08580c1f42105 100644 --- a/apps/web/src/state/peerLinks.ts +++ b/apps/web/src/state/peerLinks.ts @@ -47,6 +47,18 @@ const offersNoLinksAtom = Atom.make(false).pipe(Atom.withLabel("peer-links:offer export function useLinkedEnvironments( environmentId: EnvironmentId | null, ): ReadonlyMap { + return useLinkedEnvironmentsRead(environmentId).names; +} + +/** + * `useLinkedEnvironments`, with whether the list has its answer. While it loads the names are + * empty, which is not the same as no links: a caller that picks a view from them waits for + * `settled`. + */ +export function useLinkedEnvironmentsRead(environmentId: EnvironmentId | null): { + readonly names: ReadonlyMap; + readonly settled: boolean; +} { const offered = useAtomValue( environmentId === null ? offersNoLinksAtom : offersLinkedEnvironmentsAtom(environmentId), ); @@ -56,10 +68,14 @@ export function useLinkedEnvironments( ? peerLinkEnvironment.names({ environmentId, input: {} }) : null, ); - return linkedEnvironmentNames({ - links: offered ? (links.data?.links ?? []) : [], - environments: identities, - }); + return { + names: linkedEnvironmentNames({ + links: offered ? (links.data?.links ?? []) : [], + environments: identities, + }), + // Nothing to ask counts as answered, and so does a failed read: it will not say more. + settled: environmentId === null || !offered || links.isSuccess || links.error !== null, + }; } export function usePeerLinkHosts() { diff --git a/apps/web/src/threadRoutes.test.ts b/apps/web/src/threadRoutes.test.ts index c4fef5897c5f4..d36c1a74c651b 100644 --- a/apps/web/src/threadRoutes.test.ts +++ b/apps/web/src/threadRoutes.test.ts @@ -244,6 +244,30 @@ describe("threadRoutes", () => { }, ); + it("opens an archived board task's thread, which no archive list can restore", () => { + const projection = makeThreadProjectionFixture(); + const archivedAt = DateTime.makeUnsafe("2026-01-02T00:00:00Z"); + const boardTask = { + ...projection.thread, + archivedAt, + lineage: { ...projection.thread.lineage, engineIntake: "board-task:board-1:task-7" }, + }; + const stateOf = (thread: typeof boardTask) => + resolveThreadRouteRenderState({ + bootstrapComplete: true, + serverThreadExists: false, + serverThreadDeleted: false, + draftThreadExists: false, + unlistedThreadDetail: { + ...EMPTY_ENVIRONMENT_THREAD_STATE, + status: "live", + data: Option.some({ ...projection, thread }), + }, + }); + expect(stateOf(boardTask)).toBe("ready"); + expect(stateOf({ ...boardTask, deletedAt: archivedAt })).toBe("missing"); + }); + it("waits for the live shell before redirecting a deleted thread", () => { expect( resolveThreadRouteRenderState({ diff --git a/apps/web/src/threadRoutes.ts b/apps/web/src/threadRoutes.ts index a2047d4fe2e14..e94a0583e26e3 100644 --- a/apps/web/src/threadRoutes.ts +++ b/apps/web/src/threadRoutes.ts @@ -1,7 +1,12 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell"; import type { EnvironmentThreadState } from "@t3tools/client-runtime/state/threads"; -import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; +import { + isServerOwnedThreadLineage, + type EnvironmentId, + type ScopedThreadRef, + type ThreadId, +} from "@t3tools/contracts"; import * as Option from "effect/Option"; import type { DraftId } from "./composerDraftStore"; @@ -50,7 +55,11 @@ export function resolveThreadRouteRenderState(input: { if (projection === null) { return "loading"; } - return projection.thread.deletedAt !== null || projection.thread.archivedAt !== null + if (projection.thread.deletedAt !== null) return "missing"; + // An archived thread is restored from the archive before it opens. Server-owned work is in no + // archive list, so an archived board task's conversation still opens by id. + return projection.thread.archivedAt !== null && + !isServerOwnedThreadLineage(projection.thread.lineage) ? "missing" : "ready"; } diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index 9e311aad7cb7c..2b28e49f316bc 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -106,6 +106,7 @@ const decodeServerConfig = Schema.decodeUnknownSync(ServerConfig); const makeServerConfig = ( providers: ReadonlyArray, supportsIssues = false, + hiddenThreadTags: ReadonlyArray = [], ): ServerConfig => ({ ...decodeServerConfig({ environment: { @@ -125,7 +126,7 @@ const makeServerConfig = ( otlpTracesEnabled: false, otlpMetricsEnabled: false, }, - settings: {}, + settings: hiddenThreadTags.length === 0 ? {} : { hideTaggedThreads: true, hiddenThreadTags }, threadSnapshotPagination: true, threadResumeCompletionMarker: true, shellResumeCompletionMarker: true, @@ -231,10 +232,13 @@ export interface FakeThread { readonly providerSubagentOf?: ThreadId; /** Makes this an older settled thread the shell leaves out; only its family read returns it. */ readonly olderSettled?: true; - /** Marks this as server-owned work no thread list shows; the shell still carries it. */ + /** Marks this as server-owned work no thread list shows. Add `offShell` for what a server sends. */ readonly engineIntake?: string; - /** Leaves this out of the shell without settling it, so only a read by id finds it. */ + /** Leaves this out of the shell without settling it, so its family read or a read by id finds it. */ readonly offShell?: true; + /** Archives it: out of the shell and of every family, so only a read by id finds it. */ + readonly archived?: true; + readonly tags?: ReadonlyArray; readonly id: ThreadId; readonly title: string; /** Defaults to GPT-5.4 on Codex. */ @@ -332,6 +336,7 @@ function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { worktreePath: null, activeProviderThreadId: thread.providerThreads?.[0]?.id ?? null, ...(thread.issues === undefined ? {} : { issues: thread.issues }), + ...(thread.tags === undefined ? {} : { tags: thread.tags }), lineage: { rootThreadId: parentOf(thread) ?? thread.id, parentThreadId: parentOf(thread) ?? null, @@ -354,7 +359,7 @@ function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { visibleItemCount: thread.items.length, createdAt: AT, updatedAt: AT, - archivedAt: null, + archivedAt: thread.archived ? AT : null, settledOverride: thread.olderSettled ? "settled" : null, settledAt: thread.olderSettled ? AT : null, lastVisitedAt: AT, @@ -391,7 +396,8 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection { creationSource: shell.creationSource, createdAt: AT, updatedAt: AT, - archivedAt: null, + archivedAt: shell.archivedAt, + ...(shell.tags === undefined ? {} : { tags: shell.tags }), settledOverride: shell.settledOverride, settledAt: shell.settledAt, lastVisitedAt: AT, @@ -450,6 +456,27 @@ const subscribe = (first: ReadonlyArray, register?: (queue: Queue.Queue }), ); +type ConfigSnapshot = { + readonly version: 1; + readonly type: "snapshot"; + readonly config: ServerConfig; +}; +const configSnapshot = (): ConfigSnapshot => ({ + version: 1, + type: "snapshot", + config: serverConfig(), +}); +const configSubscribers = new Set>(); +const subscribeConfig = () => + subscribe([configSnapshot()], (queue) => { + configSubscribers.add(queue); + return () => configSubscribers.delete(queue); + }); +/** The connection outlives a test, so a scenario with its own settings sends them to it. */ +const pushConfig = () => { + for (const queue of configSubscribers) Effect.runSync(Queue.offer(queue, configSnapshot())); +}; + const handlers: Record unknown> = { // Recorded, and accepted only when the scenario asks, since a pending command holds every // later command on its thread. Accepted commands' events never arrive. @@ -503,7 +530,7 @@ const handlers: Record unknown> = { snapshotSequence: sequence, projects, threads: threads - .filter((thread) => !thread.olderSettled && !thread.offShell) + .filter((thread) => !thread.olderSettled && !thread.offShell && !thread.archived) .map(shellOf), archivedThreads: [], }, @@ -541,7 +568,9 @@ const handlers: Record unknown> = { return Effect.succeed({ snapshotSequence: sequence, threads: requested - ? threads.filter((thread) => rootOf(thread) === rootOf(requested)).map(shellOf) + ? threads + .filter((thread) => !thread.archived && rootOf(thread) === rootOf(requested)) + .map(shellOf) : [], }); }, @@ -552,8 +581,7 @@ const handlers: Record unknown> = { if (vcsStatusSubscriber === queue) vcsStatusSubscriber = null; }; }), - [WS_METHODS.subscribeServerConfig]: () => - subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig() }]), + [WS_METHODS.subscribeServerConfig]: () => subscribeConfig(), }; // Unanswered calls stay pending, like a server that has not replied yet. @@ -569,8 +597,7 @@ const client = new Proxy(handlers, { const session: EnvironmentConnectionLease["session"] = { client: client as unknown as WsRpcProtocolClient, initialConfig: Effect.sync(serverConfig), - subscribeServerConfig: () => - subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig() }]), + subscribeServerConfig: () => subscribeConfig(), ready: Effect.void, probe: Effect.void, inboundFrames: Effect.succeed(0), @@ -614,6 +641,8 @@ export function installFakeEnvironment( /** Commands left unanswered even when accepting, until `rejectPendingCommand`. */ readonly holdCommand?: (command: OrchestrationV2Command) => boolean; readonly providers?: ReadonlyArray; + /** Turns the tag filter on, hiding threads that carry one of these tags. */ + readonly hiddenThreadTags?: ReadonlyArray; }, ): Disposable { threads = fixtures; @@ -621,6 +650,7 @@ export function installFakeEnvironment( ...makeServerConfig( options?.providers ?? [CODEX_PROVIDER], fixtures.some((thread) => (thread.issues?.length ?? 0) > 0), + options?.hiddenThreadTags, ), keybindings: options?.keybindings ?? DEFAULT_RESOLVED_KEYBINDINGS, }; @@ -635,6 +665,8 @@ export function installFakeEnvironment( })), ]; holdCommand = options?.holdCommand ?? (() => false); + const ownSettings = (options?.hiddenThreadTags?.length ?? 0) > 0; + if (ownSettings) pushConfig(); globalThis.fetch = async (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), window.location.href); if (url.origin !== window.location.origin) return realFetch(input, init); @@ -663,6 +695,7 @@ export function installFakeEnvironment( holdCommand = () => false; pendingDispatches = []; pendingAssetUrls = []; + if (ownSettings) pushConfig(); }, }; } @@ -717,6 +750,21 @@ export function answerRpc(method: string, handler: (input: never) => unknown): D }; } +/** Sends a thread's row as a shell delta: how a change reaches a client whose shell left it out. */ +export async function emitShellThread(threadId: ThreadId): Promise { + const thread = threads.find((candidate) => candidate.id === threadId); + if (shellSubscriber === null || thread === undefined) throw new Error("No shell row to send"); + sequence += 1; + await Effect.runPromise( + Queue.offer(shellSubscriber, { + kind: "thread.updated", + sequence, + location: "active", + thread: shellOf(thread), + }), + ); +} + export async function emitTerminalMetadata(event: TerminalMetadataStreamEvent): Promise { if (terminalMetadataSubscriber === null) throw new Error("No terminal metadata subscription"); await Effect.runPromise(Queue.offer(terminalMetadataSubscriber, event)); diff --git a/packages/client-runtime/src/state/projectRemoval.ts b/packages/client-runtime/src/state/projectRemoval.ts index 002a6b33dca23..d8e0b473ea341 100644 --- a/packages/client-runtime/src/state/projectRemoval.ts +++ b/packages/client-runtime/src/state/projectRemoval.ts @@ -1,9 +1,49 @@ -import { isListedThreadLineage } from "@t3tools/contracts"; +import { + isListedThreadLineage, + isServerOwnedThreadLineage, + type EnvironmentId, + type OrchestrationV2ShellSnapshot, + type ProjectId, +} from "@t3tools/contracts"; import type { EnvironmentProject, EnvironmentThreadShell } from "./models.ts"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; +/** + * The threads of these projects that the server started for itself, such as a board task's + * conversation. The shell leaves their rows out and counts them instead, as of its last snapshot; + * a server that does not count sends every row, so the larger of the two is used. + */ +export function serverOwnedThreadCount(input: { + readonly members: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly id: ProjectId; + }>; + readonly counted: ( + environmentId: EnvironmentId, + ) => OrchestrationV2ShellSnapshot["serverOwnedThreads"]; + /** The rows this client holds. */ + readonly threads: ReadonlyArray< + Pick + >; +}): number { + let total = 0; + for (const member of input.members) { + const counted = + input.counted(member.environmentId)?.find((entry) => entry.projectId === member.id)?.count ?? + 0; + const held = input.threads.filter( + (thread) => + thread.environmentId === member.environmentId && + thread.projectId === member.id && + isServerOwnedThreadLineage(thread.lineage), + ).length; + total += Math.max(counted, held); + } + return total; +} + export function planProjectRemoval< Thread extends Pick, >( @@ -19,6 +59,8 @@ export function planProjectRemoval< readonly threads: ReadonlyArray; /** The members' threads this client does not hold: older settled threads its shell left out. */ readonly unloadedThreadCount?: number; + /** The members' server-owned threads, which are archived, not deleted: `serverOwnedThreadCount`. */ + readonly serverOwnedThreadCount?: number; }, resolve: MFunctionType = mFallback, ) { @@ -31,6 +73,7 @@ export function planProjectRemoval< const threadCount = projectThreads.filter((thread) => isListedThreadLineage(thread.lineage)).length + (options.unloadedThreadCount ?? 0); + const keptCount = options.serverOwnedThreadCount ?? 0; const isWholeGroup = members.length === groupMemberCount; const targetKind = hasOtherMembers || !isWholeGroup ? "checkout" : "project"; const singleMember = members.length === 1 ? members[0]! : null; @@ -80,6 +123,18 @@ export function planProjectRemoval< msg("Any archived threads are deleted from T3 Code. Provider sessions are kept."), ), ]), + // No list shows these, so this line is the only place a person learns they exist. Its last + // sentence is the exception to "any archived threads are deleted" above. + ...(keptCount > 0 + ? [ + resolve( + msg( + "{count, plural, one {{count} conversation started by a board or the engine is archived, not deleted.} other {{count} conversations started by a board or the engine are archived, not deleted.}} Board and engine conversations already archived are kept.", + { count: keptCount }, + ), + ), + ] + : []), 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/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index b937f46c64f5a..7e96ecb31f199 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2513,6 +2513,12 @@ export const OrchestrationV2ShellSnapshot = Schema.Struct({ ...OrchestrationV2ThreadShellSnapshot.fields, projects: Schema.Array(OrchestrationProjectShell), olderSettled: Schema.optionalKey(OrchestrationV2OlderSettledThreads), + /** + * Per project, the active threads carrying the server-owned marker, sent or not (their seats + * and side chats are not counted). No list shows them, so this is how a client can say a + * project has them. Exact at `snapshotSequence`; absent when there are none. + */ + serverOwnedThreads: Schema.optionalKey(Schema.Array(OrchestrationV2OlderSettledCount)), }); export type OrchestrationV2ShellSnapshot = typeof OrchestrationV2ShellSnapshot.Type; @@ -4152,8 +4158,9 @@ export const OrchestrationV2SubscribeShellInput = Schema.Struct({ knownProjectIdentities: Schema.optionalKey(Schema.String), requestCompletionMarker: Schema.optionalKey(Schema.Boolean), /** - * Snapshots leave out idle subagent children; read them with `getThreadFamily`. Send only to - * servers that advertise `shellThreadFamilies`. + * Snapshots leave out idle subagent children and server-owned threads with their families (see + * `isServerOwnedThreadLineage`); read them with `getThreadFamily`. Send only to servers that + * advertise `shellThreadFamilies`. */ omitIdleSubagents: Schema.optionalKey(Schema.Boolean), /**